Esempio n. 1
0
 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;
         }
     }
 }
Esempio n. 2
0
 /**
  * @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 [];
 }
Esempio n. 3
0
 /**
  * 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;
 }
Esempio n. 4
0
 /**
  * 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);
 }
Esempio n. 5
0
 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');
     }
 }
 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'));
 }
 /**
  * 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'];
 }
 /**
  * @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>");
     }
 }
Esempio n. 10
0
 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);
 }
Esempio n. 11
0
 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;
 }
Esempio n. 12
0
 /**
  * Load blueprints.
  */
 protected function loadBlueprint()
 {
     if (!$this->blueprint) {
         $grav = Grav::instance();
         $themes = $grav['themes'];
         $this->blueprint = $themes->get($this->name)->blueprints();
     }
 }
Esempio n. 13
0
 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 = [];
 }
Esempio n. 15
0
 /**
  * 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;
 }
Esempio n. 16
0
 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']];
 }
Esempio n. 17
0
 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);
     }
 }
Esempio n. 18
0
 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']);
     }
 }
Esempio n. 19
0
 /**
  * @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;
 }
Esempio n. 20
0
 /**
  * @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');
         }
     }
 }
Esempio n. 21
0
 /**
  * @return int|null|void
  */
 protected function serve()
 {
     $this->progress = new ProgressBar($this->output);
     $this->progress->setFormat('Archiving <cyan>%current%</cyan> files [<green>%bar%</green>] %elapsed:6s% %memory:6s%');
     Grav::instance()['config']->init();
     $destination = $this->input->getArgument('destination') ? $this->input->getArgument('destination') : null;
     $log = JsonFile::instance(Grav::instance()['locator']->findResource("log://backup.log", true, true));
     $backup = ZipBackup::backup($destination, [$this, 'output']);
     $log->content(['time' => time(), 'location' => $backup]);
     $log->save();
     $this->output->writeln('');
     $this->output->writeln('');
 }
Esempio n. 22
0
 /**
  * Persists to disk the theme parameters currently stored in the Grav Config object
  *
  * @param string $theme_name The name of the theme whose config it should store.
  *
  * @return true
  */
 public static function saveConfig($theme_name)
 {
     if (!$theme_name) {
         return false;
     }
     $locator = Grav::instance()['locator'];
     $filename = 'config://themes/' . $theme_name . '.yaml';
     $file = YamlFile::instance($locator->findResource($filename, true, true));
     $content = Grav::instance()['config']->get('themes.' . $theme_name);
     $file->save($content);
     $file->free();
     return true;
 }
Esempio n. 23
0
 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;
 }
Esempio n. 24
0
 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;
 }
Esempio n. 25
0
 public function onMenusSave(Event $event)
 {
     $defaults = ['id' => 0, 'layout' => 'list', 'target' => '_self', 'dropdown' => '', 'icon' => '', 'image' => '', 'subtitle' => '', 'icon_only' => false, 'visible' => true, 'group' => 0, 'columns' => []];
     $menu = $event->menu;
     // Each menu level has ordering from 1..n counting all menu items in the same level.
     $ordering = $this->flattenOrdering($menu['ordering']);
     $grav = Grav::instance();
     $pages = $grav['pages'];
     // Initialize pages.
     $visible = $pages->all()->visible();
     $list = [];
     /** @var Page $page */
     foreach ($visible as $page) {
         $route = trim($page->route(), '/');
         $order = isset($ordering[$route]) ? $ordering[$route] : 0;
         $parent = $page->parent();
         if ($order) {
             $list[] = $page = $page->move($parent);
             $page->order($order);
         } else {
             $list[] = $page;
         }
         $page->title($menu["items.{$route}.title"]);
         // Remove fields stored in Grav.
         if (isset($menu["items.{$route}"])) {
             unset($menu["items.{$route}.type"], $menu["items.{$route}.link"], $menu["items.{$route}.title"]);
         }
     }
     foreach ($list as $page) {
         $page->save(true);
     }
     foreach ($menu['items'] as $key => $item) {
         // Do not save default values.
         foreach ($defaults as $var => $value) {
             if (isset($item[$var]) && $item[$var] == $value) {
                 unset($item[$var]);
             }
         }
         // Do not save derived values.
         unset($item['path'], $item['alias'], $item['parent_id'], $item['level'], $item['group'], $item['current']);
         // Particles have no link.
         if (isset($item['type']) && $item['type'] === 'particle') {
             unset($item['link']);
         }
         if ($item) {
             $event->menu["items.{$key}"] = $item;
         } else {
             unset($menu["items.{$key}"]);
         }
     }
 }
