/** * @param UploadAvatar $command * @return \Flarum\Core\User * @throws \Flarum\Core\Exception\PermissionDeniedException */ public function handle(UploadAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); if ($actor->id !== $user->id) { $this->assertCan($actor, 'edit', $user); } $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'avatar'); $command->file->moveTo($tmpFile); $file = new UploadedFile($tmpFile, $command->file->getClientFilename(), $command->file->getClientMediaType(), $command->file->getSize(), $command->file->getError(), true); $this->validator->assertValid(['avatar' => $file]); $manager = new ImageManager(); $manager->make($tmpFile)->fit(100, 100)->save(); $this->events->fire(new AvatarWillBeSaved($user, $actor, $tmpFile)); $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]); if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) { $mount->delete($file); } $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $user->changeAvatarPath($uploadName); $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $user->save(); $this->dispatchEventsFor($user, $actor); return $user; }
/** * {@inheritdoc} */ public function data(ServerRequestInterface $request, Document $document) { $this->assertAdmin($request->getAttribute('actor')); $file = array_get($request->getUploadedFiles(), 'favicon'); $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'favicon'); $file->moveTo($tmpFile); $extension = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION); if ($extension !== 'ico') { $manager = new ImageManager(); $encodedImage = $manager->make($tmpFile)->resize(64, 64, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->encode('png'); file_put_contents($tmpFile, $encodedImage); $extension = 'png'; } $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new Local($this->app->publicPath() . '/assets'))]); if (($path = $this->settings->get('favicon_path')) && $mount->has($file = "target://{$path}")) { $mount->delete($file); } $uploadName = 'favicon-' . Str::lower(Str::quickRandom(8)) . '.' . $extension; $mount->move('source://' . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $this->settings->set('favicon_path', $uploadName); return parent::data($request, $document); }
/** * @param UploadAvatar $command * @return \Flarum\Core\User * @throws \Flarum\Core\Exception\PermissionDeniedException */ public function handle(UploadAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); if ($actor->id !== $user->id) { $this->assertCan($actor, 'edit', $user); } $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'avatar'); $command->file->moveTo($tmpFile); try { $file = new UploadedFile($tmpFile, $command->file->getClientFilename(), $command->file->getClientMediaType(), $command->file->getSize(), $command->file->getError(), true); $this->validator->assertValid(['avatar' => $file]); $manager = new ImageManager(); // Explicitly tell Intervention to encode the image as JSON (instead of having to guess from the extension) $encodedImage = $manager->make($tmpFile)->fit(100, 100)->encode('jpg', 100); file_put_contents($tmpFile, $encodedImage); $this->events->fire(new AvatarWillBeSaved($user, $actor, $tmpFile)); $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]); if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) { $mount->delete($file); } $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $user->changeAvatarPath($uploadName); $mount->move('source://' . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $user->save(); $this->dispatchEventsFor($user, $actor); return $user; } catch (Exception $e) { @unlink($tmpFile); throw $e; } }
public function handle(Exception $e) { if ($e instanceof JsonApiSerializableInterface) { $status = $e->getStatusCode(); $errors = $e->getErrors(); } elseif ($e instanceof ValidationException) { $status = 422; $errors = $e->errors()->toArray(); $errors = array_map(function ($field, $messages) { return ['detail' => implode("\n", $messages), 'source' => ['pointer' => '/data/attributes/' . $field]]; }, array_keys($errors), $errors); } elseif ($e instanceof ModelNotFoundException) { $status = 404; $errors = []; } else { $status = 500; $error = ['code' => $status, 'title' => 'Internal Server Error']; if ($this->app->inDebugMode()) { $error['detail'] = (string) $e; } $errors = [$error]; } $document = new Document(); $document->setErrors($errors); return new JsonApiResponse($document, $status); }
/** * Generate a URL to base with UrlGenerator's prefix. * * @return string */ public function toBase() { $base = $this->app->url($this->path); if (empty($this->prefix)) { return $base; } else { return $base . '/' . $this->prefix; } }
/** * @param Request $request * @param array $routeParams * @return \Psr\Http\Message\ResponseInterface */ public function handle(Request $request, array $routeParams = []) { $user = $request->getAttribute('actor'); if ($user->exists) { $token = array_get($request->getQueryParams(), 'token'); AccessToken::where('user_id', $user->id)->findOrFail($token); $user->accessTokens()->delete(); $this->events->fire(new UserLoggedOut($user)); } return $this->withForgetCookie(new RedirectResponse($this->app->url())); }
/** * {@inheritdoc} */ protected function delete(ServerRequestInterface $request) { $this->assertAdmin($request->getAttribute('actor')); $path = $this->settings->get('favicon_path'); $this->settings->set('favicon_path', null); $uploadDir = new Filesystem(new Local($this->app->publicPath() . '/assets')); if ($uploadDir->has($path)) { $uploadDir->delete($path); } return new EmptyResponse(204); }
/** * @param Request $request * @return \Psr\Http\Message\ResponseInterface */ public function handle(Request $request) { try { $token = array_get($request->getQueryParams(), 'token'); $user = $this->bus->dispatch(new ConfirmEmail($token)); } catch (InvalidConfirmationTokenException $e) { return new HtmlResponse('Invalid confirmation token'); } $token = $this->bus->dispatch(new GenerateAccessToken($user->id)); return $this->withRememberCookie(new RedirectResponse($this->app->url()), $token->id); }
/** * @param Request $request * @return \Psr\Http\Message\ResponseInterface */ public function handle(Request $request) { try { $token = array_get($request->getQueryParams(), 'token'); $user = $this->bus->dispatch(new ConfirmEmail($token)); } catch (InvalidConfirmationTokenException $e) { return new HtmlResponse('Invalid confirmation token'); } $session = $request->getAttribute('session'); $this->authenticator->logIn($session, $user->id); return new RedirectResponse($this->app->url()); }
/** * @param Request $request * @return \Psr\Http\Message\ResponseInterface * @throws TokenMismatchException */ public function handle(Request $request) { $session = $request->getAttribute('session'); $response = new RedirectResponse($this->app->url()); if ($user = User::find($session->get('user_id'))) { if (array_get($request->getQueryParams(), 'token') !== $session->get('csrf_token')) { throw new TokenMismatchException(); } $this->authenticator->logOut($session); $user->accessTokens()->delete(); $this->events->fire(new UserLoggedOut($user)); $response = $this->rememberer->forget($response); } return $response; }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); if ($app->isInstalled()) { $app->register('Flarum\\Admin\\AdminServiceProvider'); $adminPath = parse_url($app->url('admin'), PHP_URL_PATH); $routes = $app->make('flarum.admin.routes'); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithCookie')); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); $pipe->pipe($adminPath, $app->make('Flarum\\Admin\\Middleware\\RequireAdministrateAbility')); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', compact('routes'))); $pipe->pipe(new HandleErrors(__DIR__ . '/../../error', $app->inDebugMode())); } return $pipe; }
/** * Handles the command execution. * * @param UploadImage $command * @return null|string * * @todo check permission */ public function handle(UploadImage $command) { // check if the user can upload images, otherwise return $this->assertCan($command->actor, 'flagrow.image.upload'); $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'image'); $command->file->moveTo($tmpFile); $file = new UploadedFile($tmpFile, $command->file->getClientFilename(), $command->file->getClientMediaType(), $command->file->getSize(), $command->file->getError(), true); // validate the file $this->validator->maxFileSize = $this->settings->get('flagrow.image-upload.maxFileSize', 2048); $this->validator->assertValid(['image' => $file]); // resize if enabled if ($this->settings->get('flagrow.image-upload.mustResize')) { $manager = new ImageManager(); $manager->make($tmpFile)->fit($this->settings->get('flagrow.image-upload.resizeMaxWidth', 100), $this->settings->get('flagrow.image-upload.resizeMaxHeight', 100))->save(); } $image = (new Image())->forceFill(['user_id' => $command->actor->id, 'upload_method' => $this->settings->get('flagrow.image-upload.uploadMethod', 'local'), 'created_at' => Carbon::now(), 'file_name' => sprintf('%d-%s.%s', $command->actor->id, Str::quickRandom(), $file->guessExtension() ?: 'jpg'), 'file_size' => $file->getSize()]); // fire the Event ImageWillBeSaved, which can be extended and/or modified elsewhere $this->events->fire(new ImageWillBeSaved($command->actor, $image, $file)); $tmpFilesystem = new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))); $meta = $this->upload->uploadContents($image->file_name, $tmpFilesystem->readAndDelete(pathinfo($tmpFile, PATHINFO_BASENAME))); if ($meta) { $image->file_url = array_get($meta, 'url'); if ($image->isDirty()) { $image->save(); } return $image; } return false; }
/** * Handles the command execution. * * @param UploadImage $command * @return null|string */ public function handle(UploadImage $command) { if ($command->postId) { // load the Post for this image $post = $this->posts->findOrFail($command->postId, $command->actor); } else { $post = null; } // todo check rights // todo validate file $image = new Image(); $image->user_id = $command->actor->id; $image->upload_method = 'local'; if ($post) { $image->post_id = $post->id; } $this->events->fire(new ImageWillBeSaved($post, $command->actor, $image, $command->file)); $file_name = sprintf('%d-%d-%s.jpg', $post ? $post->id : 0, $command->actor->id, str_random()); if (!$this->uploadDir->write($file_name, $command->file)) { // todo should throw error return null; } $appPath = parse_url($this->app->url(), PHP_URL_PATH); $image->file_name = sprintf('%s/assets/images/%s', $appPath, $file_name); $image->created_at = Carbon::now(); $image->save(); return $image; }
/** * @param Request $request * @return \Psr\Http\Message\ResponseInterface */ public function handle(Request $request) { $input = $request->getParsedBody(); if (array_get($input, 'databasePassword') !== $this->app->config('database.password')) { return new HtmlResponse('Incorrect database password.', 500); } $body = fopen('php://temp', 'wb+'); $input = new StringInput(''); $output = new StreamOutput($body); try { $this->command->run($input, $output); } catch (Exception $e) { return new HtmlResponse($e->getMessage(), 500); } return new Response($body, 200); }
/** * {@inheritdoc} */ public function __invoke(Request $request, Response $response, callable $out = null) { do { // Check if a guest. $actor = $request->getAttribute('actor'); if (!$actor->isGuest()) { break; } // Check for the global cookie setting. $authSettings = SingleSO::settingsAuth($this->settings, false); if (!$authSettings) { break; } // Check if the cookie is configured. $globalCookie = $authSettings['global_cookie']; if (!$globalCookie) { break; } // Check if that cookie is set. $cookies = $request->getCookieParams(); if (!isset($cookies[$globalCookie])) { break; } // Get current request path. // And URL hash is unfortunately unavailable. // Such data will be discarded on auto-login. $requestUri = $request->getUri(); $requestPath = $requestUri->getPath(); // Ignore if the controller path, avoid infinite redirect. if (strpos($requestPath, SingleSO::CONTROLLER_PATH) === 0) { break; } // Get any query parameters. $query = $requestUri->getQuery(); // Create the redirect path, preserve ? even if no query. $params = $request->getQueryParams(); $redirect = $requestPath . ($query ? '?' . $query : (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '?') !== false ? '?' : '')); // Create the login path. $loginPath = rtrim($this->app->url(), '/') . SingleSO::CONTROLLER_PATH . '/login'; // Create the redirect target, include return redirect parameters. $target = SingleSO::addParams($loginPath, ['redirect' => $redirect]); // Take over the response, redirect to login URL. return new RedirectResponse($target); } while (false); return $out ? $out($request, $response) : $response; }
/** * Set up the locale compiler for the given locale. * * @param string $locale * @return LocaleJsCompiler */ protected function getLocaleCompiler($locale) { $compiler = new LocaleJsCompiler($this->getAssetDirectory(), "{$this->clientName}-{$locale}.js", $this->app->config('debug'), $this->cache); foreach ($this->locales->getJsFiles($locale) as $file) { $compiler->addFile($file); } return $compiler; }
public function subscribe(Dispatcher $events) { if (defined('FLARUM_TENANT')) { $events->listen(ConfigureClientView::class, [$this, 'setFilename']); Application::booting(function ($app) { $app->make('config')->set('cache.prefix', FLARUM_TENANT); }); } }
private function saveAvatarFromUrl(User $user, $url) { $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'avatar'); $manager = new ImageManager(); $manager->make($url)->fit(100, 100)->save($tmpFile); $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]); $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $user->changeAvatarPath($uploadName); $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); }
/** * {@inheritdoc} */ protected function getDefaultAttributes($model) { $attributes = ['title' => $this->settings->get('forum_title'), 'description' => $this->settings->get('forum_description'), 'baseUrl' => $url = $this->app->url(), 'basePath' => parse_url($url, PHP_URL_PATH) ?: '', 'debug' => $this->app->inDebugMode(), 'apiUrl' => $this->app->url('api'), 'welcomeTitle' => $this->settings->get('welcome_title'), 'welcomeMessage' => $this->settings->get('welcome_message'), 'themePrimaryColor' => $this->settings->get('theme_primary_color'), 'themeSecondaryColor' => $this->settings->get('theme_secondary_color'), 'logoUrl' => $this->getLogoUrl(), 'faviconUrl' => $this->getFaviconUrl(), 'headerHtml' => $this->settings->get('custom_header'), 'allowSignUp' => (bool) $this->settings->get('allow_sign_up'), 'defaultRoute' => $this->settings->get('default_route'), 'canViewDiscussions' => $this->actor->can('viewDiscussions'), 'canStartDiscussion' => $this->actor->can('startDiscussion')]; if ($this->actor->can('administrate')) { $attributes['adminUrl'] = $this->app->url('admin'); $attributes['version'] = $this->app->version(); } return $attributes; }
protected function autoLoginScript() { // Get source, remiving any extra semicolons. $src = trim(file_get_contents(__DIR__ . '/../../js/autologin/dist/main.js'), ';'); // Special variables to replace. $find = ['___BASE___', '___PATH___']; // Values to replace with. $repl = [rtrim($this->app->url(), '/'), SingleSO::CONTROLLER_PATH . '/login']; // JSON encode with minimal extra slashes. foreach ($repl as $k => $v) { $repl[$k] = str_replace('</', '<\\/', json_encode($v, JSON_UNESCAPED_SLASHES)); } // Return the transformed source. return str_replace($find, $repl, $src); }
/** * {@inheritdoc} */ protected function getDefaultAttributes($model) { $gate = $this->gate->forUser($this->actor); $attributes = ['title' => $this->settings->get('forum_title'), 'description' => $this->settings->get('forum_description'), 'baseUrl' => $url = $this->app->url(), 'basePath' => parse_url($url, PHP_URL_PATH) ?: '', 'debug' => $this->app->inDebugMode(), 'apiUrl' => $this->app->url('api'), 'welcomeTitle' => $this->settings->get('welcome_title'), 'welcomeMessage' => $this->settings->get('welcome_message'), 'themePrimaryColor' => $this->settings->get('theme_primary_color'), 'allowSignUp' => (bool) $this->settings->get('allow_sign_up'), 'defaultRoute' => $this->settings->get('default_route'), 'canViewDiscussions' => $gate->allows('viewDiscussions') || $this->actor->hasPermissionLike('viewDiscussions'), 'canStartDiscussion' => $gate->allows('startDiscussion') || $this->actor->hasPermissionLike('startDiscussion')]; if ($gate->allows('administrate')) { $attributes['adminUrl'] = $this->app->url('admin'); $attributes['version'] = $this->app->version(); } return $attributes; }
/** * Get the user's locale, falling back to the forum's default if they * haven't set one. * * @param string $value * @return string */ public function getLocaleAttribute($value) { return $value ?: Application::config('locale', 'en'); }
/** * @return Akismet */ protected function getAkismet() { return new Akismet($this->settings->get('flarum-akismet.api_key'), $this->app->url()); }
/** * Generate a URL to base with UrlGenerator's prefix. * * @return string */ public function toBase() { return $this->app->url($this->path); }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); $installed = $app->isInstalled(); $basePath = parse_url($app->url(), PHP_URL_PATH); if ($installed) { $app->register('Flarum\\Forum\\ForumServiceProvider'); $routes = $app->make('flarum.forum.routes'); $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithCookie')); $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); } else { $app->register('Flarum\\Install\\InstallServiceProvider'); $routes = $app->make('flarum.install.routes'); } $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', compact('routes'))); $pipe->pipe(new HandleErrors(__DIR__ . '/../../error', $app->inDebugMode() || !$installed)); return $pipe; }
protected function getLessStorage() { return $this->app->storagePath() . '/less'; }
/** * @param string $path * @return string */ public function expandRedirect($path) { return SingleSO::safePath($this->app->url(), $path); }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); $path = parse_url($app->url(), PHP_URL_PATH); $errorDir = __DIR__ . '/../../error'; if (!$app->isInstalled()) { $app->register('Flarum\\Install\\InstallServiceProvider'); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\StartSession')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.install.routes')])); $pipe->pipe($path, new HandleErrors($errorDir, true)); } elseif ($app->isUpToDate() && !$app->isDownForMaintenance()) { $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\StartSession')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\RememberFromCookie')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithSession')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\SetLocale')); event(new ConfigureMiddleware($pipe, $path, $this)); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.forum.routes')])); $pipe->pipe($path, new HandleErrors($errorDir, $app->inDebugMode())); } else { $pipe->pipe($path, function () use($errorDir) { return new HtmlResponse(file_get_contents($errorDir . '/503.html', 503)); }); } return $pipe; }
/** * @param Application $app */ protected function registerLogger(Application $app) { $logger = new Logger($app->environment()); $logPath = $app->storagePath() . '/logs/flarum.log'; $handler = new StreamHandler($logPath, Logger::DEBUG); $handler->setFormatter(new LineFormatter(null, null, true, true)); $logger->pushHandler($handler); $app->instance('log', $logger); $app->alias('log', 'Psr\\Log\\LoggerInterface'); }
/** * @param Application $app */ protected function registerCache(Application $app) { $app->singleton('cache.store', function ($app) { return new \Illuminate\Cache\Repository($app->make('cache.filestore')); }); $app->singleton('cache.filestore', function ($app) { return new \Illuminate\Cache\FileStore(new \Illuminate\Filesystem\Filesystem(), $app->storagePath() . '/cache'); }); $app->alias('cache.filestore', 'Illuminate\\Contracts\\Cache\\Store'); $app->alias('cache.store', 'Illuminate\\Contracts\\Cache\\Repository'); }