/** * @Route(methods="POST", defaults={"_maintenance" = true}) * @Request({"credentials": "array", "remember_me": "boolean", "redirect": "string"}) */ public function authenticateAction($credentials, $remember = false, $redirect = '') { try { if (!App::csrf()->validate()) { throw new CsrfException(__('Invalid token. Please try again.')); } App::auth()->authorize($user = App::auth()->authenticate($credentials, false)); if (($event = App::auth()->login($user, $remember)) && $event->hasResponse()) { return $event->getResponse(); } if (App::request()->isXmlHttpRequest()) { return App::response()->json(['csrf' => App::csrf()->generate()]); } else { return App::redirect(preg_replace('#(https?:)?//[^/]+#', '', $redirect)); } } catch (CsrfException $e) { if (App::request()->isXmlHttpRequest()) { return App::response()->json(['csrf' => App::csrf()->generate()], 401); } $error = $e->getMessage(); } catch (BadCredentialsException $e) { $error = __('Invalid username or password.'); } catch (AuthException $e) { $error = $e->getMessage(); } if (App::request()->isXmlHttpRequest()) { App::abort(401, $error); } else { App::message()->error($error); return App::redirect(preg_replace('#(https?:)?//[^/]+#', '', App::url()->previous())); } }
/** * @Route("/uploadmanager", name="uploadmanager", methods="GET") */ public function uploadManagerAction() { if ($this->requireLogin()) { return App::response()->redirect('@user/login'); } $uploads = Media::where(['uploader_id = :uploader AND status != :finished'], ['uploader' => App::user()->id, 'finished' => Media::STATUS_FINISHED])->orderBy('created', 'DESC')->related(['artist', 'user'])->get(); return ['$view' => ['title' => __('Upload Manager'), 'name' => 'shoutzor:views/uploadmanager.php'], 'uploads' => $uploads, 'maxFileSize' => $this->formatBytes($this->file_upload_max_size()), 'maxDuration' => App::module('shoutzor')->config('shoutzor')['uploadDurationLimit']]; }
/** * @Route("/{id}", name="view", requirements={"id"="\d+"}) */ public function viewAction($id) { $artist = Artist::query()->where('id = ?', [$id])->related('album')->first(); $request = App::request(); if (is_null($artist)) { $request->getSession()->getFlashBag()->add('error', __('Tried to view an non-existing Artist')); return App::response()->redirect('@shoutzor/artist/index'); } $topTracks = $artist->getTopMedia(); return ['$view' => ['title' => 'Artist: ' . $artist->name, 'name' => 'shoutzor:views/artist/view.php'], 'image' => is_null($artist->image) || empty($artist->image) ? App::url()->getStatic('shoutzor:assets/images/profile-placeholder.png') : App::url()->getStatic('shoutzor:' . App::module('shoutzor')->config('shoutzor')['imageDir'] . '/' . $artist->image), 'summary' => empty($artist->summary) ? __('No summary for this artist is available') : $artist->summary, 'artist' => $artist, 'topTracks' => $topTracks, 'albums' => $artist->getAlbums()]; }
/** * Converts an Exception to a Response. * * @param Request $request * @param FlattenException $exception * @return Response */ public function showAction(Request $request, FlattenException $exception) { if (is_subclass_of($exception->getClass(), 'Pagekit\\Kernel\\Exception\\HttpException')) { $title = $exception->getMessage(); } else { $title = __('Whoops, looks like something went wrong.'); } $content = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1)); $response = App::view('system/error.php', compact('title', 'exception', 'content')); return App::response($response, $exception->getCode(), $exception->getHeaders()); }
/** * @Request({"redirect": "string"}, csrf=true) */ public function migrateAction($redirect = null) { if ($updates = $this->scripts->hasUpdates()) { $this->scripts->update(); $message = __('Your Pagekit database has been updated successfully.'); } else { $message = __('Your database is up to date.'); } App::config('system')->set('version', App::version()); if ($redirect) { App::message()->success($message); return App::redirect($redirect); } return App::response()->json(compact('status', 'message')); }
/** * @Request({"redirect": "string"}, csrf=true) */ public function migrateAction($redirect = null) { $config = App::config('system'); $manager = new PackageManager(); $scripts = $manager->loadScripts(null, __DIR__ . '/../../scripts.php'); if (isset($scripts['updates'])) { $updates = $manager->filterUpdates($scripts['updates'], $config->get('version')); $manager->execute($updates); } $config->set('version', App::version()); $message = __('Your Pagekit database has been updated successfully.'); if ($redirect) { App::message()->success($message); return App::redirect($redirect); } return App::response()->json(compact('status', 'message')); }
/** * TODO: Limit catalogue if maintenance mode is enabled? * @Route("/{locale}", requirements={"locale"="[a-zA-Z0-9_-]+"}, defaults={"_maintenance" = true}) * @Request({"locale"}) */ public function indexAction($locale = null) { $intl = App::module('system/intl'); $intl->loadLocale($locale); $messages = $intl->getFormats($locale) ?: []; $messages['locale'] = $locale; $messages['translations'] = [$locale => App::translator()->getCatalogue($locale)->all()]; $messages = json_encode($messages); $request = App::request(); $json = $request->isXmlHttpRequest(); $response = $json ? App::response()->json() : App::response('', 200, ['Content-Type' => 'application/javascript']); $response->setETag(md5($json . $messages))->setPublic(); if ($response->isNotModified($request)) { return $response; } return $response->setContent($json ? $messages : sprintf('var $locale = %s;', $messages)); }
/** * @Route("/feed") * @Route("/feed/{type}") */ public function feedAction($type = '') { // fetch locale and convert to ISO-639 (en_US -> en-us) $locale = App::module('system')->config('site.locale'); $locale = str_replace('_', '-', strtolower($locale)); $site = App::module('system/site'); $feed = App::feed()->create($type ?: $this->blog->config('feed.type'), ['title' => $site->config('title'), 'link' => App::url('@blog', [], 0), 'description' => $site->config('description'), 'element' => ['language', $locale], 'selfLink' => App::url('@blog/feed', [], 0)]); if ($last = Post::where(['status = ?', 'date < ?'], [Post::STATUS_PUBLISHED, new \DateTime()])->limit(1)->orderBy('modified', 'DESC')->first()) { $feed->setDate($last->modified); } foreach (Post::where(['status = ?', 'date < ?'], [Post::STATUS_PUBLISHED, new \DateTime()])->where(function ($query) { return $query->where('roles IS NULL')->whereInSet('roles', App::user()->roles, false, 'OR'); })->related('user')->limit($this->blog->config('feed.limit'))->orderBy('date', 'DESC')->get() as $post) { $url = App::url('@blog/id', ['id' => $post->id], 0); $feed->addItem($feed->createItem(['title' => $post->title, 'link' => $url, 'description' => App::content()->applyPlugins($post->content, ['post' => $post, 'markdown' => $post->get('markdown'), 'readmore' => true]), 'date' => $post->date, 'author' => [$post->user->name, $post->user->email], 'id' => $url])); } return App::response($feed->output(), 200, ['Content-Type' => $feed->getMIMEType() . '; charset=' . $feed->getEncoding()]); }
/** * @Request(csrf=true) */ public function updateAction() { if (!($file = App::session()->get('system.update'))) { App::abort(400, __('You may not call this step directly.')); } App::session()->remove('system.update'); return App::response()->stream(function () use($file) { try { if (!file_exists($file) || !is_file($file)) { throw new \RuntimeException('File does not exist.'); } $updater = new SelfUpdater(); $updater->update($file); } catch (\Exception $e) { http_response_code(400); echo $e->getMessage(); } }); }
/** * Puts the page in maintenance mode. */ public function onRequest($event, $request) { if (!$event->isMasterRequest()) { return; } $site = App::module('system/site'); if ($site->config('maintenance.enabled') && !(App::isAdmin() || $request->attributes->get('_maintenance') || App::user()->hasAccess('site: maintenance access'))) { $message = $site->config('maintenance.msg') ?: __("We'll be back soon."); $response = App::view('system/theme:views/maintenance.php', compact('message')); $request->attributes->set('_disable_debugbar', true); $types = $request->getAcceptableContentTypes(); if ('json' == $request->getFormat(array_shift($types))) { $response = App::response()->json($message, 503); } else { $response = App::response($response, 503); } $event->setResponse($response); } }
/** * @Request(csrf=true) */ public function updateAction() { if (!($file = App::session()->get('system.update'))) { App::abort(400, __('You may not call this step directly.')); } App::session()->remove('system.update'); return App::response()->stream(function () use($file) { $output = new StreamOutput(fopen('php://output', 'w')); try { if (!file_exists($file) || !is_file($file)) { throw new \RuntimeException('File does not exist.'); } $updater = new SelfUpdater($output); $updater->update($file); } catch (\Exception $e) { $output->writeln(sprintf("\n<error>%s</error>", $e->getMessage())); $output->write("status=error"); } }); }
/** * Puts the page in maintenance mode. */ public function onRequest($event, $request) { if (!$event->isMasterRequest()) { return; } $site = App::module('system/site'); if ($site->config('maintenance.enabled') && !(App::isAdmin() || $request->attributes->get('_maintenance') || App::user()->hasAccess('site: maintenance access') || App::user()->hasAccess('system: access admin area'))) { $message = $site->config('maintenance.msg') ?: __("We'll be back soon."); $logo = $site->config('maintenance.logo') ?: 'app/system/assets/images/pagekit-logo-large-black.svg'; $response = App::view('system/theme:views/maintenance.php', compact('message', 'logo')); $request->attributes->set('_disable_debugbar', true); $types = $request->getAcceptableContentTypes(); if (!App::user()->isAuthenticated() && $request->isXMLHttpRequest()) { App::abort('401', 'Unauthorized'); } elseif ('json' == $request->getFormat(array_shift($types))) { $response = App::response()->json($message, 503); } else { $response = App::response($response, 503); } $event->setResponse($response); } }
/** * @param string $name * @return callable|null */ protected function errorHandler($name) { ini_set('display_errors', 0); return App::exception()->setHandler(function ($exception) use($name) { while (ob_get_level()) { ob_get_clean(); } $message = __('Unable to activate "%name%".<br>A fatal error occured.', ['%name%' => $name]); if (App::debug()) { $message .= '<br><br>' . $exception->getMessage(); } App::response()->json($message, 500)->send(); }); }
/** * Checks for the "system: access admin area" and redirects to login. */ public function onRequest($event, $request) { if (App::auth()->getUser() or !in_array('system: access admin area', $request->attributes->get('_access', []))) { return; } $params = []; // redirect to default URL for POST requests and don't explicitly redirect the default URL if ('POST' !== $request->getMethod() && $request->attributes->get('_route') != '@system') { $params['redirect'] = App::url()->current(true); } $event->setResponse(App::response()->redirect('@system/login', $params)); }
/** * @Route("/disconnect", methods="DELETE") */ public function disconnectAction() { unset(App::config('analytics')['profile']); unset(App::config('analytics')['token']); return App::response()->json(array()); }
public function downloadAction() { return App::response()->download('extensions/hello/extension.svg'); }
/** * Redirects a user after successful logout. * * @param LogoutEvent $event */ public function onLogout(LogoutEvent $event) { $event->setResponse(App::response()->redirect(App::request()->get(Auth::REDIRECT_PARAM))); }
/** * @Request({"data": "array", "action": "string",}) */ public function weatherAction($data, $action) { $url = $this->api; if ($action === 'weather') { $url .= '/weather'; } elseif ($action === 'find') { $url .= '/find'; } $data['APPID'] = $this->apiKey; $url .= '?' . http_build_query($data); return App::response(file_get_contents($url), 200, ['Content-Type' => 'application/json']); }