/** * Redirects an action */ public function redirect() { if ($this->redirect) { $this->grav->redirect($this->redirect, $this->redirectCode); } else { if ($redirect = $this->grav['config']->get('plugins.login.redirect')) { $this->grav->redirect($redirect, $this->redirectCode); } } }
public function onGetPageTemplates($event) { $types = $event->types; $locator = Grav::instance()['locator']; $types->scanBlueprints($locator->findResources('plugin://' . $this->name . '/blueprints')); $types->scanTemplates($locator->findResources('plugin://' . $this->name . '/templates')); }
/** * Save the current page in a different language. Automatically switches to that language. * * @return bool True if the action was performed. */ protected function taskSaveas() { if (!$this->authorizeTask('save', $this->dataPermissions())) { return false; } $data = (array) $this->data; $language = $data['lang']; if ($language) { $this->grav['session']->admin_lang = $language ?: 'en'; } $uri = $this->grav['uri']; $obj = $this->admin->page($uri->route()); $this->preparePage($obj, false, $language); $file = $obj->file(); if ($file) { $filename = $this->determineFilenameIncludingLanguage($obj->name(), $language); $path = $obj->path() . DS . $filename; $aFile = File::instance($path); $aFile->save(); $aPage = new Page(); $aPage->init(new \SplFileInfo($path), $language . '.md'); $aPage->header($obj->header()); $aPage->rawMarkdown($obj->rawMarkdown()); $aPage->validate(); $aPage->filter(); $aPage->save(); $this->grav->fireEvent('onAdminAfterSave', new Event(['page' => $obj])); } $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info'); $this->setRedirect('/' . $language . $uri->route()); return true; }
/** * @return int|null|void */ protected function serve() { $grav = Grav::instance(); $this->output->writeln(''); $this->output->writeln('<yellow>Current Configuration:</yellow>'); $this->output->writeln(''); dump($grav['config']->get('plugins.email')); $this->output->writeln(''); require_once __DIR__ . '/../vendor/autoload.php'; $grav['Email'] = new Email(); $email_to = $this->input->getOption('to') ?: $grav['config']->get('plugins.email.to'); $subject = $this->input->getOption('subject'); $body = $this->input->getOption('body'); if (!$subject) { $subject = 'Testing Grav Email Plugin'; } if (!$body) { $configuration = print_r($grav['config']->get('plugins.email'), true); $body = $grav['language']->translate(['PLUGIN_EMAIL.TEST_EMAIL_BODY', $configuration]); } $sent = EmailUtils::sendEmail($subject, $body, $email_to); if ($sent) { $this->output->writeln("<green>Message sent successfully!</green>"); } else { $this->output->writeln("<red>Problem sending email...</red>"); } }
/** * set some instance variable states */ public function __construct() { $this->grav = Grav::instance(); $this->shortcode = $this->grav['shortcode']; $this->config = $this->grav['config']; $this->twig = $this->grav['twig']; }
public function init() { $grav = Grav::instance(); /** @var Config $config */ $config = $grav['config']; $mode = $config->get('system.debugger.mode'); TracyDebugger::$logDirectory = $config->get('system.debugger.log.enabled') ? LOG_DIR : null; TracyDebugger::$maxDepth = $config->get('system.debugger.max_depth'); // Switch debugger into development mode if configured if ($config->get('system.debugger.enabled')) { if ($config->get('system.debugger.strict')) { TracyDebugger::$strictMode = true; } if (function_exists('ini_set')) { ini_set('display_errors', true); } if ($mode == strtolower('detect')) { TracyDebugger::$productionMode = self::DETECT; } elseif ($mode == strtolower('production')) { TracyDebugger::$productionMode = self::PRODUCTION; } else { TracyDebugger::$productionMode = self::DEVELOPMENT; } } }
/** * Backup * * @param null $destination * @param callable|null $messager * * @return null|string */ public static function backup($destination = null, callable $messager = null) { if (!$destination) { $destination = Grav::instance()['locator']->findResource('backup://', true); if (!$destination) { throw new \RuntimeException('The backup folder is missing.'); } } $name = substr(strip_tags(Grav::instance()['config']->get('site.title', basename(GRAV_ROOT))), 0, 20); $inflector = new Inflector(); if (is_dir($destination)) { $date = date('YmdHis', time()); $filename = trim($inflector->hyphenize($name), '-') . '-' . $date . '.zip'; $destination = rtrim($destination, DS) . DS . $filename; } $messager && $messager(['type' => 'message', 'level' => 'info', 'message' => 'Creating new Backup "' . $destination . '"']); $messager && $messager(['type' => 'message', 'level' => 'info', 'message' => '']); $zip = new \ZipArchive(); $zip->open($destination, \ZipArchive::CREATE); $max_execution_time = ini_set('max_execution_time', 600); static::folderToZip(GRAV_ROOT, $zip, strlen(rtrim(GRAV_ROOT, DS) . DS), $messager); $messager && $messager(['type' => 'progress', 'percentage' => false, 'complete' => true]); $messager && $messager(['type' => 'message', 'level' => 'info', 'message' => '']); $messager && $messager(['type' => 'message', 'level' => 'info', 'message' => 'Saving and compressing archive...']); $zip->close(); if ($max_execution_time !== false) { ini_set('max_execution_time', $max_execution_time); } return $destination; }
/** * Twig process that renders the site layout. This is the main twig process that renders the overall * page and handles all the layout for the site display. * * @param string $format Output format (defaults to HTML). * @return string the rendered output * @throws \RuntimeException */ public function processSite($format = null) { // set the page now its been processed $this->grav->fireEvent('onTwigSiteVariables'); $pages = $this->grav['pages']; $page = $this->grav['page']; $twig_vars = $this->twig_vars; $twig_vars['pages'] = $pages->root(); $twig_vars['page'] = $page; $twig_vars['header'] = $page->header(); $twig_vars['content'] = $page->content(); $ext = '.' . ($format ? $format : 'html') . TWIG_EXT; // determine if params are set, if so disable twig cache $params = $this->grav['uri']->params(null, true); if (!empty($params)) { $this->twig->setCache(false); } // Get Twig template layout $template = $this->template($page->template() . $ext); try { $output = $this->twig->render($template, $twig_vars); } catch (\Twig_Error_Loader $e) { // If loader error, and not .html.twig, try it as fallback if ($ext != '.html' . TWIG_EXT) { try { $output = $this->twig->render($page->template() . '.html' . TWIG_EXT, $twig_vars); } catch (\Twig_Error_Loader $e) { throw new \RuntimeException($e->getRawMessage(), 404, $e); } } else { throw new \RuntimeException($e->getRawMessage(), 404, $e); } } return $output; }
/** * Create Medium from a file * * @param string $file * @param array $params * @return Medium */ public static function fromFile($file, array $params = []) { if (!file_exists($file)) { return null; } $path = dirname($file); $filename = basename($file); $parts = explode('.', $filename); $ext = array_pop($parts); $basename = implode('.', $parts); $config = Grav::instance()['config']; $media_params = $config->get("media.types." . strtolower($ext)); if (!$media_params) { return null; } $params += $media_params; // Add default settings for undefined variables. $params += $config->get('media.types.defaults'); $params += ['type' => 'file', 'thumb' => 'media/thumb.png', 'mime' => 'application/octet-stream', 'filepath' => $file, 'filename' => $filename, 'basename' => $basename, 'extension' => $ext, 'path' => $path, 'modified' => filemtime($file), 'thumbnails' => []]; $locator = Grav::instance()['locator']; $file = $locator->findResource("image://{$params['thumb']}"); if ($file) { $params['thumbnails']['default'] = $file; } return static::fromArray($params); }
public function __construct(array $items = array(), Grav $grav = null, $environment = null) { $this->grav = $grav ?: Grav::instance(); $this->finder = new ConfigFinder(); $this->environment = $environment ?: 'localhost'; $this->messages[] = 'Environment Name: ' . $this->environment; if (isset($items['@class'])) { if ($items['@class'] != get_class($this)) { throw new \InvalidArgumentException('Unrecognized config cache file!'); } // Loading pre-compiled configuration. $this->timestamp = (int) $items['timestamp']; $this->checksum = $items['checksum']; $this->items = (array) $items['data']; } else { // Make sure that if (!isset($items['streams']['schemes'])) { $items['streams']['schemes'] = []; } $items['streams']['schemes'] += $this->streams; $items = $this->autoDetectEnvironmentConfig($items); $this->messages[] = $items['streams']['schemes']['config']['prefixes']['']; parent::__construct($items); } $this->check(); }
/** * Create a RecursiveFilterIterator from a RecursiveIterator * * @param RecursiveIterator $iterator */ public function __construct(\RecursiveIterator $iterator) { parent::__construct($iterator); if (empty($this::$folder_ignores)) { $this::$folder_ignores = Grav::instance()['config']->get('system.pages.ignore_folders'); } }
/** * @return array */ public static function getSubscribedEvents() { if (!Grav::instance()['config']->get('plugins.admin-pro.enabled')) { return ['onPluginsInitialized' => [['setup', 100000], ['onPluginsInitialized', 1001]], 'onShutdown' => ['onShutdown', 1000], 'onFormProcessed' => ['onFormProcessed', 0], 'onAdminDashboard' => ['onAdminDashboard', 0]]; } return []; }
/** * Redirect to the route stored in $this->redirect */ public function redirect() { if (!$this->redirect) { return; } $base = $this->admin->base; $this->redirect = '/' . ltrim($this->redirect, '/'); $multilang = $this->isMultilang(); $redirect = ''; if ($multilang) { // if base path does not already contain the lang code, add it $langPrefix = '/' . $this->grav['session']->admin_lang; if (!Utils::startsWith($base, $langPrefix . '/')) { $base = $langPrefix . $base; } // now the first 4 chars of base contain the lang code. // if redirect path already contains the lang code, and is != than the base lang code, then use redirect path as-is if (Utils::pathPrefixedByLangCode($base) && Utils::pathPrefixedByLangCode($this->redirect) && substr($base, 0, 4) != substr($this->redirect, 0, 4)) { $redirect = $this->redirect; } else { if (!Utils::startsWith($this->redirect, $base)) { $this->redirect = $base . $this->redirect; } } } else { if (!Utils::startsWith($this->redirect, $base)) { $this->redirect = $base . $this->redirect; } } if (!$redirect) { $redirect = $this->redirect; } $this->grav->redirect($redirect, $this->redirectCode); }
/** * Load blueprints. */ protected function loadBlueprint() { if (!$this->blueprint) { $grav = Grav::instance(); $themes = $grav['themes']; $this->blueprint = $themes->get($this->name)->blueprints(); } }
public function url(array $args = []) { $grav = Grav::instance(); $url = $grav['uri']->url; $parts = Url::parse($url, true); $parts['vars'] = array_replace($parts['vars'], $args); return Url::build($parts); }
public function initTheme() { /** @var Themes $themes */ $themes = $this->grav['themes']; try { $instance = $themes->load(); } catch (\InvalidArgumentException $e) { throw new \RuntimeException($this->current() . ' theme could not be found'); } if ($instance instanceof EventSubscriberInterface) { /** @var EventDispatcher $events */ $events = $this->grav['events']; $events->addSubscriber($instance); } $this->grav['theme'] = $instance; $this->grav->fireEvent('onThemeInitialized'); }
public function init() { $this->grav = Grav::instance(); if ($this->enabled()) { $this->debugbar->addCollector(new \DebugBar\DataCollector\ConfigCollector((array) $this->grav['config']->get('system'))); } return $this; }
/** * Redirect to the route stored in $this->redirect */ public function redirect() { if (!$this->redirect) { return; } $base = $this->admin->base; $path = trim(substr($this->redirect, 0, strlen($base)) == $base ? substr($this->redirect, strlen($base)) : $this->redirect, '/'); $this->grav->redirect($base . '/' . preg_replace('|/+|', '/', $path), $this->redirectCode); }
public function resetHandlers() { $grav = Grav::instance(); $config = $grav['config']->get('system.errors'); $jsonRequest = $_SERVER && isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] == 'application/json'; // Setup Whoops-based error handler $whoops = new \Whoops\Run(); $verbosity = 1; if (isset($config['display'])) { if (is_int($config['display'])) { $verbosity = $config['display']; } else { $verbosity = $config['display'] ? 1 : 0; } } switch ($verbosity) { case 1: $error_page = new Whoops\Handler\PrettyPageHandler(); $error_page->setPageTitle('Crikey! There was an error...'); $error_page->addResourcePath(GRAV_ROOT . '/system/assets'); $error_page->addCustomCss('whoops.css'); $whoops->pushHandler($error_page); break; case -1: $whoops->pushHandler(new BareHandler()); break; default: $whoops->pushHandler(new SimplePageHandler()); break; } if (method_exists('Whoops\\Util\\Misc', 'isAjaxRequest')) { //Whoops 2.0 if (Whoops\Util\Misc::isAjaxRequest() || $jsonRequest) { $whoops->pushHandler(new Whoops\Handler\JsonResponseHandler()); } } elseif (function_exists('Whoops\\isAjaxRequest')) { //Whoops 2.0.0-alpha if (Whoops\isAjaxRequest() || $jsonRequest) { $whoops->pushHandler(new Whoops\Handler\JsonResponseHandler()); } } else { //Whoops 1.x $json_page = new Whoops\Handler\JsonResponseHandler(); $json_page->onlyForAjaxRequests(true); } if (isset($config['log']) && $config['log']) { $logger = $grav['log']; $whoops->pushHandler(function ($exception, $inspector, $run) use($logger) { try { $logger->addCritical($exception->getMessage() . ' - Trace: ' . $exception->getTraceAsString()); } catch (\Exception $e) { echo $e; } }, 'log'); } $whoops->register(); }
/** * initialize some internal instance variables */ public function __construct() { $this->grav = Grav::instance(); $this->config = $this->grav['config']; $this->handlers = new HandlerContainer(); $this->events = new EventContainer(); $this->states = []; $this->assets = []; $this->objects = []; }
/** * Initialize the debugger * * @return $this * @throws \DebugBar\DebugBarException */ public function init() { $this->grav = Grav::instance(); $this->config = $this->grav['config']; if ($this->enabled()) { $this->debugbar->addCollector(new ConfigCollector((array) $this->config->get('system'), 'Config')); $this->debugbar->addCollector(new ConfigCollector((array) $this->config->get('plugins'), 'Plugins')); } return $this; }
/** * Handle deleting a file from a blueprint * * @return bool True if the action was performed. */ protected function taskRemoveFileFromBlueprint() { $uri = $this->grav['uri']; $blueprint = base64_decode($uri->param('blueprint')); $path = base64_decode($uri->param('path')); $proute = base64_decode($uri->param('proute')); $type = $uri->param('type'); $field = $uri->param('field'); $event = $this->grav->fireEvent('onAdminCanSave', new Event(['controller' => &$this])); if (!$event['can_save']) { return false; } $this->taskRemoveMedia(); if ($type == 'pages') { $page = $this->admin->page(true, $proute); $keys = explode('.', preg_replace('/^header./', '', $field)); $header = (array) $page->header(); $data_path = implode('.', $keys); $data = Utils::getDotNotation($header, $data_path); if (isset($data[$path])) { unset($data[$path]); Utils::setDotNotation($header, $data_path, $data); $page->header($header); } $page->save(); } else { $blueprint_prefix = $type == 'config' ? '' : $type . '.'; $blueprint_name = str_replace('/blueprints', '', str_replace('config/', '', $blueprint)); $blueprint_field = $blueprint_prefix . $blueprint_name . '.' . $field; $files = $this->grav['config']->get($blueprint_field); if ($files) { foreach ($files as $key => $value) { if ($key == $path) { unset($files[$key]); } } } $this->grav['config']->set($blueprint_field, $files); switch ($type) { case 'config': $data = $this->grav['config']->get($blueprint_name); $config = $this->admin->data($blueprint, $data); $config->save(); break; case 'themes': Theme::saveConfig($blueprint_name); break; case 'plugins': Plugin::saveConfig($blueprint_name); break; } } $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.REMOVE_SUCCESSFUL')]; return true; }
/** * Redirects an action */ public function redirect() { $redirect = $this->grav['config']->get('plugins.newsletter.admin.subscriber.enable.redirect'); if (!$redirect) { $this->grav->redirect($redirect, $this->redirectCode); } else { if ($this->redirect) { $this->grav->redirect($this->redirect, $this->redirectCode); } } }
public function getAssetsPaths() { $grav = Grav::instance(); /** @var UniformResourceLocator $locator */ $locator = $grav['locator']; if (is_link($locator('user://gantry5/assets'))) { // Development environment. return ['' => ['gantry-theme://', "user://gantry5/assets/{$this->name}", 'user://gantry5/assets/common']]; } return ['' => ['gantry-theme://', 'user://gantry5/assets']]; }
public function init() { if (empty($this->plural)) { $language = Grav::instance()['language']; $this->plural = $language->translate('INFLECTOR_PLURALS', null, true); $this->singular = $language->translate('INFLECTOR_SINGULAR', null, true); $this->uncountable = $language->translate('INFLECTOR_UNCOUNTABLE', null, true); $this->irregular = $language->translate('INFLECTOR_IRREGULAR', null, true); $this->ordinals = $language->translate('INFLECTOR_ORDINALS', null, true); } }
/** * @throws \LogicException */ protected static function load() { $container = parent::load(); $container['site'] = function ($c) { return new Site(); }; // Use locator from Grav. $container['locator'] = function ($c) { return Grav::instance()['locator']; }; return $container; }
public function resetHandlers() { $grav = Grav::instance(); $config = $grav['config']->get('system.errors'); if (isset($config['display']) && !$config['display']) { unset($this->handlerStack['pretty']); $this->handlerStack = array('simple' => new SimplePageHandler()) + $this->handlerStack; } if (isset($config['log']) && !$config['log']) { unset($this->handlerStack['log']); } }
/** * @return int|null|void */ protected function serve() { $this->gpm = new GPM($this->input->getOption('force')); $packages = $this->input->getArgument('package'); $installed = false; if (!count($packages)) { $packages = ['grav']; } foreach ($packages as $package) { $package = strtolower($package); $name = null; $version = null; $updatable = false; if ($package == 'grav') { $name = 'Grav'; $version = GRAV_VERSION; $upgrader = new Upgrader(); if ($upgrader->isUpgradable()) { $updatable = ' [upgradable: v<green>' . $upgrader->getRemoteVersion() . '</green>]'; } } else { // get currently installed version $locator = \Grav\Common\Grav::instance()['locator']; $blueprints_path = $locator->findResource('plugins://' . $package . DS . 'blueprints.yaml'); if (!file_exists($blueprints_path)) { // theme? $blueprints_path = $locator->findResource('themes://' . $package . DS . 'blueprints.yaml'); if (!file_exists($blueprints_path)) { continue; } } $package_yaml = Yaml::parse(file_get_contents($blueprints_path)); $version = $package_yaml['version']; if (!$version) { continue; } $installed = $this->gpm->findPackage($package); if ($installed) { $name = $installed->name; if ($this->gpm->isUpdatable($package)) { $updatable = ' [updatable: v<green>' . $installed->available . '</green>]'; } } } $updatable = $updatable ?: ''; if ($installed || $package == 'grav') { $this->output->writeln('You are running <white>' . $name . '</white> v<cyan>' . $version . '</cyan>' . $updatable); } else { $this->output->writeln('Package <red>' . $package . '</red> not found'); } } }
protected function getItems() { $grav = Grav::instance(); // Initialize pages. $pages = $grav['pages']->all()->routable(); $items = []; /** @var Page $page */ foreach ($pages as $page) { $route = trim($page->route(), '/'); $items[] = ['name' => $route, 'field' => ['id', 'link/' . $route], 'disabled' => !$page->isPage(), 'label' => str_repeat('—', substr_count($route, '/')) . ' ' . $page->title()]; } return $items; }
public function setMessages(array $messages = []) { $this->messages = $messages; $language = Grav::instance()['language']; $this->message = $language->translate('FORM.VALIDATION_FAIL', null, true) . ' ' . $this->message; foreach ($messages as $variable => &$list) { $list = array_unique($list); foreach ($list as $message) { $this->message .= "<br/>{$message}"; } } return $this; }