} if (Core::isInstalled()) { $settings = $app->make('Flarum\\Core\\Settings\\SettingsRepository'); $app->register(new \Flarum\Core\CoreServiceProvider($app)); $config->set('mail.driver', Core::config('mail_driver')); $config->set('mail.host', Core::config('mail_host')); $config->set('mail.port', Core::config('mail_port')); $config->set('mail.from.address', Core::config('mail_from')); $config->set('mail.from.name', Core::config('forum_title')); $config->set('mail.encryption', Core::config('mail_encryption')); $config->set('mail.username', Core::config('mail_username')); $config->set('mail.password', Core::config('mail_password')); // Register extensions and tell them to listen for events $app->register(new \Flarum\Support\ExtensionsServiceProvider($app)); } $app->boot(); // If the version stored in the database doesn't match the version of the // code, then run the upgrade script (migrations). This is temporary - a // proper, more secure upgrade method is planned. if (Core::isInstalled() && $settings->get('version') !== $app::VERSION) { $input = new \Symfony\Component\Console\Input\StringInput(''); $output = new \Symfony\Component\Console\Output\BufferedOutput(); app('Flarum\\Console\\UpgradeCommand')->run($input, $output); $settings->set('version', $app::VERSION); app('flarum.formatter')->flush(); $forum = app('Flarum\\Forum\\Actions\\ClientAction'); $forum->flushAssets(); $admin = app('Flarum\\Admin\\Actions\\ClientAction'); $admin->flushAssets(); } return $app;
public function handle(Exception $e) { if ($e instanceof JsonApiSerializable) { $status = $e->getStatusCode(); $errors = $e->getErrors(); } else { if ($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); } else { if ($e instanceof ModelNotFoundException) { $status = 404; $errors = []; } else { $status = 500; $error = ['code' => $status, 'title' => 'Internal Server Error']; if (Core::inDebugMode()) { $error['detail'] = (string) $e; } $errors = [$error]; } } } // JSON API errors must be collected in an array under the // "errors" key in the top level of the document $data = ['errors' => $errors]; return new JsonResponse($data, $status); }
public function validatePost(PostWillBeSaved $event) { $post = $event->post; if ($post->exists || $post->user->groups()->count()) { return; } $akismet = new Akismet($this->settings->get('akismet.api_key'), Core::url()); $isSpam = $akismet->isSpam($post->content, $post->user->username, $post->user->email, null, 'comment'); if ($isSpam) { $post->hide(); $this->savingPost = $post; CommentPost::saved(function (CommentPost $post) { if ($post !== $this->savingPost) { return; } $report = new Report(); $report->post_id = $post->id; $report->reporter = 'Akismet'; $report->reason = 'spam'; $report->time = time(); $report->save(); $this->savingPost = null; }); } }
/** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('flarum.db', function () { $factory = new ConnectionFactory($this->app); $connection = $factory->make($this->app->make('flarum.config')['database']); $connection->setEventDispatcher($this->app->make('Illuminate\\Contracts\\Events\\Dispatcher')); $connection->setFetchMode(PDO::FETCH_CLASS); return $connection; }); $this->app->alias('flarum.db', 'Illuminate\\Database\\ConnectionInterface'); $this->app->singleton('Illuminate\\Database\\ConnectionResolverInterface', function () { $resolver = new ConnectionResolver(['flarum' => $this->app->make('flarum.db')]); $resolver->setDefaultConnection('flarum'); return $resolver; }); $this->app->alias('Illuminate\\Database\\ConnectionResolverInterface', 'db'); if (Core::isInstalled()) { $this->app->booting(function () { $resolver = $this->app->make('Illuminate\\Database\\ConnectionResolverInterface'); Model::setConnectionResolver($resolver); Model::setEventDispatcher($this->app->make('events')); }); } $this->app->singleton('Flarum\\Migrations\\MigrationRepositoryInterface', function ($app) { return new DatabaseMigrationRepository($app['db'], 'migrations'); }); }
/** * {@inheritdoc} */ protected function getDefaultAttributes($forum) { $attributes = ['title' => Core::config('forum_title'), 'baseUrl' => Core::url(), 'basePath' => parse_url(Core::url(), PHP_URL_PATH) ?: '', 'debug' => Core::inDebugMode(), 'apiUrl' => Core::url('api'), 'welcomeTitle' => Core::config('welcome_title'), 'welcomeMessage' => Core::config('welcome_message'), 'themePrimaryColor' => Core::config('theme_primary_color'), 'canView' => $forum->can($this->actor, 'view'), 'canStartDiscussion' => $forum->can($this->actor, 'startDiscussion'), 'allowSignUp' => (bool) Core::config('allow_sign_up'), 'defaultRoute' => Core::config('default_route')]; if ($this->actor->isAdmin()) { $attributes['adminUrl'] = Core::url('admin'); $attributes['version'] = Application::VERSION; } return $attributes; }
/** * Register the service provider. * * @return void */ public function register() { // Extensions will not be registered if Flarum is not installed yet if (!Core::isInstalled()) { return; } $extensions = json_decode(Core::config('extensions_enabled'), true); $providers = []; foreach ($extensions as $extension) { if (file_exists($file = base_path() . '/extensions/' . $extension . '/bootstrap.php')) { $providers[$extension] = (require $file); } } // @todo store $providers somewhere so that extensions can talk to each other }
public function handle(RequestPasswordResetCommand $command) { $user = $this->users->findByEmail($command->email); if (!$user) { throw new ModelNotFoundException(); } $token = PasswordToken::generate($user->id); $token->save(); $data = ['username' => $user->username, 'url' => route('flarum.forum.resetPassword', ['token' => $token->id]), 'forumTitle' => Core::config('forum_title')]; $this->mailer->send(['text' => 'flarum::emails.resetPassword'], $data, function ($message) use($user) { $message->to($user->email); $message->subject('Reset Your Password'); }); return $user; }
public function handle(Request $request) { $images = $request->http->getUploadedFiles()['images']; $results = []; foreach ($images as $image_key => $image) { $tmpFile = tempnam(sys_get_temp_dir(), 'image'); $image->moveTo($tmpFile); $urlGenerator = app('Flarum\\Http\\UrlGeneratorInterface'); $dir = 'uploads/' . date('Ym/d'); $path = './assets/' . $dir; $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new Local($path))]); $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $results['img_' . $image_key] = Core::url() . '/assets/' . $dir . '/' . $uploadName; } return new JsonResponse($results); }
/** * @param RequestPasswordReset $command * @return \Flarum\Core\Users\User * @throws ModelNotFoundException */ public function handle(RequestPasswordReset $command) { $user = $this->users->findByEmail($command->email); if (!$user) { throw new ModelNotFoundException(); } $token = PasswordToken::generate($user->id); $token->save(); // TODO: Need to use UrlGenerator, but since this is part of core we // don't know that the forum routes will be loaded. Should the reset // password route be part of core?? $data = ['username' => $user->username, 'url' => Core::url() . '/reset/' . $token->id, 'forumTitle' => $this->settings->get('forum_title')]; $this->mailer->send(['text' => 'flarum::emails.resetPassword'], $data, function (Message $message) use($user) { $message->to($user->email); $message->subject('Reset Your Password'); }); return $user; }
/** * @param string $url * @return RedirectResponse */ protected function redirectTo($url) { $url = Core::url() . $url; $content = sprintf(' <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="refresh" content="1;url=%1$s" /> <title>Redirecting to %1$s</title> </head> <body> Redirecting to <a href="%1$s">%1$s</a>. </body> </html>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8')); $response = new RedirectResponse($url); $response->getBody()->write($content); return $response; }
public function validatePost(PostWillBeSaved $event) { $post = $event->post; if ($post->exists || $post->user->groups()->count()) { return; } $akismet = new Akismet($this->settings->get('akismet.api_key'), Core::url()); $isSpam = $akismet->isSpam($post->content, $post->user->username, $post->user->email, null, 'comment'); if ($isSpam) { $post->is_approved = false; // TODO: // $post->is_spam = true; $post->afterSave(function ($post) { $flag = new Flag(); $flag->post_id = $post->id; $flag->type = 'akismet'; $flag->time = time(); $flag->save(); }); } }
public function toAsset($path) { return Core::url($this->prefix) . "/assets/{$path}"; }
use Flarum\Forum\Middleware\HandleErrors; use Franzl\Middleware\Whoops\Middleware as WhoopsMiddleware; use Zend\Diactoros\Server; use Zend\Stratigility\MiddlewarePipe; $app = (require __DIR__ . '/flarum/bootstrap.php'); // If Flarum's configuration exists, then we can assume that installation has // been completed. We will set up a middleware pipe to route the request through // to one of the main forum actions. if (Core::isInstalled()) { $app->register('Flarum\\Forum\\ForumServiceProvider'); $flarum = new MiddlewarePipe(); $flarum->pipe($app->make('Flarum\\Forum\\Middleware\\LoginWithCookie')); $flarum->pipe($app->make('Flarum\\Api\\Middleware\\ReadJsonParameters')); $basePath = parse_url(Core::url(), PHP_URL_PATH); $router = $app->make('Flarum\\Http\\RouterMiddleware', ['routes' => $app->make('flarum.forum.routes')]); $flarum->pipe($basePath, $router); if (Core::inDebugMode()) { $flarum->pipe(new WhoopsMiddleware()); } else { $flarum->pipe(new HandleErrors(base_path('error'))); } } else { $app->register('Flarum\\Install\\InstallServiceProvider'); $flarum = new MiddlewarePipe(); $basePath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $router = $app->make('Flarum\\Http\\RouterMiddleware', ['routes' => $app->make('flarum.install.routes')]); $flarum->pipe($basePath, $router); $flarum->pipe(new WhoopsMiddleware()); } $server = Server::createServer($flarum, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server->listen();
public function toAsset($path) { return Core::url() . "/assets/{$path}"; }
public function getTitleAttribute() { return Core::config('forum_title'); }
/** * 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 ?: Core::config('locale', 'en'); }
$handler = new \Monolog\Handler\StreamHandler($logPath, Monolog\Logger::DEBUG); $handler->setFormatter(new \Monolog\Formatter\LineFormatter(null, null, true, true)); $logger->pushHandler($handler); $app->instance('log', $logger); $app->alias('log', 'Psr\\Log\\LoggerInterface'); $app->singleton('cache', function ($app) { $store = new FileStore(new Filesystem(), storage_path('framework/cache')); $repository = new Repository($store); $repository->setEventDispatcher($app->make('events')); return $repository; }); $app->alias('cache', 'Illuminate\\Contracts\\Cache\\Repository'); $serviceProviders = ['Flarum\\Core\\DatabaseServiceProvider', 'Flarum\\Core\\Settings\\SettingsServiceProvider', 'Flarum\\Locale\\LocaleServiceProvider', 'Illuminate\\Bus\\BusServiceProvider', 'Illuminate\\Filesystem\\FilesystemServiceProvider', 'Illuminate\\Hashing\\HashServiceProvider', 'Illuminate\\Mail\\MailServiceProvider', 'Illuminate\\View\\ViewServiceProvider', 'Illuminate\\Events\\EventServiceProvider', 'Illuminate\\Validation\\ValidationServiceProvider']; foreach ($serviceProviders as $provider) { $app->register(new $provider($app)); } if (Core::isInstalled()) { $app->register(new \Flarum\Core\CoreServiceProvider($app)); $config->set('mail.driver', Core::config('mail_driver')); $config->set('mail.host', Core::config('mail_host')); $config->set('mail.port', Core::config('mail_port')); $config->set('mail.from.address', Core::config('mail_from')); $config->set('mail.from.name', Core::config('forum_title')); $config->set('mail.encryption', Core::config('mail_encryption')); $config->set('mail.username', Core::config('mail_username')); $config->set('mail.password', Core::config('mail_password')); // Register extensions and tell them to listen for events $app->register(new \Flarum\Support\ExtensionsServiceProvider($app)); } $app->boot(); return $app;
protected function getPayload($user, $email) { $token = $this->generateToken($user, $email); return ['username' => $user->username, 'url' => route('flarum.forum.confirmEmail', ['token' => $token->id]), 'forumTitle' => Core::config('forum_title')]; }
/** * Get the data that should be made available to email templates. * * @param User $user * @param string $email * * @return array */ protected function getEmailData(User $user, $email) { $token = $this->generateToken($user, $email); // TODO: Need to use UrlGenerator, but since this is part of core we // don't know that the forum routes will be loaded. Should the confirm // email route be part of core?? return ['username' => $user->username, 'url' => Core::url() . '/confirm/' . $token->id, 'forumTitle' => $this->settings->get('forum_title')]; }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Flarum\Api\Middleware\JsonApiErrors; use Flarum\Core; use Zend\Diactoros\Server; use Zend\Stratigility\MiddlewarePipe; $app = (require __DIR__ . '/flarum/bootstrap.php'); $app->register('Flarum\\Api\\ApiServiceProvider'); $api = new MiddlewarePipe(); $api->pipe($app->make('Flarum\\Api\\Middleware\\ReadJsonParameters')); $api->pipe($app->make('Flarum\\Api\\Middleware\\LoginWithHeader')); $api->pipe($app->make('Flarum\\Api\\Middleware\\FakeHttpMethods')); $apiPath = parse_url(Core::url('api'), PHP_URL_PATH); $router = $app->make('Flarum\\Http\\RouterMiddleware', ['routes' => $app->make('flarum.api.routes')]); $api->pipe($apiPath, $router); $api->pipe(new JsonApiErrors()); $server = Server::createServer($api, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server->listen();