Esempio n. 26
0
 /**
  * This is the same as the Gregwar Image class except this one fires a Grav Event on creation of new cached file
  *
  * @param string $type    the image type
  * @param int    $quality the quality (for JPEG)
  * @param bool   $actual
  *
  * @return mixed|string
  */
 public function cacheFile($type = 'jpg', $quality = 80, $actual = false)
 {
     if ($type == 'guess') {
         $type = $this->guessType();
     }
     if (!count($this->operations) && $type == $this->guessType() && !$this->forceCache) {
         return $this->getFilename($this->getFilePath());
     }
     // Computes the hash
     $this->hash = $this->getHash($type, $quality);
     // Generates the cache file
     $cacheFile = '';
     if (!$this->prettyName || $this->prettyPrefix) {
         $cacheFile .= $this->hash;
     }
     if ($this->prettyPrefix) {
         $cacheFile .= '-';
     }
     if ($this->prettyName) {
         $cacheFile .= $this->prettyName;
     }
     $cacheFile .= '.' . $type;
     // If the files does not exists, save it
     $image = $this;
     // Target file should be younger than all the current image
     // dependencies
     $conditions = array('younger-than' => $this->getDependencies());
     // The generating function
     $generate = function ($target) use($image, $type, $quality) {
         $result = $image->save($target, $type, $quality);
         if ($result != $target) {
             throw new GenerationError($result);
         }
         Grav::instance()->fireEvent('onImageMediumSaved', new Event(['image' => $target]));
     };
     // Asking the cache for the cacheFile
     try {
         $perms = Grav::instance()['config']->get('system.images.cache_perms', '0755');
         $perms = octdec($perms);
         $file = $this->cache->setDirectoryMode($perms)->getOrCreateFile($cacheFile, $conditions, $generate, $actual);
     } catch (GenerationError $e) {
         $file = $e->getNewFile();
     }
     if ($actual) {
         return $file;
     } else {
         return $this->getFilename($file);
     }
 }
Esempio n. 27
0
 /**
  * Matches an email to a user
  *
  * @return User
  */
 public static function findUserByEmail($email)
 {
     $account_dir = Grav::instance()['locator']->findResource('account://');
     $files = array_diff(scandir($account_dir), ['.', '..']);
     foreach ($files as $file) {
         if (strpos($file, '.yaml') !== false) {
             $user = User::load(trim(substr($file, 0, -5)));
             if ($user['email'] == $email) {
                 return $user;
             }
         }
     }
     // If a User with the provided email cannot be found, then load user with that email as the username
     return User::load($email);
 }
 /**
  * Initialization function to setup key variables needed by the MarkdownGravLinkTrait
  *
  * @param $page
  * @param $defaults
  */
 protected function init($page, $defaults)
 {
     $grav = Grav::instance();
     $this->page = $page;
     $this->BlockTypes['{'][] = "TwigTag";
     $this->special_chars = ['>' => 'gt', '<' => 'lt', '"' => 'quot'];
     if ($defaults === null) {
         $defaults = Grav::instance()['config']->get('system.pages.markdown');
     }
     $this->setBreaksEnabled($defaults['auto_line_breaks']);
     $this->setUrlsLinked($defaults['auto_url_links']);
     $this->setMarkupEscaped($defaults['escape_markup']);
     $this->setSpecialChars($defaults['special_chars']);
     $grav->fireEvent('onMarkdownInitialized', new Event(['markdown' => $this]));
 }
Esempio n. 29
0
 /**
  * Return list of all theme data with their blueprints.
  *
  * @return array
  */
 public function all()
 {
     $list = array();
     $locator = Grav::instance()['locator'];
     $iterator = new \DirectoryIterator($locator->findResource('themes://', false));
     /** @var \DirectoryIterator $directory */
     foreach ($iterator as $directory) {
         if (!$directory->isDir() || $directory->isDot()) {
             continue;
         }
         $type = $directory->getBasename();
         $list[$type] = self::get($type);
     }
     ksort($list);
     return $list;
 }
Esempio n. 30
0
 public function __construct(array $setup = 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;
     // Make sure that
     if (!isset($setup['streams']['schemes'])) {
         $setup['streams']['schemes'] = [];
     }
     $setup['streams']['schemes'] += $this->streams;
     $setup = $this->autoDetectEnvironmentConfig($setup);
     $this->setup = $setup;
     parent::__construct($setup);
     $this->check();
 }