/** * {@inheritdoc} */ public function main(App $app) { $this->breadcrumbs = new BreadcrumbsManager($app); $app->extend('view', function ($view) { return $view->addGlobal('breadcrumbs', $this); }); }
/** * {@inheritdoc} */ public function load($module) { $class = $module[is_string($module['main']) ? 'main' : 'class']; $module = new $class($module); $module->main($this->app); if (is_a($module, 'Pagekit\\Event\\EventSubscriberInterface')) { $this->app->subscribe($module); } return $module; }
/** * @return array */ public function getStyles() { if (!static::$styles) { $paths = glob($this->app->locator()->get('theme:styles') . '/*/style.less', GLOB_NOSORT) ?: []; static::$styles = ['default']; foreach ($paths as $p) { static::$styles[] = basename(dirname($p)); } } return static::$styles; }
/** * @param File $file * @return mixed */ public static function getNext($file) { $module = App::module('bixie/download'); return self::where(['title < ?', 'status = ?'], [$file->title, '1'])->where(function ($query) { return $query->where('roles IS NULL')->whereInSet('roles', App::user()->roles, false, 'OR'); })->orderBy($module->config('ordering'), $module->config('ordering_dir'))->first(); }
/** * @Route("/bulk", methods="POST") * @Request({"widgets": "array"}, csrf=true) */ public function bulkSaveAction($widgets = []) { foreach ($widgets as $data) { $this->saveAction($data, isset($data['id']) ? $data['id'] : 0); } return ['message' => 'success', 'positions' => array_values(App::position()->all())]; }
/** * Returns several config settings needed for the settings view. */ public function configAction() { $styles = array_map(function ($fn) { return basename($fn, '.css'); }, glob(App::locator()->get('highlight:assets/styles') . '/*.css')); return compact('styles'); }
/** * @Route("/edit") * @Request({"id"}) */ public function editAction($id = '') { /** @var \Bixie\Formmaker\FormmakerModule $formmaker */ $formmaker = App::module('bixie/formmaker'); if (is_numeric($id)) { $field = Field::find($id); } else { $field = Field::create(); $field->setFieldType($id); } if (!$field) { App::abort(404, __('Field not found.')); } if (!($type = $formmaker->getFieldType($field->type))) { App::abort(404, __('Type not found.')); } //default values $fixedFields = ['multiple', 'required']; if (!$field->id) { foreach ($type->getConfig() as $key => $value) { if (!in_array($key, $fixedFields)) { $field->set($key, $value); } } } //check fixed value foreach ($fixedFields as $key) { if ($type[$key] != -1) { $field->set($key, $type[$key]); } } return ['field' => $field, 'type' => $type, 'roles' => array_values(Role::findAll())]; }
public function __construct() { $config = App::module('shoutzor')->config(); $this->enabled = $config['acoustid']['enabled'] == 1; $this->appKey = $config['acoustid']['appKey']; $this->requirementDir = realpath($config['root_path'] . '/../shoutzor-requirements/acoustid'); }
/** * @Request({"user": "******"}, csrf=true) */ public function saveAction($data) { $user = App::user(); if (!$user->isAuthenticated()) { App::abort(404); } try { $user = User::find($user->id); if ($password = @$data['password_new']) { if (!App::auth()->getUserProvider()->validateCredentials($user, ['password' => @$data['password_old']])) { throw new Exception(__('Invalid Password.')); } if (trim($password) != $password || strlen($password) < 3) { throw new Exception(__('Invalid Password.')); } $user->password = App::get('auth.password')->hash($password); } if (@$data['email'] != $user->email) { $user->set('verified', false); } $user->name = @$data['name']; $user->email = @$data['email']; $user->validate(); $user->save(); return ['message' => 'success']; } catch (Exception $e) { App::abort(400, $e->getMessage()); } }
public function getRandomTrack($autoForce = true, $forced = false) { if ($forced === true) { return Media::query()->orderBy('rand()')->first(); } else { $list = array(); } $config = App::module('shoutzor')->config('shoutzor'); $requestHistoryTime = (new DateTime())->sub(new DateInterval('PT' . $config['mediaRequestDelay'] . 'M'))->format('Y-m-d H:i:s'); $artistHistoryTime = (new DateTime())->sub(new DateInterval('PT' . $config['artistRequestDelay'] . 'M'))->format('Y-m-d H:i:s'); //Build a list of media id's that are available to play, next, randomly pick one $q = Media::query()->select('DISTINCT m.*')->from('@shoutzor_media m')->leftJoin('@shoutzor_requestlist q', 'q.media_id = m.id')->where('q.media_id IS NULL')->where('m.id NOT IN ( SELECT h.media_id FROM @shoutzor_history h LEFT JOIN @shoutzor_requestlist tq ON tq.media_id = h.media_id WHERE h.played_at > :maxTime )', ['maxTime' => $requestHistoryTime])->where('m.id NOT IN ( SELECT tma.media_id FROM @shoutzor_media_artist tma WHERE tma.artist_id IN ( SELECT ma.artist_id FROM @shoutzor_media_artist ma WHERE ma.media_id IN ( SELECT th.media_id FROM @shoutzor_history th LEFT JOIN @shoutzor_requestlist tq ON tq.media_id = th.media_id WHERE th.played_at > :maxTime ) ) )', ['maxTime' => $artistHistoryTime])->groupBy('m.id')->orderBy('rand(' . microtime(true) . ')'); if ($q->count() === 0) { return $autoForce === true ? $this->getRandomTrack(true, true) : false; } return $q->first(); }
/** * @Route(methods="POST", defaults={"_maintenance" = true}) * @Request({"credentials": "array", "_remember_me": "boolean"}) */ public function authenticateAction($credentials, $remember = false) { $isXml = App::request()->isXmlHttpRequest(); try { if (!App::csrf()->validate()) { throw new AuthException(__('Invalid token. Please try again.')); } App::auth()->authorize($user = App::auth()->authenticate($credentials, false)); if (!$isXml) { return App::auth()->login($user, $remember); } else { App::auth()->setUser($user, $remember); return ['success' => true]; } } catch (BadCredentialsException $e) { $error = __('Invalid username or password.'); } catch (AuthException $e) { $error = $e->getMessage(); } if (!$isXml) { App::message()->error($error); return App::redirect(App::url()->previous()); } else { App::abort(400, $error); } }
/** * @Saving */ public static function saving($event, Field $field) { $userprofile = App::module('bixie/userprofile'); if (!($type = $userprofile->getFieldType($field->type))) { throw new Exception(__('Field type not found.')); } foreach (['multiple', 'required'] as $key) { if ($type[$key] != -1) { //check fixed value if ($type[$key] != $field->get($key)) { throw new Exception(__('Invalid value for ' . $key . ' option.')); } } } //slug $i = 2; $id = $field->id; if (!$field->slug) { $field->slug = $field->label; } while (self::where(['slug = ?'], [$field->slug])->where(function ($query) use($id) { if ($id) { $query->where('id <> ?', [$id]); } })->first()) { $field->slug = preg_replace('/-\\d+$/', '', $field->slug) . '-' . $i++; } if (!$field->id) { $next = self::getConnection()->fetchColumn('SELECT MAX(priority) + 1 FROM @userprofile_field'); $field->priority = $next ?: 0; } }
/** * @Request({"user", "key"}) */ public function confirmAction($username = "", $activation = "") { if (empty($username) || empty($activation) || !($user = User::where(compact('username', 'activation'))->first())) { return $this->messageView(__('Invalid key.'), $success = false); } if ($user->isBlocked()) { return $this->messageView(__('Your account has not been activated or is blocked.'), $success = false); } $error = ''; if ('POST' === App::request()->getMethod()) { try { if (!App::csrf()->validate()) { throw new Exception(__('Invalid token. Please try again.')); } $password = App::request()->request->get('password'); if (empty($password)) { throw new Exception(__('Enter password.')); } if ($password != trim($password)) { throw new Exception(__('Invalid password.')); } $user->password = App::get('auth.password')->hash($password); $user->activation = null; $user->save(); App::message()->success(__('Your password has been reset.')); return App::redirect('@user/login'); } catch (Exception $e) { $error = $e->getMessage(); } } return ['$view' => ['title' => __('Reset Confirm'), 'name' => 'system/user/reset-confirm.php'], 'username' => $username, 'activation' => $activation, 'error' => $error]; }
/** * Returns the path relative to the root. * * @param string $path * @return string */ protected function getRelativePath($path) { if (0 === strpos($path, App::path())) { $path = ltrim(str_replace('\\', '/', substr($path, strlen(App::path()))), '/'); } return $path; }
/** * @Route("/", name="index") */ public function indexAction() { $config = App::module('shoutzor')->config('liquidsoap'); $liquidsoapManager = new LiquidsoapManager(); $wrapperActive = $liquidsoapManager->isUp('wrapper'); $shoutzorActive = $liquidsoapManager->isUp('shoutzor'); $form = new FormGenerator('', 'POST', 'uk-form uk-form-horizontal'); $form->addField(new DivField("Permission Check", $config['logDirectoryPath'] . (is_writable($config['logDirectoryPath']) ? " is writable" : " is not writable! chown manually to www-data:www-data"), "", is_writable($config['logDirectoryPath']) ? "uk-alert uk-alert-success" : "uk-alert uk-alert-danger")); //Usually the log directory and the socket directory will be the same //Thus, showing twice that the same directory is (not) writable has no use if ($config['logDirectoryPath'] != $config['socketPath']) { $form->addField(new DivField("Permission Check", $config['socketPath'] . (is_writable($config['socketPath']) ? " is writable" : " is not writable! chown manually to www-data:www-data"), "", is_writable($config['socketPath']) ? "uk-alert uk-alert-success" : "uk-alert uk-alert-danger")); } $form->addField(new DivField("Permission Check", $liquidsoapManager->getPidFileDirectory() . (is_writable($liquidsoapManager->getPidFileDirectory()) ? " is writable" : " is not writable! chown manually to liquidsoap:www-data"), "", is_writable($liquidsoapManager->getPidFileDirectory()) ? "uk-alert uk-alert-success" : "uk-alert uk-alert-danger")); $form->addField(new DividerField()); $form->addField(new InputField("wrapperToggle", "wrapperToggle", $wrapperActive ? "Deactivate Wrapper" : "Activate Wrapper", "button", $wrapperActive ? "Deactivate Wrapper" : "Activate Wrapper", "(De)activates the wrapper liquidsoap script", $wrapperActive ? "uk-button uk-button-danger" : "uk-button uk-button-primary", 'data-status="' . ($wrapperActive ? 'started' : 'stopped') . '"'))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY)); if ($wrapperActive === false) { $form->setError("The wrapper script is not activated!"); } else { $form->setSuccess("The wrapper script is up and running!"); } $form->addField(new InputField("shoutzorToggle", "shoutzorToggle", $shoutzorActive ? "Deactivate Shoutzor" : "Activate Shoutzor", "button", $shoutzorActive ? "Deactivate Shoutzor" : "Activate Shoutzor", "(De)activates the shoutzor liquidsoap script", $shoutzorActive ? "uk-button uk-button-danger" : "uk-button uk-button-primary", 'data-status="' . ($wrapperActive ? 'started' : 'stopped') . '"'))->setValidationType(FormValidation::TYPE_STRING)->setValidationRequirements(array(FormValidation::REQ_NOTEMPTY)); if ($shoutzorActive === false) { if ($wrapperActive === false) { $form->setError("The wrapper script needs to be activated first!"); } else { $form->setError("The shoutzor script is not activated!"); } } else { $form->setSuccess("The shoutzor script is up and running!"); } $content = $form->render(); return ['$view' => ['title' => __('Shoutzor System'), 'name' => 'shoutzor:views/admin/system.php'], 'form' => $content]; }
/** * Registers node routes */ public function onRequest() { $site = App::module('system/site'); $frontpage = $site->config('frontpage'); $nodes = Node::findAll(true); uasort($nodes, function ($a, $b) { return strcmp(substr_count($a->path, '/'), substr_count($b->path, '/')) * -1; }); foreach ($nodes as $node) { if ($node->status !== 1 || !($type = $site->getType($node->type))) { continue; } $type = array_replace(['alias' => '', 'redirect' => '', 'controller' => ''], $type); $type['defaults'] = array_merge(isset($type['defaults']) ? $type['defaults'] : [], $node->get('defaults', []), ['_node' => $node->id]); $type['path'] = $node->path; $route = null; if ($node->get('alias')) { App::routes()->alias($node->path, $node->link, $type['defaults']); } elseif ($node->get('redirect')) { App::routes()->redirect($node->path, $node->get('redirect'), $type['defaults']); } elseif ($type['controller']) { App::routes()->add($type); } if (!$frontpage && isset($type['frontpage']) && $type['frontpage']) { $frontpage = $node->id; } } if ($frontpage && isset($nodes[$frontpage])) { App::routes()->alias('/', $nodes[$frontpage]->link); } else { App::routes()->get('/', function () { return __('No Frontpage assigned.'); }); } }
/** * @Route("/", methods="GET") * @Request({"folder": "string"}) */ public function indexAction($folder = '') { $images = []; $folder = trim($folder, '/'); $pttrn = '/\\.(jpg|jpeg|gif|png)$/i'; $dir = App::path(); if (!($files = glob($dir . '/' . $folder . '/*'))) { return []; } foreach ($files as $img) { // extension filter if (!preg_match($pttrn, $img)) { continue; } $data = array(); $data['filename'] = basename($img); // remove extension $data['title'] = preg_replace('/\\.[^.]+$/', '', $data['filename']); // remove leading number $data['title'] = preg_replace('/^\\d+\\s?+/', '', $data['title']); // remove trailing numbers $data['title'] = preg_replace('/\\s?+\\d+$/', '', $data['title']); // replace underscores with space and add capital $data['title'] = ucfirst(trim(str_replace(['_', '-'], ' ', $data['title']))); $data['image']['src'] = $folder . '/' . basename($img); $data['image']['alt'] = $data['title']; $images[] = $data; } return $images; }
public function __construct() { $config = App::module('shoutzor')->config('lastfm'); $this->enabled = $config['enabled'] == 1; $this->appKey = $config['apikey']; $this->secret = $config['secret']; }
/** * @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())); } }
/** * @return MailHelper */ public function sendMail() { if (!($adminMail = $this->submission->form->get('submitEmail'))) { return $this; } $user_email = $this->submission->email ?: false; $mailSubject = $this->replaceString($this->submission->form->get('email_subject')); $mailBody = $this->replaceString($this->submission->form->get('email_body')); $mailBody = App::content()->applyPlugins($mailBody, ['submission' => $this->submission, 'markdown' => $this->submission->form->get('email_body_markdown')]); try { /** @var Message $mail */ $mail = App::mailer()->create(); if ($user_email && $this->submission->form->get('use_replyto', 0)) { $mail->setReplyTo($user_email); } $mail->setTo($adminMail)->setSubject($mailSubject)->setBody(App::view('bixie/formmaker/mails/template.php', compact('mailBody')), 'text/html')->send(); if ($user_email) { $mail = App::mailer()->create(); $mail->setTo($user_email)->setSubject($mailSubject)->setBody(App::view('bixie/formmaker/mails/template.php', compact('mailBody')), 'text/html')->send(); } } catch (\Exception $e) { throw new Exception(__('Unable to send confirmation mail.')); } return $this; }
public function onAuthSuccess(AuthenticateEvent $event) { if (!($credentials = $event->getCredentials()) or !isset($credentials['username'])) { return; } App::cache()->delete($this->getCacheKey($credentials['username'])); }
protected static function getFormat($format) { $intl = App::module('system/intl'); $formats = $intl->getFormats($intl->getLocale()); $moment_format = isset($formats['DATETIME_FORMATS'][$format]) ? $formats['DATETIME_FORMATS'][$format] : $format; return strtr($moment_format, static::$intl2php); }
/** * @return array */ public function getTypes() { //todo cache this if (!$this->types) { $this->types = []; $paths = glob(App::locator()->get('formmaker:app/fields') . '/*.php', GLOB_NOSORT) ?: []; foreach ($paths as $p) { $package = array_merge(['id' => '', 'hasOptions' => 0, 'required' => 0, 'multiple' => 0, 'dependancies' => [], 'style' => [], 'prepareValue' => function (Field $field, $value) { return $value; }, 'formatValue' => function (Field $field, $value) { if (count($field->options)) { $options = $field->getOptionsRef(); if (is_array($value) && count($value)) { return array_map(function ($val) use($options) { return isset($options[$val]) ? $options[$val] : $val; }, $value); } else { return $value ? isset($options[$value]) ? [$options[$value]] : [$value] : ['-']; } } else { return is_array($value) ? count($value) ? $value : ['-'] : [$value ?: '-']; } }], include $p); $this->registerType($package); } } return $this->types; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { if (!in_array($this->option('db-driver'), ['mysql', 'sqlite'])) { $this->error("Unsupported db driver."); exit; } $this->line("Setting up Pagekit installation..."); $app = $this->container; App::module('session')->config['storage'] = 'array'; $app->boot(); $app['module']->load('installer'); $installer = new Installer($app); $dbDriver = $this->option('db-driver'); $config = ['locale' => $this->option('locale'), 'database' => ['default' => $dbDriver, 'connections' => [$dbDriver => ['dbname' => $this->option('db-name'), 'host' => $this->option('db-host'), 'user' => $this->option('db-user'), 'password' => $this->option('db-pass'), 'prefix' => $this->option('db-prefix')]]]]; $user = ['username' => $this->option('username'), 'password' => $this->option('password'), 'email' => $this->option('mail')]; $options = ['system' => ['site' => ['locale' => $this->option('locale')], 'admin' => ['locale' => $this->option('locale')]], 'system/site' => ['title' => $this->option('title')]]; $result = $installer->install($config, $options, $user); $status = $result['status']; $message = $result['message']; if ($status == 'success') { $this->line("Done"); } else { $this->error($message); } }
/** * @return \Bixie\Framework\FieldType\FieldTypeBase */ public function getFieldType() { if (!isset($this->fieldType)) { $this->fieldType = App::module('bixie/framework')->getFieldType($this->field->type); } return $this->fieldType; }
/** * {@inheritdoc} */ public function jsonSerialize() { $form = $this->toArray(); if (is_array($form['data']) && !App::user()->isAdministrator()) { unset($form['data']['submitEmail']); } return $form; }
/** * Adds protected node types. */ public function onEnable($event, $module) { foreach ((array) $module->get('nodes') as $type => $route) { if (isset($route['protected']) and $route['protected'] and !Node::where(['type = ?'], [$type])->first()) { Node::create(['title' => $route['label'], 'slug' => App::filter($route['label'], 'slugify'), 'type' => $type, 'status' => 1, 'link' => $route['name']])->save(); } } }
/** * @Request({"id", "data"}, csrf=true) */ public function saveAction($id, $data) { if (!$id || !($record = TestBD::find($id))) { App::abort(404, __('Record not found.')); } $record->save($data); return ['res' => 'success']; }
/** * @Route("/{id}", methods="DELETE", requirements={"id"="\d+"}) * @Request({"id": "int"}, csrf=true) */ public function deleteAction($id) { if (!($widget = Widget::find($id))) { App::abort(404, 'Widget not found.'); } $widget->delete(); return ['message' => 'success']; }
public function getThankyou() { if ($this->form->get('afterSubmit') == 'thankyou') { $thankyou = (new MailHelper($this))->replaceString($this->form->get('thankyou')); return App::content()->applyPlugins($thankyou, ['submission' => $this, 'markdown' => $this->form->get('thankyou_markdown')]); } return ''; }