Path: blob/1.0-develop/app/Http/Controllers/Api/Remote/ActivityProcessingController.php
10284 views
<?php12namespace Pterodactyl\Http\Controllers\Api\Remote;34use Carbon\Carbon;5use Illuminate\Support\Str;6use Pterodactyl\Models\User;7use Webmozart\Assert\Assert;8use Pterodactyl\Models\Server;9use Illuminate\Support\Facades\Log;10use Pterodactyl\Models\ActivityLog;11use Pterodactyl\Models\ActivityLogSubject;12use Pterodactyl\Http\Controllers\Controller;13use Pterodactyl\Http\Requests\Api\Remote\ActivityEventRequest;1415class ActivityProcessingController extends Controller16{17public function __invoke(ActivityEventRequest $request)18{19$tz = Carbon::now()->getTimezone();2021/** @var \Pterodactyl\Models\Node $node */22$node = $request->attributes->get('node');2324$servers = $node->servers()->whereIn('uuid', $request->servers())->get()->keyBy('uuid');25$users = User::query()->whereIn('uuid', $request->users())->get()->keyBy('uuid');2627$logs = [];28foreach ($request->input('data') as $datum) {29/** @var Server|null $server */30$server = $servers->get($datum['server']);31if (is_null($server) || !Str::startsWith($datum['event'], 'server:')) {32continue;33}3435try {36$when = Carbon::createFromFormat(37\DateTimeInterface::RFC3339,38preg_replace('/(\.\d+)Z$/', 'Z', $datum['timestamp']),39'UTC'40);41} catch (\Exception $exception) {42Log::warning($exception, ['timestamp' => $datum['timestamp']]);4344// If we cannot parse the value for some reason don't blow up this request, just go ahead45// and log the event with the current time, and set the metadata value to have the original46// timestamp that was provided.47$when = Carbon::now();48$datum['metadata'] = array_merge($datum['metadata'] ?? [], ['original_timestamp' => $datum['timestamp']]);49}5051$log = [52'ip' => empty($datum['ip']) ? '127.0.0.1' : $datum['ip'],53'event' => $datum['event'],54'properties' => json_encode($datum['metadata'] ?? []),55// We have to change the time to the current timezone due to the way Laravel is handling56// the date casting internally. If we just leave it in UTC it ends up getting double-cast57// and the time is way off.58'timestamp' => $when->setTimezone($tz),59];6061if ($user = $users->get($datum['user'])) {62$log['actor_id'] = $user->id;63$log['actor_type'] = $user->getMorphClass();64}6566if (!isset($logs[$datum['server']])) {67$logs[$datum['server']] = [];68}6970$logs[$datum['server']][] = $log;71}7273foreach ($logs as $key => $data) {74Assert::isInstanceOf($server = $servers->get($key), Server::class);7576$batch = [];77foreach ($data as $datum) {78$id = ActivityLog::insertGetId($datum);79$batch[] = [80'activity_log_id' => $id,81'subject_id' => $server->id,82'subject_type' => $server->getMorphClass(),83];84}8586ActivityLogSubject::insert($batch);87}88}89}909192