commit 906f96a15edb382b71cabaefe45b7d7b1c615fec Author: Kévin Tessier Date: Thu May 24 18:51:55 2018 +0200 fisrt commit' diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..ef79a4b --- /dev/null +++ b/.htaccess @@ -0,0 +1,75 @@ + + +RewriteEngine On + +## Begin RewriteBase +# If you are getting 500 or 404 errors on subpages, you may have to uncomment the RewriteBase entry +# You should change the '/' to your appropriate subfolder. For example if you have +# your Grav install at the root of your site '/' should work, else it might be something +# along the lines of: RewriteBase / +## + +# RewriteBase / + +## End - RewriteBase + +## Begin - X-Forwarded-Proto +# In some hosted or load balanced environments, SSL negotiation happens upstream. +# In order for Grav to recognize the connection as secure, you need to uncomment +# the following lines. +# +# RewriteCond %{HTTP:X-Forwarded-Proto} https +# RewriteRule .* - [E=HTTPS:on] +# +## End - X-Forwarded-Proto + +## Begin - Exploits +# If you experience problems on your site block out the operations listed below +# This attempts to block the most common type of exploit `attempts` to Grav +# +# Block out any script trying to base64_encode data within the URL. +RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR] +# Block out any script that includes a ' . "\n"); + + if ($this->js_pipeline_before_excludes && $pipeline_result) { + if ($inlineGroup) { + $inline_js .= $pipeline_result; + } + else { + $output .= $pipeline_html; + } + } + foreach ($this->js_no_pipeline as $file) { + if ($group && $file['group'] == $group) { + if ($file['loading'] === 'inline') { + $inline_js .= $this->gatherLinks([$file], JS_ASSET) . "\n"; + } + else { + $output .= '' . "\n"; + } + } + } + if (!$this->js_pipeline_before_excludes && $pipeline_result) { + if ($inlineGroup) { + $inline_js .= $pipeline_result; + } + else { + $output .= $pipeline_html; + } + } + } else { + foreach ($this->js as $file) { + if ($group && $file['group'] == $group) { + if ($inlineGroup || $file['loading'] === 'inline') { + $inline_js .= $this->gatherLinks([$file], JS_ASSET) . "\n"; + } + else { + $output .= '' . "\n"; + } + } + } + } + + // Render Inline JS + foreach ($this->inline_js as $inline) { + if ($group && $inline['group'] == $group) { + $inline_js .= $inline['asset'] . "\n"; + } + } + + if ($inline_js) { + $attribute_string = isset($inline) && $inline['type'] ? " type=\"" . $inline['type'] . "\"" : ''; + $output .= "\n\n" . $inline_js . "\n\n"; + } + + return $output; + } + + /** + * Minify and concatenate CSS + * + * @param string $group + * @param bool $returnURL true if pipeline should return the URL, otherwise the content + * + * @return bool|string URL or generated content if available, else false + */ + protected function pipelineCss($group = 'head', $returnURL = true) + { + // temporary list of assets to pipeline + $temp_css = []; + + // clear no-pipeline assets lists + $this->css_no_pipeline = []; + + // Compute uid based on assets and timestamp + $uid = md5(json_encode($this->css) . $this->css_minify . $this->css_rewrite . $group); + $file = $uid . '.css'; + $inline_file = $uid . '-inline.css'; + + $relative_path = "{$this->base_url}{$this->assets_url}/{$file}"; + + // If inline files exist set them on object + if (file_exists($this->assets_dir . $inline_file)) { + $this->css_no_pipeline = json_decode(file_get_contents($this->assets_dir . $inline_file), true); + } + + // If pipeline exist return its URL or content + if (file_exists($this->assets_dir . $file)) { + if ($returnURL) { + return $relative_path . $this->getTimestamp(); + } + else { + return file_get_contents($this->assets_dir . $file) . "\n"; + } + } + + // Remove any non-pipeline files + foreach ($this->css as $id => $asset) { + if ($asset['group'] == $group) { + if (!$asset['pipeline'] || + ($asset['remote'] && $this->css_pipeline_include_externals === false)) { + $this->css_no_pipeline[$id] = $asset; + } else { + $temp_css[$id] = $asset; + } + } + } + + //if nothing found get out of here! + if (count($temp_css) == 0) { + return false; + } + + // Write non-pipeline files out + if (!empty($this->css_no_pipeline)) { + file_put_contents($this->assets_dir . $inline_file, json_encode($this->css_no_pipeline)); + } + + + $css_minify = $this->css_minify; + + // If this is a Windows server, and minify_windows is false (default value) skip the + // minification process because it will cause Apache to die/crash due to insufficient + // ThreadStackSize in httpd.conf - See: https://bugs.php.net/bug.php?id=47689 + if (strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN' && !$this->css_minify_windows) { + $css_minify = false; + } + + // Concatenate files + $buffer = $this->gatherLinks($temp_css, CSS_ASSET); + if ($css_minify) { + $minifier = new \MatthiasMullie\Minify\CSS(); + $minifier->add($buffer); + $buffer = $minifier->minify(); + } + + // Write file + if (strlen(trim($buffer)) > 0) { + file_put_contents($this->assets_dir . $file, $buffer); + + if ($returnURL) { + return $relative_path . $this->getTimestamp(); + } + else { + return $buffer . "\n"; + } + } else { + return false; + } + } + + /** + * Minify and concatenate JS files. + * + * @param string $group + * @param bool $returnURL true if pipeline should return the URL, otherwise the content + * + * @return bool|string URL or generated content if available, else false + */ + protected function pipelineJs($group = 'head', $returnURL = true) + { + // temporary list of assets to pipeline + $temp_js = []; + + // clear no-pipeline assets lists + $this->js_no_pipeline = []; + + // Compute uid based on assets and timestamp + $uid = md5(json_encode($this->js) . $this->js_minify . $group); + $file = $uid . '.js'; + $inline_file = $uid . '-inline.js'; + + $relative_path = "{$this->base_url}{$this->assets_url}/{$file}"; + + // If inline files exist set them on object + if (file_exists($this->assets_dir . $inline_file)) { + $this->js_no_pipeline = json_decode(file_get_contents($this->assets_dir . $inline_file), true); + } + + // If pipeline exist return its URL or content + if (file_exists($this->assets_dir . $file)) { + if ($returnURL) { + return $relative_path . $this->getTimestamp(); + } + else { + return file_get_contents($this->assets_dir . $file) . "\n"; + } + } + + // Remove any non-pipeline files + foreach ($this->js as $id => $asset) { + if ($asset['group'] == $group) { + if (!$asset['pipeline'] || + ($asset['remote'] && $this->js_pipeline_include_externals === false)) { + $this->js_no_pipeline[] = $asset; + } else { + $temp_js[$id] = $asset; + } + } + } + + //if nothing found get out of here! + if (count($temp_js) == 0) { + return false; + } + + // Write non-pipeline files out + if (!empty($this->js_no_pipeline)) { + file_put_contents($this->assets_dir . $inline_file, json_encode($this->js_no_pipeline)); + } + + // Concatenate files + $buffer = $this->gatherLinks($temp_js, JS_ASSET); + if ($this->js_minify) { + $minifier = new \MatthiasMullie\Minify\JS(); + $minifier->add($buffer); + $buffer = $minifier->minify(); + } + + // Write file + if (strlen(trim($buffer)) > 0) { + file_put_contents($this->assets_dir . $file, $buffer); + + if ($returnURL) { + return $relative_path . $this->getTimestamp(); + } + else { + return $buffer . "\n"; + } + } else { + return false; + } + } + + /** + * Return the array of all the registered CSS assets + * If a $key is provided, it will try to return only that asset + * else it will return null + * + * @param null|string $key the asset key + * @return array + */ + public function getCss($key = null) + { + if (!empty($key)) { + $asset_key = md5($key); + if (isset($this->css[$asset_key])) { + return $this->css[$asset_key]; + } else { + return null; + } + } + + return $this->css; + } + + /** + * Return the array of all the registered JS assets + * If a $key is provided, it will try to return only that asset + * else it will return null + * + * @param null|string $key the asset key + * @return array + */ + public function getJs($key = null) + { + if (!empty($key)) { + $asset_key = md5($key); + if (isset($this->js[$asset_key])) { + return $this->js[$asset_key]; + } else { + return null; + } + } + + return $this->js; + } + + /** + * Set the whole array of CSS assets + * + * @param $css + */ + public function setCss($css) + { + $this->css = $css; + } + + /** + * Set the whole array of JS assets + * + * @param $js + */ + public function setJs($js) + { + $this->js = $js; + } + + /** + * Removes an item from the CSS array if set + * + * @param string $key The asset key + */ + public function removeCss($key) + { + $asset_key = md5($key); + if (isset($this->css[$asset_key])) { + unset($this->css[$asset_key]); + } + } + + /** + * Removes an item from the JS array if set + * + * @param string $key The asset key + */ + public function removeJs($key) + { + $asset_key = md5($key); + if (isset($this->js[$asset_key])) { + unset($this->js[$asset_key]); + } + } + + /** + * Return the array of all the registered collections + * + * @return array + */ + public function getCollections() + { + return $this->collections; + } + + /** + * Set the array of collections explicitly + * + * @param $collections + */ + public function setCollection($collections) + { + $this->collections = $collections; + } + + /** + * Determines if an asset exists as a collection, CSS or JS reference + * + * @param $asset + * + * @return bool + */ + public function exists($asset) + { + if (isset($this->collections[$asset]) || isset($this->css[$asset]) || isset($this->js[$asset])) { + return true; + } else { + return false; + } + } + + /** + * Add/replace collection. + * + * @param string $collectionName + * @param array $assets + * @param bool $overwrite + * + * @return $this + */ + public function registerCollection($collectionName, Array $assets, $overwrite = false) + { + if ($overwrite || !isset($this->collections[$collectionName])) { + $this->collections[$collectionName] = $assets; + } + + return $this; + } + + /** + * Reset all assets. + * + * @return $this + */ + public function reset() + { + return $this->resetCss()->resetJs(); + } + + /** + * Reset JavaScript assets. + * + * @return $this + */ + public function resetJs() + { + $this->js = []; + $this->inline_js = []; + + return $this; + } + + /** + * Reset CSS assets. + * + * @return $this + */ + public function resetCss() + { + $this->css = []; + $this->inline_css = []; + + return $this; + } + + /** + * Add all JavaScript assets within $directory + * + * @param string $directory Relative to the Grav root path, or a stream identifier + * + * @return $this + */ + public function addDirJs($directory) + { + return $this->addDir($directory, self::JS_REGEX); + } + + /** + * Add all CSS assets within $directory + * + * @param string $directory Relative to the Grav root path, or a stream identifier + * + * @return $this + */ + public function addDirCss($directory) + { + return $this->addDir($directory, self::CSS_REGEX); + } + + /** + * Add all assets matching $pattern within $directory. + * + * @param string $directory Relative to the Grav root path, or a stream identifier + * @param string $pattern (regex) + * + * @return $this + * @throws Exception + */ + public function addDir($directory, $pattern = self::DEFAULT_REGEX) + { + $root_dir = rtrim(ROOT_DIR, '/'); + + // Check if $directory is a stream. + if (strpos($directory, '://')) { + $directory = Grav::instance()['locator']->findResource($directory, null); + } + + // Get files + $files = $this->rglob($root_dir . DIRECTORY_SEPARATOR . $directory, $pattern, $root_dir . '/'); + + // No luck? Nothing to do + if (!$files) { + return $this; + } + + // Add CSS files + if ($pattern === self::CSS_REGEX) { + foreach ($files as $file) { + $this->addCss($file); + } + + return $this; + } + + // Add JavaScript files + if ($pattern === self::JS_REGEX) { + foreach ($files as $file) { + $this->addJs($file); + } + + return $this; + } + + // Unknown pattern. + foreach ($files as $asset) { + $this->add($asset); + } + + return $this; + } + + /** + * Determine whether a link is local or remote. + * + * Understands both "http://" and "https://" as well as protocol agnostic links "//" + * + * @param string $link + * + * @return bool + */ + protected function isRemoteLink($link) + { + $base = Grav::instance()['uri']->rootUrl(true); + + // sanity check for local URLs with absolute URL's enabled + if (Utils::startsWith($link, $base)) { + return false; + } + + return ('http://' === substr($link, 0, 7) || 'https://' === substr($link, 0, 8) || '//' === substr($link, 0, + 2)); + } + + /** + * Build local links including grav asset shortcodes + * + * @param string $asset the asset string reference + * @param bool $absolute build absolute asset link + * + * @return string the final link url to the asset + */ + protected function buildLocalLink($asset, $absolute = false) + { + try { + $asset = Grav::instance()['locator']->findResource($asset, $absolute); + } catch (\Exception $e) { + } + + $uri = $absolute ? $asset : $this->base_url . ltrim($asset, '/'); + return $asset ? $uri : false; + } + + /** + * Get the last modification time of asset + * + * @param string $asset the asset string reference + * + * @return string the last modifcation time or false on error + */ + protected function getLastModificationTime($asset) + { + $file = GRAV_ROOT . $asset; + if (Grav::instance()['locator']->isStream($asset)) { + $file = $this->buildLocalLink($asset, true); + } + + return file_exists($file) ? filemtime($file) : false; + } + + /** + * Build an HTML attribute string from an array. + * + * @param array $attributes + * + * @return string + */ + protected function attributes(array $attributes) + { + $html = ''; + $no_key = ['loading']; + + foreach ($attributes as $key => $value) { + // For numeric keys we will assume that the key and the value are the same + // as this will convert HTML attributes such as "required" to a correct + // form like required="required" instead of using incorrect numerics. + if (is_numeric($key)) { + $key = $value; + } + if (is_array($value)) { + $value = implode(' ', $value); + } + + if (in_array($key, $no_key)) { + $element = htmlentities($value, ENT_QUOTES, 'UTF-8', false); + } else { + $element = $key . '="' . htmlentities($value, ENT_QUOTES, 'UTF-8', false) . '"'; + } + + $html .= ' ' . $element; + } + + return $html; + } + + /** + * Download and concatenate the content of several links. + * + * @param array $links + * @param bool $css + * + * @return string + */ + protected function gatherLinks(array $links, $css = true) + { + $buffer = ''; + + + foreach ($links as $asset) { + $relative_dir = ''; + $local = true; + + $link = $asset['asset']; + $relative_path = $link; + + if ($this->isRemoteLink($link)) { + $local = false; + if ('//' === substr($link, 0, 2)) { + $link = 'http:' . $link; + } + } else { + // Fix to remove relative dir if grav is in one + if (($this->base_url != '/') && (strpos($this->base_url, $link) == 0)) { + $base_url = '#' . preg_quote($this->base_url, '#') . '#'; + $relative_path = ltrim(preg_replace($base_url, '/', $link, 1), '/'); + } + + $relative_dir = dirname($relative_path); + $link = ROOT_DIR . $relative_path; + } + + $file = ($this->fetch_command instanceof Closure) ? @$this->fetch_command->__invoke($link) : @file_get_contents($link); + + // No file found, skip it... + if ($file === false) { + continue; + } + + // Double check last character being + if (!$css) { + $file = rtrim($file, ' ;') . ';'; + } + + // If this is CSS + the file is local + rewrite enabled + if ($css && $local && $this->css_rewrite) { + $file = $this->cssRewrite($file, $relative_dir); + } + + $file = rtrim($file) . PHP_EOL; + $buffer .= $file; + } + + // Pull out @imports and move to top + if ($css) { + $buffer = $this->moveImports($buffer); + } + + return $buffer; + } + + /** + * Finds relative CSS urls() and rewrites the URL with an absolute one + * + * @param string $file the css source file + * @param string $relative_path relative path to the css file + * + * @return mixed + */ + protected function cssRewrite($file, $relative_path) + { + // Strip any sourcemap comments + $file = preg_replace(self::CSS_SOURCEMAP_REGEX, '', $file); + + // Find any css url() elements, grab the URLs and calculate an absolute path + // Then replace the old url with the new one + $file = preg_replace_callback(self::CSS_URL_REGEX, function ($matches) use ($relative_path) { + + $old_url = $matches[2]; + + // Ensure link is not rooted to webserver, a data URL, or to a remote host + if (Utils::startsWith($old_url, '/') || Utils::startsWith($old_url, 'data:') || $this->isRemoteLink($old_url)) { + return $matches[0]; + } + + $new_url = $this->base_url . ltrim(Utils::normalizePath($relative_path . '/' . $old_url), '/'); + + return str_replace($old_url, $new_url, $matches[0]); + }, $file); + + return $file; + } + + /** + * Moves @import statements to the top of the file per the CSS specification + * + * @param string $file the file containing the combined CSS files + * + * @return string the modified file with any @imports at the top of the file + */ + protected function moveImports($file) + { + $this->imports = []; + + $file = preg_replace_callback(self::CSS_IMPORT_REGEX, function ($matches) { + $this->imports[] = $matches[0]; + + return ''; + }, $file); + + return implode("\n", $this->imports) . "\n\n" . $file; + } + + /** + * Recursively get files matching $pattern within $directory. + * + * @param string $directory + * @param string $pattern (regex) + * @param string $ltrim Will be trimmed from the left of the file path + * + * @return array + */ + protected function rglob($directory, $pattern, $ltrim = null) + { + $iterator = new RegexIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, + FilesystemIterator::SKIP_DOTS)), $pattern); + $offset = strlen($ltrim); + $files = []; + + foreach ($iterator as $file) { + $files[] = substr($file->getPathname(), $offset); + } + + return $files; + } + + /** + * Sets the state of CSS Pipeline + * + * @param boolean $value + */ + public function setCssPipeline($value) + { + $this->css_pipeline = (bool)$value; + } + + /** + * Sets the state of JS Pipeline + * + * @param boolean $value + */ + public function setJsPipeline($value) + { + $this->js_pipeline = (bool)$value; + } + + /** + * Explicitly set's a timestamp for assets + * + * @param $value + */ + public function setTimestamp($value) + { + $this->timestamp = $value; + } + + /** + * Get the timestamp for assets + * + * @return string + */ + public function getTimestamp($include_join = true) + { + if ($this->timestamp) { + $timestamp = $include_join ? '?' . $this->timestamp : $this->timestamp; + return $timestamp; + } + return; + } + + /** + * + * + * @param $asset + * @return string + */ + public function getQuerystring($asset) + { + $querystring = ''; + + if (!empty($asset['query'])) { + if (Utils::contains($asset['asset'], '?')) { + $querystring .= '&' . $asset['query']; + } else { + $querystring .= '?' . $asset['query']; + } + } + + if ($this->timestamp) { + if (Utils::contains($asset['asset'], '?') || $querystring) { + $querystring .= '&' . $this->timestamp; + } else { + $querystring .= '?' . $this->timestamp; + } + } + + return $querystring; + } + + /** + * @return string + */ + public function __toString() + { + return ''; + } + + /** + * @param $a + * @param $b + * + * @return mixed + */ + protected function sortAssetsByPriorityThenOrder($a, $b) + { + if ($a['priority'] == $b['priority']) { + return $a['order'] - $b['order']; + } + + return $b['priority'] - $a['priority']; + } + +} diff --git a/system/src/Grav/Common/Backup/ZipBackup.php b/system/src/Grav/Common/Backup/ZipBackup.php new file mode 100644 index 0000000..517d7da --- /dev/null +++ b/system/src/Grav/Common/Backup/ZipBackup.php @@ -0,0 +1,144 @@ +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; + } + + /** + * @param $folder + * @param $zipFile + * @param $exclusiveLength + * @param $messager + */ + private static function folderToZip($folder, \ZipArchive $zipFile, $exclusiveLength, callable $messager = null) + { + $handle = opendir($folder); + while (false !== $f = readdir($handle)) { + if ($f !== '.' && $f !== '..') { + $filePath = "$folder/$f"; + // Remove prefix from file path before add to zip. + $localPath = substr($filePath, $exclusiveLength); + + if (in_array($f, static::$ignoreFolders)) { + continue; + } + if (in_array($localPath, static::$ignorePaths)) { + $zipFile->addEmptyDir($f); + continue; + } + + if (is_file($filePath)) { + $zipFile->addFile($filePath, $localPath); + + $messager && $messager([ + 'type' => 'progress', + 'percentage' => false, + 'complete' => false + ]); + } elseif (is_dir($filePath)) { + // Add sub-directory. + $zipFile->addEmptyDir($localPath); + static::folderToZip($filePath, $zipFile, $exclusiveLength, $messager); + } + } + } + closedir($handle); + } +} diff --git a/system/src/Grav/Common/Browser.php b/system/src/Grav/Common/Browser.php new file mode 100644 index 0000000..bb0a3fb --- /dev/null +++ b/system/src/Grav/Common/Browser.php @@ -0,0 +1,137 @@ +useragent = parse_user_agent(); + } catch (\InvalidArgumentException $e) { + $this->useragent = parse_user_agent("Mozilla/5.0 (compatible; Unknown;)"); + } + } + + /** + * Get the current browser identifier + * + * Currently detected browsers: + * + * Android Browser + * BlackBerry Browser + * Camino + * Kindle / Silk + * Firefox / Iceweasel + * Safari + * Internet Explorer + * IEMobile + * Chrome + * Opera + * Midori + * Vivaldi + * TizenBrowser + * Lynx + * Wget + * Curl + * + * @return string the lowercase browser name + */ + public function getBrowser() + { + return strtolower($this->useragent['browser']); + } + + /** + * Get the current platform identifier + * + * Currently detected platforms: + * + * Desktop + * -> Windows + * -> Linux + * -> Macintosh + * -> Chrome OS + * Mobile + * -> Android + * -> iPhone + * -> iPad / iPod Touch + * -> Windows Phone OS + * -> Kindle + * -> Kindle Fire + * -> BlackBerry + * -> Playbook + * -> Tizen + * Console + * -> Nintendo 3DS + * -> New Nintendo 3DS + * -> Nintendo Wii + * -> Nintendo WiiU + * -> PlayStation 3 + * -> PlayStation 4 + * -> PlayStation Vita + * -> Xbox 360 + * -> Xbox One + * + * @return string the lowercase platform name + */ + public function getPlatform() + { + return strtolower($this->useragent['platform']); + } + + /** + * Get the current full version identifier + * + * @return string the browser full version identifier + */ + public function getLongVersion() + { + return $this->useragent['version']; + } + + /** + * Get the current major version identifier + * + * @return string the browser major version identifier + */ + public function getVersion() + { + $version = explode('.', $this->getLongVersion()); + + return intval($version[0]); + } + + /** + * Determine if the request comes from a human, or from a bot/crawler + * + * @return bool + */ + public function isHuman() + { + $browser = $this->getBrowser(); + if (empty($browser)) { + return false; + } + + if (preg_match('~(bot|crawl)~i', $browser)) { + return false; + } + + return true; + } +} diff --git a/system/src/Grav/Common/Cache.php b/system/src/Grav/Common/Cache.php new file mode 100644 index 0000000..71eb29f --- /dev/null +++ b/system/src/Grav/Common/Cache.php @@ -0,0 +1,510 @@ +init($grav); + } + + /** + * Initialization that sets a base key and the driver based on configuration settings + * + * @param Grav $grav + * + * @return void + */ + public function init(Grav $grav) + { + /** @var Config $config */ + $this->config = $grav['config']; + $this->now = time(); + + $this->cache_dir = $grav['locator']->findResource('cache://doctrine', true, true); + + /** @var Uri $uri */ + $uri = $grav['uri']; + + $prefix = $this->config->get('system.cache.prefix'); + + if (is_null($this->enabled)) { + $this->enabled = (bool)$this->config->get('system.cache.enabled'); + } + + // Cache key allows us to invalidate all cache on configuration changes. + $this->key = ($prefix ? $prefix : 'g') . '-' . substr(md5($uri->rootUrl(true) . $this->config->key() . GRAV_VERSION), + 2, 8); + + $this->driver_setting = $this->config->get('system.cache.driver'); + + $this->driver = $this->getCacheDriver(); + + // Set the cache namespace to our unique key + $this->driver->setNamespace($this->key); + } + + /** + * Public accessor to set the enabled state of the cache + * + * @param $enabled + */ + public function setEnabled($enabled) + { + $this->enabled = (bool) $enabled; + } + + /** + * Returns the current enabled state + * + * @return bool + */ + public function getEnabled() + { + return $this->enabled; + } + + /** + * Get cache state + * + * @return string + */ + public function getCacheStatus() + { + return 'Cache: [' . ($this->enabled ? 'true' : 'false') . '] Setting: [' . $this->driver_setting . '] Driver: [' . $this->driver_name . ']'; + } + + /** + * Automatically picks the cache mechanism to use. If you pick one manually it will use that + * If there is no config option for $driver in the config, or it's set to 'auto', it will + * pick the best option based on which cache extensions are installed. + * + * @return DoctrineCache\CacheProvider The cache driver to use + */ + public function getCacheDriver() + { + $setting = $this->driver_setting; + $driver_name = 'file'; + + // CLI compatibility requires a non-volatile cache driver + if ($this->config->get('system.cache.cli_compatibility') && ( + $setting == 'auto' || $this->isVolatileDriver($setting))) { + $setting = $driver_name; + } + + if (!$setting || $setting == 'auto') { + if (extension_loaded('apcu')) { + $driver_name = 'apcu'; + } elseif (extension_loaded('apc')) { + $driver_name = 'apc'; + } elseif (extension_loaded('wincache')) { + $driver_name = 'wincache'; + } elseif (extension_loaded('xcache')) { + $driver_name = 'xcache'; + } + } else { + $driver_name = $setting; + } + + $this->driver_name = $driver_name; + + switch ($driver_name) { + case 'apc': + $driver = new DoctrineCache\ApcCache(); + break; + + case 'apcu': + $driver = new DoctrineCache\ApcuCache(); + break; + + case 'wincache': + $driver = new DoctrineCache\WinCacheCache(); + break; + + case 'xcache': + $driver = new DoctrineCache\XcacheCache(); + break; + + case 'memcache': + $memcache = new \Memcache(); + $memcache->connect($this->config->get('system.cache.memcache.server', 'localhost'), + $this->config->get('system.cache.memcache.port', 11211)); + $driver = new DoctrineCache\MemcacheCache(); + $driver->setMemcache($memcache); + break; + + case 'memcached': + $memcached = new \Memcached(); + $memcached->addServer($this->config->get('system.cache.memcached.server', 'localhost'), + $this->config->get('system.cache.memcached.port', 11211)); + $driver = new DoctrineCache\MemcachedCache(); + $driver->setMemcached($memcached); + break; + + case 'redis': + $redis = new \Redis(); + $socket = $this->config->get('system.cache.redis.socket', false); + $password = $this->config->get('system.cache.redis.password', false); + + if ($socket) { + $redis->connect($socket); + } else { + $redis->connect($this->config->get('system.cache.redis.server', 'localhost'), + $this->config->get('system.cache.redis.port', 6379)); + } + + // Authenticate with password if set + if ($password && !$redis->auth($password)) { + throw new \RedisException('Redis authentication failed'); + } + + $driver = new DoctrineCache\RedisCache(); + $driver->setRedis($redis); + break; + + default: + $driver = new DoctrineCache\FilesystemCache($this->cache_dir); + break; + } + + return $driver; + } + + /** + * Gets a cached entry if it exists based on an id. If it does not exist, it returns false + * + * @param string $id the id of the cached entry + * + * @return object|bool returns the cached entry, can be any type, or false if doesn't exist + */ + public function fetch($id) + { + if ($this->enabled) { + return $this->driver->fetch($id); + } else { + return false; + } + } + + /** + * Stores a new cached entry. + * + * @param string $id the id of the cached entry + * @param array|object $data the data for the cached entry to store + * @param int $lifetime the lifetime to store the entry in seconds + */ + public function save($id, $data, $lifetime = null) + { + if ($this->enabled) { + if ($lifetime === null) { + $lifetime = $this->getLifetime(); + } + $this->driver->save($id, $data, $lifetime); + } + } + + /** + * Deletes an item in the cache based on the id + * + * @param string $id the id of the cached data entry + * @return bool true if the item was deleted successfully + */ + public function delete($id) + { + if ($this->enabled) { + return $this->driver->delete($id); + } + return false; + } + + /** + * Returns a boolean state of whether or not the item exists in the cache based on id key + * + * @param string $id the id of the cached data entry + * @return bool true if the cached items exists + */ + public function contains($id) + { + if ($this->enabled) { + return $this->driver->contains(($id)); + } + return false; + } + + /** + * Getter method to get the cache key + */ + public function getKey() + { + return $this->key; + } + + /** + * Setter method to set key (Advanced) + */ + public function setKey($key) + { + $this->key = $key; + $this->driver->setNamespace($this->key); + } + + /** + * Helper method to clear all Grav caches + * + * @param string $remove standard|all|assets-only|images-only|cache-only + * + * @return array + */ + public static function clearCache($remove = 'standard') + { + $locator = Grav::instance()['locator']; + $output = []; + $user_config = USER_DIR . 'config/system.yaml'; + + switch ($remove) { + case 'all': + $remove_paths = self::$all_remove; + break; + case 'assets-only': + $remove_paths = self::$assets_remove; + break; + case 'images-only': + $remove_paths = self::$images_remove; + break; + case 'cache-only': + $remove_paths = self::$cache_remove; + break; + case 'tmp-only': + $remove_paths = self::$tmp_remove; + break; + default: + if (Grav::instance()['config']->get('system.cache.clear_images_by_default')) { + $remove_paths = self::$standard_remove; + } else { + $remove_paths = self::$standard_remove_no_images; + } + + } + + // Clearing cache event to add paths to clear + Grav::instance()->fireEvent('onBeforeCacheClear', new Event(['remove' => $remove, 'paths' => &$remove_paths])); + + foreach ($remove_paths as $stream) { + + // Convert stream to a real path + try { + $path = $locator->findResource($stream, true, true); + if($path === false) continue; + + $anything = false; + $files = glob($path . '/*'); + + if (is_array($files)) { + foreach ($files as $file) { + if (is_link($file)) { + $output[] = 'Skipping symlink: ' . $file; + } elseif (is_file($file)) { + if (@unlink($file)) { + $anything = true; + } + } elseif (is_dir($file)) { + if (Folder::delete($file)) { + $anything = true; + } + } + } + } + + if ($anything) { + $output[] = 'Cleared: ' . $path . '/*'; + } + } catch (\Exception $e) { + // stream not found or another error while deleting files. + $output[] = 'ERROR: ' . $e->getMessage(); + } + } + + $output[] = ''; + + if (($remove == 'all' || $remove == 'standard') && file_exists($user_config)) { + touch($user_config); + + $output[] = 'Touched: ' . $user_config; + $output[] = ''; + } + + // Clear stat cache + @clearstatcache(); + + // Clear opcache + if (function_exists('opcache_reset')) { + @opcache_reset(); + } + + return $output; + } + + + /** + * Set the cache lifetime programmatically + * + * @param int $future timestamp + */ + public function setLifetime($future) + { + if (!$future) { + return; + } + + $interval = $future - $this->now; + if ($interval > 0 && $interval < $this->getLifetime()) { + $this->lifetime = $interval; + } + } + + + /** + * Retrieve the cache lifetime (in seconds) + * + * @return mixed + */ + public function getLifetime() + { + if ($this->lifetime === null) { + $this->lifetime = $this->config->get('system.cache.lifetime') ?: 604800; // 1 week default + } + + return $this->lifetime; + } + + /** + * Returns the current driver name + * + * @return mixed + */ + public function getDriverName() + { + return $this->driver_name; + } + + /** + * Returns the current driver setting + * + * @return mixed + */ + public function getDriverSetting() + { + return $this->driver_setting; + } + + /** + * is this driver a volatile driver in that it resides in PHP process memory + * + * @param $setting + * @return bool + */ + public function isVolatileDriver($setting) + { + if (in_array($setting, ['apc', 'apcu', 'xcache', 'wincache'])) { + return true; + } else { + return false; + } + } +} diff --git a/system/src/Grav/Common/Composer.php b/system/src/Grav/Common/Composer.php new file mode 100644 index 0000000..2671925 --- /dev/null +++ b/system/src/Grav/Common/Composer.php @@ -0,0 +1,60 @@ +path = $path ? rtrim($path, '\\/') . '/' : ''; + $this->cacheFolder = $cacheFolder; + $this->files = $files; + $this->timestamp = 0; + } + + /** + * Get filename for the compiled PHP file. + * + * @param string $name + * @return $this + */ + public function name($name = null) + { + if (!$this->name) { + $this->name = $name ?: md5(json_encode(array_keys($this->files))); + } + + return $this; + } + + /** + * Function gets called when cached configuration is saved. + */ + public function modified() {} + + /** + * Get timestamp of compiled configuration + * + * @return int Timestamp of compiled configuration + */ + public function timestamp() + { + return $this->timestamp ?: time(); + } + + /** + * Load the configuration. + * + * @return mixed + */ + public function load() + { + if ($this->object) { + return $this->object; + } + + $filename = $this->createFilename(); + if (!$this->loadCompiledFile($filename) && $this->loadFiles()) { + $this->saveCompiledFile($filename); + } + + return $this->object; + } + + /** + * Returns checksum from the configuration files. + * + * You can set $this->checksum = false to disable this check. + * + * @return bool|string + */ + public function checksum() + { + if (!isset($this->checksum)) { + $this->checksum = md5(json_encode($this->files) . $this->version); + } + + return $this->checksum; + } + + protected function createFilename() + { + return "{$this->cacheFolder}/{$this->name()->name}.php"; + } + + /** + * Create configuration object. + * + * @param array $data + */ + abstract protected function createObject(array $data = []); + + /** + * Finalize configuration object. + */ + abstract protected function finalizeObject(); + + /** + * Load single configuration file and append it to the correct position. + * + * @param string $name Name of the position. + * @param string $filename File to be loaded. + */ + abstract protected function loadFile($name, $filename); + + /** + * Load and join all configuration files. + * + * @return bool + * @internal + */ + protected function loadFiles() + { + $this->createObject(); + + $list = array_reverse($this->files); + foreach ($list as $files) { + foreach ($files as $name => $item) { + $this->loadFile($name, $this->path . $item['file']); + } + } + + $this->finalizeObject(); + + return true; + } + + /** + * Load compiled file. + * + * @param string $filename + * @return bool + * @internal + */ + protected function loadCompiledFile($filename) + { + if (!file_exists($filename)) { + return false; + } + + $cache = include $filename; + if ( + !is_array($cache) + || !isset($cache['checksum']) + || !isset($cache['data']) + || !isset($cache['@class']) + || $cache['@class'] != get_class($this) + ) { + return false; + } + + // Load real file if cache isn't up to date (or is invalid). + if ($cache['checksum'] !== $this->checksum()) { + return false; + } + + $this->createObject($cache['data']); + $this->timestamp = isset($cache['timestamp']) ? $cache['timestamp'] : 0; + + $this->finalizeObject(); + + return true; + } + + /** + * Save compiled file. + * + * @param string $filename + * @throws \RuntimeException + * @internal + */ + protected function saveCompiledFile($filename) + { + $file = PhpFile::instance($filename); + + // Attempt to lock the file for writing. + try { + $file->lock(false); + } catch (\Exception $e) { + // Another process has locked the file; we will check this in a bit. + } + + if ($file->locked() === false) { + // File was already locked by another process. + return; + } + + $cache = [ + '@class' => get_class($this), + 'timestamp' => time(), + 'checksum' => $this->checksum(), + 'files' => $this->files, + 'data' => $this->getState() + ]; + + $file->save($cache); + $file->unlock(); + $file->free(); + + $this->modified(); + } + + protected function getState() + { + return $this->object->toArray(); + } +} diff --git a/system/src/Grav/Common/Config/CompiledBlueprints.php b/system/src/Grav/Common/Config/CompiledBlueprints.php new file mode 100644 index 0000000..a29ecde --- /dev/null +++ b/system/src/Grav/Common/Config/CompiledBlueprints.php @@ -0,0 +1,116 @@ +checksum = false to disable this check. + * + * @return bool|string + */ + public function checksum() + { + if (null === $this->checksum) { + $this->checksum = md5(json_encode($this->files) . json_encode($this->getTypes()) . $this->version); + } + + return $this->checksum; + } + + /** + * Create configuration object. + * + * @param array $data + */ + protected function createObject(array $data = []) + { + $this->object = (new BlueprintSchema($data))->setTypes($this->getTypes()); + } + + /** + * Get list of form field types. + * + * @return array + */ + protected function getTypes() + { + return Grav::instance()['plugins']->formFieldTypes ?: []; + } + + /** + * Finalize configuration object. + */ + protected function finalizeObject() + { + } + + /** + * Load single configuration file and append it to the correct position. + * + * @param string $name Name of the position. + * @param array $files Files to be loaded. + */ + protected function loadFile($name, $files) + { + // Load blueprint file. + $blueprint = new Blueprint($files); + + $this->object->embed($name, $blueprint->load()->toArray(), '/', true); + } + + /** + * Load and join all configuration files. + * + * @return bool + * @internal + */ + protected function loadFiles() + { + $this->createObject(); + + // Convert file list into parent list. + $list = []; + /** @var array $files */ + foreach ($this->files as $files) { + foreach ($files as $name => $item) { + $list[$name][] = $this->path . $item['file']; + } + } + + // Load files. + foreach ($list as $name => $files) { + $this->loadFile($name, $files); + } + + $this->finalizeObject(); + + return true; + } + + protected function getState() + { + return $this->object->getState(); + } +} diff --git a/system/src/Grav/Common/Config/CompiledConfig.php b/system/src/Grav/Common/Config/CompiledConfig.php new file mode 100644 index 0000000..6f21123 --- /dev/null +++ b/system/src/Grav/Common/Config/CompiledConfig.php @@ -0,0 +1,103 @@ +callable = $blueprints; + + return $this; + } + + /** + * @param bool $withDefaults + * @return mixed + */ + public function load($withDefaults = false) + { + $this->withDefaults = $withDefaults; + + return parent::load(); + } + + /** + * Create configuration object. + * + * @param array $data + */ + protected function createObject(array $data = []) + { + if ($this->withDefaults && empty($data) && is_callable($this->callable)) { + $blueprints = $this->callable; + $data = $blueprints()->getDefaults(); + } + + $this->object = new Config($data, $this->callable); + } + + /** + * Finalize configuration object. + */ + protected function finalizeObject() + { + $this->object->checksum($this->checksum()); + $this->object->timestamp($this->timestamp()); + } + + /** + * Function gets called when cached configuration is saved. + */ + public function modified() + { + $this->object->modified(true); + } + + /** + * Load single configuration file and append it to the correct position. + * + * @param string $name Name of the position. + * @param string $filename File to be loaded. + */ + protected function loadFile($name, $filename) + { + $file = CompiledYamlFile::instance($filename); + $this->object->join($name, $file->content(), '/'); + $file->free(); + } +} diff --git a/system/src/Grav/Common/Config/CompiledLanguages.php b/system/src/Grav/Common/Config/CompiledLanguages.php new file mode 100644 index 0000000..610e347 --- /dev/null +++ b/system/src/Grav/Common/Config/CompiledLanguages.php @@ -0,0 +1,69 @@ +object = new Languages($data); + } + + /** + * Finalize configuration object. + */ + protected function finalizeObject() + { + $this->object->checksum($this->checksum()); + $this->object->timestamp($this->timestamp()); + } + + + /** + * Function gets called when cached configuration is saved. + */ + public function modified() + { + $this->object->modified(true); + } + + /** + * Load single configuration file and append it to the correct position. + * + * @param string $name Name of the position. + * @param string $filename File to be loaded. + */ + protected function loadFile($name, $filename) + { + $file = CompiledYamlFile::instance($filename); + if (preg_match('|languages\.yaml$|', $filename)) { + $this->object->mergeRecursive((array) $file->content()); + } else { + $this->object->mergeRecursive([$name => $file->content()]); + } + $file->free(); + } +} diff --git a/system/src/Grav/Common/Config/Config.php b/system/src/Grav/Common/Config/Config.php new file mode 100644 index 0000000..55282cd --- /dev/null +++ b/system/src/Grav/Common/Config/Config.php @@ -0,0 +1,114 @@ +checksum(); + } + + public function checksum($checksum = null) + { + if ($checksum !== null) { + $this->checksum = $checksum; + } + + return $this->checksum; + } + + public function modified($modified = null) + { + if ($modified !== null) { + $this->modified = $modified; + } + + return $this->modified; + } + + public function timestamp($timestamp = null) + { + if ($timestamp !== null) { + $this->timestamp = $timestamp; + } + + return $this->timestamp; + } + + public function reload() + { + $grav = Grav::instance(); + + // Load new configuration. + $config = ConfigServiceProvider::load($grav); + + /** @var Debugger $debugger */ + $debugger = $grav['debugger']; + + if ($config->modified()) { + // Update current configuration. + $this->items = $config->toArray(); + $this->checksum($config->checksum()); + $this->modified(true); + + $debugger->addMessage('Configuration was changed and saved.'); + } + + return $this; + } + + public function debug() + { + /** @var Debugger $debugger */ + $debugger = Grav::instance()['debugger']; + + $debugger->addMessage('Environment Name: ' . $this->environment); + if ($this->modified()) { + $debugger->addMessage('Configuration reloaded and cached.'); + } + } + + public function init() + { + $setup = Grav::instance()['setup']->toArray(); + foreach ($setup as $key => $value) { + if ($key === 'streams' || !is_array($value)) { + // Optimized as streams and simple values are fully defined in setup. + $this->items[$key] = $value; + } else { + $this->joinDefaults($key, $value); + } + } + + // Override the media.upload_limit based on PHP values + $upload_limit = Utils::getUploadLimit(); + $this->items['system']['media']['upload_limit'] = $upload_limit > 0 ? $upload_limit : 1024*1024*1024; + } + + /** + * @return mixed + * @deprecated + */ + public function getLanguages() + { + return Grav::instance()['languages']; + } +} diff --git a/system/src/Grav/Common/Config/ConfigFileFinder.php b/system/src/Grav/Common/Config/ConfigFileFinder.php new file mode 100644 index 0000000..7980671 --- /dev/null +++ b/system/src/Grav/Common/Config/ConfigFileFinder.php @@ -0,0 +1,262 @@ +base = $base ? "{$base}/" : ''; + + return $this; + } + + /** + * Return all locations for all the files with a timestamp. + * + * @param array $paths List of folders to look from. + * @param string $pattern Pattern to match the file. Pattern will also be removed from the key. + * @param int $levels Maximum number of recursive directories. + * @return array + */ + public function locateFiles(array $paths, $pattern = '|\.yaml$|', $levels = -1) + { + $list = []; + foreach ($paths as $folder) { + $list += $this->detectRecursive($folder, $pattern, $levels); + } + return $list; + } + + /** + * Return all locations for all the files with a timestamp. + * + * @param array $paths List of folders to look from. + * @param string $pattern Pattern to match the file. Pattern will also be removed from the key. + * @param int $levels Maximum number of recursive directories. + * @return array + */ + public function getFiles(array $paths, $pattern = '|\.yaml$|', $levels = -1) + { + $list = []; + foreach ($paths as $folder) { + $path = trim(Folder::getRelativePath($folder), '/'); + + $files = $this->detectRecursive($folder, $pattern, $levels); + + $list += $files[trim($path, '/')]; + } + return $list; + } + + /** + * Return all paths for all the files with a timestamp. + * + * @param array $paths List of folders to look from. + * @param string $pattern Pattern to match the file. Pattern will also be removed from the key. + * @param int $levels Maximum number of recursive directories. + * @return array + */ + public function listFiles(array $paths, $pattern = '|\.yaml$|', $levels = -1) + { + $list = []; + foreach ($paths as $folder) { + $list = array_merge_recursive($list, $this->detectAll($folder, $pattern, $levels)); + } + return $list; + } + + /** + * Find filename from a list of folders. + * + * Note: Only finds the last override. + * + * @param string $filename + * @param array $folders + * @return array + */ + public function locateFileInFolder($filename, array $folders) + { + $list = []; + foreach ($folders as $folder) { + $list += $this->detectInFolder($folder, $filename); + } + return $list; + } + + /** + * Find filename from a list of folders. + * + * @param array $folders + * @param string $filename + * @return array + */ + public function locateInFolders(array $folders, $filename = null) + { + $list = []; + foreach ($folders as $folder) { + $path = trim(Folder::getRelativePath($folder), '/'); + $list[$path] = $this->detectInFolder($folder, $filename); + } + return $list; + } + + /** + * Return all existing locations for a single file with a timestamp. + * + * @param array $paths Filesystem paths to look up from. + * @param string $name Configuration file to be located. + * @param string $ext File extension (optional, defaults to .yaml). + * @return array + */ + public function locateFile(array $paths, $name, $ext = '.yaml') + { + $filename = preg_replace('|[.\/]+|', '/', $name) . $ext; + + $list = []; + foreach ($paths as $folder) { + $path = trim(Folder::getRelativePath($folder), '/'); + + if (is_file("{$folder}/{$filename}")) { + $modified = filemtime("{$folder}/{$filename}"); + } else { + $modified = 0; + } + $basename = $this->base . $name; + $list[$path] = [$basename => ['file' => "{$path}/{$filename}", 'modified' => $modified]]; + } + + return $list; + } + + /** + * Detects all directories with a configuration file and returns them with last modification time. + * + * @param string $folder Location to look up from. + * @param string $pattern Pattern to match the file. Pattern will also be removed from the key. + * @param int $levels Maximum number of recursive directories. + * @return array + * @internal + */ + protected function detectRecursive($folder, $pattern, $levels) + { + $path = trim(Folder::getRelativePath($folder), '/'); + + if (is_dir($folder)) { + // Find all system and user configuration files. + $options = [ + 'levels' => $levels, + 'compare' => 'Filename', + 'pattern' => $pattern, + 'filters' => [ + 'pre-key' => $this->base, + 'key' => $pattern, + 'value' => function (\RecursiveDirectoryIterator $file) use ($path) { + return ['file' => "{$path}/{$file->getSubPathname()}", 'modified' => $file->getMTime()]; + } + ], + 'key' => 'SubPathname' + ]; + + $list = Folder::all($folder, $options); + + ksort($list); + } else { + $list = []; + } + + return [$path => $list]; + } + + /** + * Detects all directories with the lookup file and returns them with last modification time. + * + * @param string $folder Location to look up from. + * @param string $lookup Filename to be located (defaults to directory name). + * @return array + * @internal + */ + protected function detectInFolder($folder, $lookup = null) + { + $folder = rtrim($folder, '/'); + $path = trim(Folder::getRelativePath($folder), '/'); + $base = $path === $folder ? '' : ($path ? substr($folder, 0, -strlen($path)) : $folder . '/'); + + $list = []; + + if (is_dir($folder)) { + $iterator = new \DirectoryIterator($folder); + + /** @var \DirectoryIterator $directory */ + foreach ($iterator as $directory) { + if (!$directory->isDir() || $directory->isDot()) { + continue; + } + + $name = $directory->getBasename(); + $find = ($lookup ?: $name) . '.yaml'; + $filename = "{$path}/{$name}/{$find}"; + + if (file_exists($base . $filename)) { + $basename = $this->base . $name; + $list[$basename] = ['file' => $filename, 'modified' => filemtime($base . $filename)]; + } + } + } + + return $list; + } + + /** + * Detects all plugins with a configuration file and returns them with last modification time. + * + * @param string $folder Location to look up from. + * @param string $pattern Pattern to match the file. Pattern will also be removed from the key. + * @param int $levels Maximum number of recursive directories. + * @return array + * @internal + */ + protected function detectAll($folder, $pattern, $levels) + { + $path = trim(Folder::getRelativePath($folder), '/'); + + if (is_dir($folder)) { + // Find all system and user configuration files. + $options = [ + 'levels' => $levels, + 'compare' => 'Filename', + 'pattern' => $pattern, + 'filters' => [ + 'pre-key' => $this->base, + 'key' => $pattern, + 'value' => function (\RecursiveDirectoryIterator $file) use ($path) { + return ["{$path}/{$file->getSubPathname()}" => $file->getMTime()]; + } + ], + 'key' => 'SubPathname' + ]; + + $list = Folder::all($folder, $options); + + ksort($list); + } else { + $list = []; + } + + return $list; + } +} diff --git a/system/src/Grav/Common/Config/Languages.php b/system/src/Grav/Common/Config/Languages.php new file mode 100644 index 0000000..aa97cdb --- /dev/null +++ b/system/src/Grav/Common/Config/Languages.php @@ -0,0 +1,55 @@ +checksum = $checksum; + } + + return $this->checksum; + } + + public function modified($modified = null) + { + if ($modified !== null) { + $this->modified = $modified; + } + + return $this->modified; + } + + public function timestamp($timestamp = null) + { + if ($timestamp !== null) { + $this->timestamp = $timestamp; + } + + return $this->timestamp; + } + + public function reformat() + { + if (isset($this->items['plugins'])) { + $this->items = array_merge_recursive($this->items, $this->items['plugins']); + unset($this->items['plugins']); + } + } + + public function mergeRecursive(array $data) + { + $this->items = Utils::arrayMergeRecursiveUnique($this->items, $data); + } +} diff --git a/system/src/Grav/Common/Config/Setup.php b/system/src/Grav/Common/Config/Setup.php new file mode 100644 index 0000000..e9180fe --- /dev/null +++ b/system/src/Grav/Common/Config/Setup.php @@ -0,0 +1,279 @@ + [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['system'], + ] + ], + 'user' => [ + 'type' => 'ReadOnlyStream', + 'force' => true, + 'prefixes' => [ + '' => ['user'], + ] + ], + 'environment' => [ + 'type' => 'ReadOnlyStream' + // If not defined, environment will be set up in the constructor. + ], + 'asset' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['assets'], + ] + ], + 'blueprints' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['environment://blueprints', 'user://blueprints', 'system/blueprints'], + ] + ], + 'config' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['environment://config', 'user://config', 'system/config'], + ] + ], + 'plugins' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['user://plugins'], + ] + ], + 'plugin' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['user://plugins'], + ] + ], + 'themes' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['user://themes'], + ] + ], + 'languages' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['environment://languages', 'user://languages', 'system/languages'], + ] + ], + 'cache' => [ + 'type' => 'Stream', + 'force' => true, + 'prefixes' => [ + '' => ['cache'], + 'images' => ['images'] + ] + ], + 'log' => [ + 'type' => 'Stream', + 'force' => true, + 'prefixes' => [ + '' => ['logs'] + ] + ], + 'backup' => [ + 'type' => 'Stream', + 'force' => true, + 'prefixes' => [ + '' => ['backup'] + ] + ], + 'tmp' => [ + 'type' => 'Stream', + 'force' => true, + 'prefixes' => [ + '' => ['tmp'] + ] + ], + 'image' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['user://images', 'system://images'] + ] + ], + 'page' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['user://pages'] + ] + ], + 'account' => [ + 'type' => 'ReadOnlyStream', + 'prefixes' => [ + '' => ['user://accounts'] + ] + ], + ]; + + /** + * @param Container|array $container + */ + public function __construct($container) + { + $environment = null !== static::$environment ? static::$environment : ($container['uri']->environment() ?: 'localhost'); + + // Pre-load setup.php which contains our initial configuration. + // Configuration may contain dynamic parts, which is why we need to always load it. + // If "GRAVE_SETUP_PATH" has been defined, use it, otherwise use defaults. + $file = defined('GRAV_SETUP_PATH') ? GRAV_SETUP_PATH : GRAV_ROOT . '/setup.php'; + $setup = is_file($file) ? (array) include $file : []; + + // Add default streams defined in beginning of the class. + if (!isset($setup['streams']['schemes'])) { + $setup['streams']['schemes'] = []; + } + $setup['streams']['schemes'] += $this->streams; + + // Initialize class. + parent::__construct($setup); + + // Set up environment. + $this->def('environment', $environment ?: 'cli'); + $this->def('streams.schemes.environment.prefixes', ['' => $environment ? ["user://{$this->environment}"] : []]); + } + + /** + * @return $this + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ + public function init() + { + $locator = new UniformResourceLocator(GRAV_ROOT); + $files = []; + + $guard = 5; + do { + $check = $files; + $this->initializeLocator($locator); + $files = $locator->findResources('config://streams.yaml'); + + if ($check === $files) { + break; + } + + // Update streams. + foreach (array_reverse($files) as $path) { + $file = CompiledYamlFile::instance($path); + $content = (array)$file->content(); + if (!empty($content['schemes'])) { + $this->items['streams']['schemes'] = $content['schemes'] + $this->items['streams']['schemes']; + } + } + } while (--$guard); + + if (!$guard) { + throw new \RuntimeException('Setup: Configuration reload loop detected!'); + } + + // Make sure we have valid setup. + $this->check($locator); + + return $this; + } + + /** + * Initialize resource locator by using the configuration. + * + * @param UniformResourceLocator $locator + * @throws \BadMethodCallException + */ + public function initializeLocator(UniformResourceLocator $locator) + { + $locator->reset(); + + $schemes = (array) $this->get('streams.schemes', []); + + foreach ($schemes as $scheme => $config) { + if (isset($config['paths'])) { + $locator->addPath($scheme, '', $config['paths']); + } + + $override = isset($config['override']) ? $config['override'] : false; + $force = isset($config['force']) ? $config['force'] : false; + + if (isset($config['prefixes'])) { + foreach ((array)$config['prefixes'] as $prefix => $paths) { + $locator->addPath($scheme, $prefix, $paths, $override, $force); + } + } + } + } + + /** + * Get available streams and their types from the configuration. + * + * @return array + */ + public function getStreams() + { + $schemes = []; + foreach ((array) $this->get('streams.schemes') as $scheme => $config) { + $type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream'; + if ($type[0] !== '\\') { + $type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type; + } + + $schemes[$scheme] = $type; + } + + return $schemes; + } + + /** + * @param UniformResourceLocator $locator + * @throws \InvalidArgumentException + * @throws \BadMethodCallException + * @throws \RuntimeException + */ + protected function check(UniformResourceLocator $locator) + { + $streams = isset($this->items['streams']['schemes']) ? $this->items['streams']['schemes'] : null; + if (!is_array($streams)) { + throw new \InvalidArgumentException('Configuration is missing streams.schemes!'); + } + $diff = array_keys(array_diff_key($this->streams, $streams)); + if ($diff) { + throw new \InvalidArgumentException( + sprintf('Configuration is missing keys %s from streams.schemes!', implode(', ', $diff)) + ); + } + + if (!$locator->findResource('environment://config', true)) { + // If environment does not have its own directory, remove it from the lookup. + $this->set('streams.schemes.environment.prefixes', ['config' => []]); + $this->initializeLocator($locator); + } + + // Create security.yaml if it doesn't exist. + $filename = $locator->findResource('config://security.yaml', true, true); + $file = YamlFile::instance($filename); + if (!$file->exists()) { + $file->save(['salt' => Utils::generateRandomString(14)]); + $file->free(); + } + } +} diff --git a/system/src/Grav/Common/Data/Blueprint.php b/system/src/Grav/Common/Data/Blueprint.php new file mode 100644 index 0000000..bf33d41 --- /dev/null +++ b/system/src/Grav/Common/Data/Blueprint.php @@ -0,0 +1,254 @@ +initInternals(); + + $this->blueprintSchema->setTypes($types); + + return $this; + } + + /** + * Get nested structure containing default values defined in the blueprints. + * + * Fields without default value are ignored in the list. + * + * @return array + */ + public function getDefaults() + { + $this->initInternals(); + + return $this->blueprintSchema->getDefaults(); + } + + /** + * Merge two arrays by using blueprints. + * + * @param array $data1 + * @param array $data2 + * @param string $name Optional + * @param string $separator Optional + * @return array + */ + public function mergeData(array $data1, array $data2, $name = null, $separator = '.') + { + $this->initInternals(); + + return $this->blueprintSchema->mergeData($data1, $data2, $name, $separator); + } + + /** + * Return data fields that do not exist in blueprints. + * + * @param array $data + * @param string $prefix + * @return array + */ + public function extra(array $data, $prefix = '') + { + $this->initInternals(); + + return $this->blueprintSchema->extra($data, $prefix); + } + + /** + * Validate data against blueprints. + * + * @param array $data + * @throws \RuntimeException + */ + public function validate(array $data) + { + $this->initInternals(); + + $this->blueprintSchema->validate($data); + } + + /** + * Filter data by using blueprints. + * + * @param array $data + * @return array + */ + public function filter(array $data) + { + $this->initInternals(); + + return $this->blueprintSchema->filter($data); + } + + /** + * Return blueprint data schema. + * + * @return BlueprintSchema + */ + public function schema() + { + $this->initInternals(); + + return $this->blueprintSchema; + } + + /** + * Initialize validator. + */ + protected function initInternals() + { + if (!isset($this->blueprintSchema)) { + $types = Grav::instance()['plugins']->formFieldTypes; + + $this->blueprintSchema = new BlueprintSchema; + if ($types) { + $this->blueprintSchema->setTypes($types); + } + $this->blueprintSchema->embed('', $this->items); + $this->blueprintSchema->init(); + } + } + + /** + * @param string $filename + * @return string + */ + protected function loadFile($filename) + { + $file = CompiledYamlFile::instance($filename); + $content = $file->content(); + $file->free(); + + return $content; + } + + /** + * @param string|array $path + * @param string $context + * @return array + */ + protected function getFiles($path, $context = null) + { + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + + if (is_string($path) && !$locator->isStream($path)) { + // Find path overrides. + $paths = isset($this->overrides[$path]) ? (array) $this->overrides[$path] : []; + + // Add path pointing to default context. + if ($context === null) { + $context = $this->context; + } + if ($context && $context[strlen($context)-1] !== '/') { + $context .= '/'; + } + $path = $context . $path; + + if (!preg_match('/\.yaml$/', $path)) { + $path .= '.yaml'; + } + + $paths[] = $path; + } else { + $paths = (array) $path; + } + + $files = []; + foreach ($paths as $lookup) { + if (is_string($lookup) && strpos($lookup, '://')) { + $files = array_merge($files, $locator->findResources($lookup)); + } else { + $files[] = $lookup; + } + } + + return array_values(array_unique($files)); + } + + /** + * @param array $field + * @param string $property + * @param array $call + */ + protected function dynamicData(array &$field, $property, array &$call) + { + $params = $call['params']; + + if (is_array($params)) { + $function = array_shift($params); + } else { + $function = $params; + $params = []; + } + + list($o, $f) = preg_split('/::/', $function, 2); + if (!$f) { + if (function_exists($o)) { + $data = call_user_func_array($o, $params); + } + } else { + if (method_exists($o, $f)) { + $data = call_user_func_array(array($o, $f), $params); + } + } + + // If function returns a value, + if (isset($data)) { + if (isset($field[$property]) && is_array($field[$property]) && is_array($data)) { + // Combine field and @data-field together. + $field[$property] += $data; + } else { + // Or create/replace field with @data-field. + $field[$property] = $data; + } + } + } + + /** + * @param array $field + * @param string $property + * @param array $call + */ + protected function dynamicConfig(array &$field, $property, array &$call) + { + $value = $call['params']; + + $default = isset($field[$property]) ? $field[$property] : null; + $config = Grav::instance()['config']->get($value, $default); + + if (!is_null($config)) { + $field[$property] = $config; + } + } +} diff --git a/system/src/Grav/Common/Data/BlueprintSchema.php b/system/src/Grav/Common/Data/BlueprintSchema.php new file mode 100644 index 0000000..3205c38 --- /dev/null +++ b/system/src/Grav/Common/Data/BlueprintSchema.php @@ -0,0 +1,171 @@ + true, + 'help' => true, + 'placeholder' => true, + 'placeholder_key' => true, + 'placeholder_value' => true, + 'fields' => true + ]; + + /** + * Validate data against blueprints. + * + * @param array $data + * @throws \RuntimeException + */ + public function validate(array $data) + { + try { + $messages = $this->validateArray($data, $this->nested); + + } catch (\RuntimeException $e) { + throw (new ValidationException($e->getMessage(), $e->getCode(), $e))->setMessages(); + } + + if (!empty($messages)) { + throw (new ValidationException())->setMessages($messages); + } + } + + /** + * Filter data by using blueprints. + * + * @param array $data + * @return array + */ + public function filter(array $data) + { + return $this->filterArray($data, $this->nested); + } + + /** + * @param array $data + * @param array $rules + * @returns array + * @throws \RuntimeException + * @internal + */ + protected function validateArray(array $data, array $rules) + { + $messages = $this->checkRequired($data, $rules); + + foreach ($data as $key => $field) { + $val = isset($rules[$key]) ? $rules[$key] : (isset($rules['*']) ? $rules['*'] : null); + $rule = is_string($val) ? $this->items[$val] : null; + + if ($rule) { + // Item has been defined in blueprints. + $messages += Validation::validate($field, $rule); + } elseif (is_array($field) && is_array($val)) { + // Array has been defined in blueprints. + $messages += $this->validateArray($field, $val); + } elseif (isset($rules['validation']) && $rules['validation'] === 'strict') { + // Undefined/extra item. + throw new \RuntimeException(sprintf('%s is not defined in blueprints', $key)); + } + } + + return $messages; + } + + /** + * @param array $data + * @param array $rules + * @return array + * @internal + */ + protected function filterArray(array $data, array $rules) + { + $results = array(); + foreach ($data as $key => $field) { + $val = isset($rules[$key]) ? $rules[$key] : (isset($rules['*']) ? $rules['*'] : null); + $rule = is_string($val) ? $this->items[$val] : null; + + if ($rule) { + // Item has been defined in blueprints. + $field = Validation::filter($field, $rule); + } elseif (is_array($field) && is_array($val)) { + // Array has been defined in blueprints. + $field = $this->filterArray($field, $val); + } elseif (isset($rules['validation']) && $rules['validation'] === 'strict') { + $field = null; + } + + if (isset($field) && (!is_array($field) || !empty($field))) { + $results[$key] = $field; + } + } + + return $results; + } + + /** + * @param array $data + * @param array $fields + * @return array + */ + protected function checkRequired(array $data, array $fields) + { + $messages = []; + + foreach ($fields as $name => $field) { + if (!is_string($field)) { + continue; + } + $field = $this->items[$field]; + if (isset($field['validate']['required']) + && $field['validate']['required'] === true) { + + if (isset($data[$name])) { + continue; + } + if ($field['type'] === 'file' && isset($data['data']['name'][$name])) { //handle case of file input fields required + continue; + } + + $value = isset($field['label']) ? $field['label'] : $field['name']; + $language = Grav::instance()['language']; + $message = sprintf($language->translate('FORM.MISSING_REQUIRED_FIELD', null, true) . ' %s', $language->translate($value)); + $messages[$field['name']][] = $message; + } + } + + return $messages; + } + + /** + * @param array $field + * @param string $property + * @param array $call + */ + protected function dynamicConfig(array &$field, $property, array &$call) + { + $value = $call['params']; + + $default = isset($field[$property]) ? $field[$property] : null; + $config = Grav::instance()['config']->get($value, $default); + + if (null !== $config) { + $field[$property] = $config; + } + } +} diff --git a/system/src/Grav/Common/Data/Blueprints.php b/system/src/Grav/Common/Data/Blueprints.php new file mode 100644 index 0000000..c7090c5 --- /dev/null +++ b/system/src/Grav/Common/Data/Blueprints.php @@ -0,0 +1,100 @@ +search = $search; + } + + /** + * Get blueprint. + * + * @param string $type Blueprint type. + * @return Blueprint + * @throws \RuntimeException + */ + public function get($type) + { + if (!isset($this->instances[$type])) { + $this->instances[$type] = $this->loadFile($type); + } + + return $this->instances[$type]; + } + + /** + * Get all available blueprint types. + * + * @return array List of type=>name + */ + public function types() + { + if ($this->types === null) { + $this->types = array(); + + $grav = Grav::instance(); + + /** @var UniformResourceLocator $locator */ + $locator = $grav['locator']; + + // Get stream / directory iterator. + if ($locator->isStream($this->search)) { + $iterator = $locator->getIterator($this->search); + } else { + $iterator = new \DirectoryIterator($this->search); + } + + /** @var \DirectoryIterator $file */ + foreach ($iterator as $file) { + if (!$file->isFile() || '.' . $file->getExtension() !== YAML_EXT) { + continue; + } + $name = $file->getBasename(YAML_EXT); + $this->types[$name] = ucfirst(str_replace('_', ' ', $name)); + } + } + + return $this->types; + } + + + /** + * Load blueprint file. + * + * @param string $name Name of the blueprint. + * @return Blueprint + */ + protected function loadFile($name) + { + $blueprint = new Blueprint($name); + + if (is_array($this->search) || is_object($this->search)) { + // Page types. + $blueprint->setOverrides($this->search); + $blueprint->setContext('blueprints://pages'); + } else { + $blueprint->setContext($this->search); + } + + return $blueprint->load()->init(); + } +} diff --git a/system/src/Grav/Common/Data/Data.php b/system/src/Grav/Common/Data/Data.php new file mode 100644 index 0000000..a9ceca3 --- /dev/null +++ b/system/src/Grav/Common/Data/Data.php @@ -0,0 +1,287 @@ +items = $items; + $this->blueprints = $blueprints; + } + + /** + * Get value by using dot notation for nested arrays/objects. + * + * @example $value = $data->value('this.is.my.nested.variable'); + * + * @param string $name Dot separated path to the requested value. + * @param mixed $default Default value (or null). + * @param string $separator Separator, defaults to '.' + * @return mixed Value. + */ + public function value($name, $default = null, $separator = '.') + { + return $this->get($name, $default, $separator); + } + + /** + * Join nested values together by using blueprints. + * + * @param string $name Dot separated path to the requested value. + * @param mixed $value Value to be joined. + * @param string $separator Separator, defaults to '.' + * @return $this + * @throws \RuntimeException + */ + public function join($name, $value, $separator = '.') + { + $old = $this->get($name, null, $separator); + if ($old !== null) { + if (!is_array($old)) { + throw new \RuntimeException('Value ' . $old); + } + if (is_object($value)) { + $value = (array) $value; + } elseif (!is_array($value)) { + throw new \RuntimeException('Value ' . $value); + } + $value = $this->blueprints()->mergeData($old, $value, $name, $separator); + } + + $this->set($name, $value, $separator); + + return $this; + } + + /** + * Get nested structure containing default values defined in the blueprints. + * + * Fields without default value are ignored in the list. + + * @return array + */ + public function getDefaults() + { + return $this->blueprints()->getDefaults(); + } + + /** + * Set default values by using blueprints. + * + * @param string $name Dot separated path to the requested value. + * @param mixed $value Value to be joined. + * @param string $separator Separator, defaults to '.' + * @return $this + */ + public function joinDefaults($name, $value, $separator = '.') + { + if (is_object($value)) { + $value = (array) $value; + } + $old = $this->get($name, null, $separator); + if ($old !== null) { + $value = $this->blueprints()->mergeData($value, $old, $name, $separator); + } + + $this->set($name, $value, $separator); + + return $this; + } + + /** + * Get value from the configuration and join it with given data. + * + * @param string $name Dot separated path to the requested value. + * @param array $value Value to be joined. + * @param string $separator Separator, defaults to '.' + * @return array + * @throws \RuntimeException + */ + public function getJoined($name, $value, $separator = '.') + { + if (is_object($value)) { + $value = (array) $value; + } elseif (!is_array($value)) { + throw new \RuntimeException('Value ' . $value); + } + + $old = $this->get($name, null, $separator); + + if ($old === null) { + // No value set; no need to join data. + return $value; + } + + if (!is_array($old)) { + throw new \RuntimeException('Value ' . $old); + } + + // Return joined data. + return $this->blueprints()->mergeData($old, $value, $name, $separator); + } + + + /** + * Merge two configurations together. + * + * @param array $data + * @return $this + */ + public function merge(array $data) + { + $this->items = $this->blueprints()->mergeData($this->items, $data); + + return $this; + } + + /** + * Set default values to the configuration if variables were not set. + * + * @param array $data + * @return $this + */ + public function setDefaults(array $data) + { + $this->items = $this->blueprints()->mergeData($data, $this->items); + + return $this; + } + + /** + * Validate by blueprints. + * + * @return $this + * @throws \Exception + */ + public function validate() + { + $this->blueprints()->validate($this->items); + + return $this; + } + + /** + * @return $this + * Filter all items by using blueprints. + */ + public function filter() + { + $this->items = $this->blueprints()->filter($this->items); + + return $this; + } + + /** + * Get extra items which haven't been defined in blueprints. + * + * @return array + */ + public function extra() + { + return $this->blueprints()->extra($this->items); + } + + /** + * Return blueprints. + * + * @return Blueprint + */ + public function blueprints() + { + if (!$this->blueprints){ + $this->blueprints = new Blueprint; + } elseif (is_callable($this->blueprints)) { + // Lazy load blueprints. + $blueprints = $this->blueprints; + $this->blueprints = $blueprints(); + } + return $this->blueprints; + } + + /** + * Save data if storage has been defined. + * @throws \RuntimeException + */ + public function save() + { + $file = $this->file(); + if ($file) { + $file->save($this->items); + } + } + + /** + * Returns whether the data already exists in the storage. + * + * NOTE: This method does not check if the data is current. + * + * @return bool + */ + public function exists() + { + $file = $this->file(); + + return $file && $file->exists(); + } + + /** + * Return unmodified data as raw string. + * + * NOTE: This function only returns data which has been saved to the storage. + * + * @return string + */ + public function raw() + { + $file = $this->file(); + + return $file ? $file->raw() : ''; + } + + /** + * Set or get the data storage. + * + * @param FileInterface $storage Optionally enter a new storage. + * @return FileInterface + */ + public function file(FileInterface $storage = null) + { + if ($storage) { + $this->storage = $storage; + } + return $this->storage; + } +} diff --git a/system/src/Grav/Common/Data/DataInterface.php b/system/src/Grav/Common/Data/DataInterface.php new file mode 100644 index 0000000..aa61d26 --- /dev/null +++ b/system/src/Grav/Common/Data/DataInterface.php @@ -0,0 +1,69 @@ +value('this.is.my.nested.variable'); + * + * @param string $name Dot separated path to the requested value. + * @param mixed $default Default value (or null). + * @param string $separator Separator, defaults to '.' + * @return mixed Value. + */ + public function value($name, $default = null, $separator = '.'); + + /** + * Merge external data. + * + * @param array $data + * @return mixed + */ + public function merge(array $data); + + /** + * Return blueprints. + */ + public function blueprints(); + + /** + * Validate by blueprints. + * + * @throws \Exception + */ + public function validate(); + + /** + * Filter all items by using blueprints. + */ + public function filter(); + + /** + * Get extra items which haven't been defined in blueprints. + */ + public function extra(); + + /** + * Save data into the file. + */ + public function save(); + + /** + * Set or get the data storage. + * + * @param FileInterface $storage Optionally enter a new storage. + * @return FileInterface + */ + public function file(FileInterface $storage = null); +} diff --git a/system/src/Grav/Common/Data/Validation.php b/system/src/Grav/Common/Data/Validation.php new file mode 100644 index 0000000..8ab5cf1 --- /dev/null +++ b/system/src/Grav/Common/Data/Validation.php @@ -0,0 +1,767 @@ +translate($field['validate']['message']) + : $language->translate('FORM.INVALID_INPUT', null, true) . ' "' . $language->translate($name) . '"'; + + + // If this is a YAML field validate/filter as such + if ($type != 'yaml' && isset($field['yaml']) && $field['yaml'] === true) { + $method = 'typeYaml'; + } + + if (method_exists(__CLASS__, $method)) { + $success = self::$method($value, $validate, $field); + } else { + $success = true; + } + + if (!$success) { + $messages[$field['name']][] = $message; + } + + // Check individual rules. + foreach ($validate as $rule => $params) { + $method = 'validate' . ucfirst(strtr($rule, '-', '_')); + + if (method_exists(__CLASS__, $method)) { + $success = self::$method($value, $params); + + if (!$success) { + $messages[$field['name']][] = $message; + } + } + } + + return $messages; + } + + /** + * Filter value against a blueprint field definition. + * + * @param mixed $value + * @param array $field + * @return mixed Filtered value. + */ + public static function filter($value, array $field) + { + $validate = isset($field['validate']) ? (array) $field['validate'] : []; + + // If value isn't required, we will return null if empty value is given. + if (empty($validate['required']) && ($value === null || $value === '')) { + return null; + } + + if (!isset($field['type'])) { + $field['type'] = 'text'; + } + + + // Validate type with fallback type text. + $type = (string) isset($field['validate']['type']) ? $field['validate']['type'] : $field['type']; + $method = 'filter' . ucfirst(strtr($type, '-', '_')); + + // If this is a YAML field validate/filter as such + if ($type != 'yaml' && isset($field['yaml']) && $field['yaml'] === true) { + $method = 'filterYaml'; + } + + if (!method_exists(__CLASS__, $method)) { + $method = 'filterText'; + } + + return self::$method($value, $validate, $field); + } + + /** + * HTML5 input: text + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeText($value, array $params, array $field) + { + if (!is_string($value)) { + return false; + } + + if (isset($params['min']) && strlen($value) < $params['min']) { + return false; + } + + if (isset($params['max']) && strlen($value) > $params['max']) { + return false; + } + + $min = isset($params['min']) ? $params['min'] : 0; + if (isset($params['step']) && (strlen($value) - $min) % $params['step'] == 0) { + return false; + } + + if ((!isset($params['multiline']) || !$params['multiline']) && preg_match('/\R/um', $value)) { + return false; + } + + return true; + } + + protected static function filterText($value, array $params, array $field) + { + return (string) $value; + } + + protected static function filterCommaList($value, array $params, array $field) + { + return is_array($value) ? $value : preg_split('/\s*,\s*/', $value, -1, PREG_SPLIT_NO_EMPTY); + } + + public static function typeCommaList($value, array $params, array $field) + { + return is_array($value) ? true : self::typeText($value, $params, $field); + } + + protected static function filterLower($value, array $params) + { + return strtolower($value); + } + + protected static function filterUpper($value, array $params) + { + return strtoupper($value); + } + + + /** + * HTML5 input: textarea + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeTextarea($value, array $params, array $field) + { + if (!isset($params['multiline'])) { + $params['multiline'] = true; + } + + return self::typeText($value, $params, $field); + } + + /** + * HTML5 input: password + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typePassword($value, array $params, array $field) + { + return self::typeText($value, $params, $field); + } + + /** + * HTML5 input: hidden + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeHidden($value, array $params, array $field) + { + return self::typeText($value, $params, $field); + } + + /** + * Custom input: checkbox list + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeCheckboxes($value, array $params, array $field) + { + // Set multiple: true so checkboxes can easily use min/max counts to control number of options required + $field['multiple'] = true; + return self::typeArray((array) $value, $params, $field); + } + + protected static function filterCheckboxes($value, array $params, array $field) + { + return self::filterArray($value, $params, $field); + } + + /** + * HTML5 input: checkbox + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeCheckbox($value, array $params, array $field) + { + $value = (string) $value; + + if (!isset($field['value'])) { + $field['value'] = 1; + } + if (isset($value) && $value != $field['value']) { + return false; + } + + return true; + } + + /** + * HTML5 input: radio + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeRadio($value, array $params, array $field) + { + return self::typeArray((array) $value, $params, $field); + } + + /** + * Custom input: toggle + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeToggle($value, array $params, array $field) + { + return self::typeArray((array) $value, $params, $field); + } + + /** + * Custom input: file + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeFile($value, array $params, array $field) + { + return self::typeArray((array) $value, $params, $field); + } + + protected static function filterFile($value, array $params, array $field) + { + return (array) $value; + } + + /** + * HTML5 input: select + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeSelect($value, array $params, array $field) + { + return self::typeArray((array) $value, $params, $field); + } + + /** + * HTML5 input: number + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeNumber($value, array $params, array $field) + { + if (!is_numeric($value)) { + return false; + } + + if (isset($params['min']) && $value < $params['min']) { + return false; + } + + if (isset($params['max']) && $value > $params['max']) { + return false; + } + + $min = isset($params['min']) ? $params['min'] : 0; + if (isset($params['step']) && fmod($value - $min, $params['step']) == 0) { + return false; + } + + return true; + } + + protected static function filterNumber($value, array $params, array $field) + { + return (string)(int)$value !== (string)(float)$value ? (float) $value : (int) $value; + } + + protected static function filterDateTime($value, array $params, array $field) + { + $format = Grav::instance()['config']->get('system.pages.dateformat.default'); + if ($format) { + $converted = new \DateTime($value); + return $converted->format($format); + } + return $value; + } + + + /** + * HTML5 input: range + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeRange($value, array $params, array $field) + { + return self::typeNumber($value, $params, $field); + } + + protected static function filterRange($value, array $params, array $field) + { + return self::filterNumber($value, $params, $field); + } + + /** + * HTML5 input: color + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeColor($value, array $params, array $field) + { + return preg_match('/^\#[0-9a-fA-F]{3}[0-9a-fA-F]{3}?$/u', $value); + } + + /** + * HTML5 input: email + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeEmail($value, array $params, array $field) + { + $values = !is_array($value) ? explode(',', preg_replace('/\s+/', '', $value)) : $value; + + foreach ($values as $value) { + if (!(self::typeText($value, $params, $field) && filter_var($value, FILTER_VALIDATE_EMAIL))) { + return false; + } + } + + return true; + } + + /** + * HTML5 input: url + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + + public static function typeUrl($value, array $params, array $field) + { + return self::typeText($value, $params, $field) && filter_var($value, FILTER_VALIDATE_URL); + } + + /** + * HTML5 input: datetime + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeDatetime($value, array $params, array $field) + { + if ($value instanceof \DateTime) { + return true; + } elseif (!is_string($value)) { + return false; + } elseif (!isset($params['format'])) { + return false !== strtotime($value); + } + + $dateFromFormat = \DateTime::createFromFormat($params['format'], $value); + + return $dateFromFormat && $value === date($params['format'], $dateFromFormat->getTimestamp()); + } + + /** + * HTML5 input: datetime-local + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeDatetimeLocal($value, array $params, array $field) + { + return self::typeDatetime($value, $params, $field); + } + + /** + * HTML5 input: date + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeDate($value, array $params, array $field) + { + $params = array($params); + if (!isset($params['format'])) { + $params['format'] = 'Y-m-d'; + } + return self::typeDatetime($value, $params, $field); + } + + /** + * HTML5 input: time + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeTime($value, array $params, array $field) + { + $params = array($params); + if (!isset($params['format'])) { + $params['format'] = 'H:i'; + } + return self::typeDatetime($value, $params, $field); + } + + /** + * HTML5 input: month + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeMonth($value, array $params, array $field) + { + $params = array($params); + if (!isset($params['format'])) { + $params['format'] = 'Y-m'; + } + return self::typeDatetime($value, $params, $field); + } + + /** + * HTML5 input: week + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeWeek($value, array $params, array $field) + { + if (!isset($params['format']) && !preg_match('/^\d{4}-W\d{2}$/u', $value)) { + return false; + } + return self::typeDatetime($value, $params, $field); + } + + /** + * Custom input: array + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeArray($value, array $params, array $field) + { + if (!is_array($value)) { + return false; + } + + if (isset($field['multiple'])) { + if (isset($params['min']) && count($value) < $params['min']) { + return false; + } + + if (isset($params['max']) && count($value) > $params['max']) { + return false; + } + + $min = isset($params['min']) ? $params['min'] : 0; + if (isset($params['step']) && (count($value) - $min) % $params['step'] == 0) { + return false; + } + } + + $options = isset($field['options']) ? array_keys($field['options']) : array(); + $values = isset($field['use']) && $field['use'] == 'keys' ? array_keys($value) : $value; + if ($options && array_diff($values, $options)) { + return false; + } + + return true; + } + + protected static function filterArray($value, $params, $field) + { + $values = (array) $value; + $options = isset($field['options']) ? array_keys($field['options']) : array(); + $multi = isset($field['multiple']) ? $field['multiple'] : false; + + if (count($values) == 1 && isset($values[0]) && $values[0] == '') { + return null; + } + + + if ($options) { + $useKey = isset($field['use']) && $field['use'] == 'keys'; + foreach ($values as $key => $value) { + $values[$key] = $useKey ? (bool) $value : $value; + } + } + + if ($multi) { + foreach ($values as $key => $value) { + if (is_array($value)) { + $value = implode(',', $value); + $values[$key] = array_map('trim', explode(',', $value)); + } else { + $values[$key] = trim($value); + } + } + } + + if (isset($field['ignore_empty']) && Utils::isPositive($field['ignore_empty'])) { + foreach ($values as $key => $value) { + foreach ($value as $inner_key => $inner_value) { + if ($inner_value == '') { + unset($value[$inner_key]); + } + } + + $values[$key] = $value; + } + } + + return $values; + } + + public static function typeList($value, array $params, array $field) + { + if (!is_array($value)) { + return false; + } + + if (isset($field['fields'])) { + foreach ($value as $key => $item) { + foreach ($field['fields'] as $subKey => $subField) { + $subKey = trim($subKey, '.'); + $subValue = isset($item[$subKey]) ? $item[$subKey] : null; + self::validate($subValue, $subField); + } + } + } + + return true; + } + + protected static function filterList($value, array $params, array $field) + { + return (array) $value; + } + + public static function filterYaml($value, $params) + { + try { + if (is_string($value)) { + return (array) Yaml::parse($value); + } else { + return $value; + } + } catch (ParseException $e) { + return $value; + } + } + + /** + * Custom input: ignore (will not validate) + * + * @param mixed $value Value to be validated. + * @param array $params Validation parameters. + * @param array $field Blueprint for the field. + * @return bool True if validation succeeded. + */ + public static function typeIgnore($value, array $params, array $field) + { + return true; + } + + public static function filterIgnore($value, array $params, array $field) + { + return $value; + } + + + // HTML5 attributes (min, max and range are handled inside the types) + + public static function validateRequired($value, $params) + { + if (is_scalar($value)) { + return (bool) $params !== true || $value !== ''; + } else { + return (bool) $params !== true || !empty($value); + } + } + + public static function validatePattern($value, $params) + { + return (bool) preg_match("`^{$params}$`u", $value); + } + + + // Internal types + + public static function validateAlpha($value, $params) + { + return ctype_alpha($value); + } + + public static function validateAlnum($value, $params) + { + return ctype_alnum($value); + } + + public static function typeBool($value, $params) + { + return is_bool($value) || $value == 1 || $value == 0; + } + + public static function validateBool($value, $params) + { + return is_bool($value) || $value == 1 || $value == 0; + } + + protected static function filterBool($value, $params) + { + return (bool) $value; + } + + public static function validateDigit($value, $params) + { + return ctype_digit($value); + } + + public static function validateFloat($value, $params) + { + return is_float(filter_var($value, FILTER_VALIDATE_FLOAT)); + } + + protected static function filterFloat($value, $params) + { + return (float) $value; + } + + public static function validateHex($value, $params) + { + return ctype_xdigit($value); + } + + public static function validateInt($value, $params) + { + return is_numeric($value) && (int) $value == $value; + } + + protected static function filterInt($value, $params) + { + return (int) $value; + } + + public static function validateArray($value, $params) + { + return is_array($value) + || ($value instanceof \ArrayAccess + && $value instanceof \Traversable + && $value instanceof \Countable); + } + + public static function filterItem_List($value, $params) + { + return array_values(array_filter($value, function($v) { return !empty($v); } )); + } + + public static function validateJson($value, $params) + { + return (bool) (@json_decode($value)); + } +} diff --git a/system/src/Grav/Common/Data/ValidationException.php b/system/src/Grav/Common/Data/ValidationException.php new file mode 100644 index 0000000..9272894 --- /dev/null +++ b/system/src/Grav/Common/Data/ValidationException.php @@ -0,0 +1,37 @@ +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 .= "
$message"; + } + } + + return $this; + } + + public function getMessages() + { + return $this->messages; + } +} diff --git a/system/src/Grav/Common/Debugger.php b/system/src/Grav/Common/Debugger.php new file mode 100644 index 0000000..4687325 --- /dev/null +++ b/system/src/Grav/Common/Debugger.php @@ -0,0 +1,275 @@ +init() gets called. + $this->enabled = true; + + $this->debugbar = new StandardDebugBar(); + $this->debugbar['time']->addMeasure('Loading', $this->debugbar['time']->getRequestStartTime(), microtime(true)); + } + + /** + * Initialize the debugger + * + * @return $this + * @throws \DebugBar\DebugBarException + */ + public function init() + { + $this->grav = Grav::instance(); + $this->config = $this->grav['config']; + + // Enable/disable debugger based on configuration. + $this->enabled = $this->config->get('system.debugger.enabled'); + + 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; + } + + /** + * Set/get the enabled state of the debugger + * + * @param bool $state If null, the method returns the enabled value. If set, the method sets the enabled state + * + * @return null + */ + public function enabled($state = null) + { + if ($state !== null) { + $this->enabled = $state; + } + + return $this->enabled; + } + + /** + * Add the debugger assets to the Grav Assets + * + * @return $this + */ + public function addAssets() + { + if ($this->enabled()) { + + // Only add assets if Page is HTML + $page = $this->grav['page']; + if ($page->templateFormat() !== 'html') { + return $this; + } + + /** @var Assets $assets */ + $assets = $this->grav['assets']; + + // Add jquery library + $assets->add('jquery', 101); + + $this->renderer = $this->debugbar->getJavascriptRenderer(); + $this->renderer->setIncludeVendors(false); + + // Get the required CSS files + list($css_files, $js_files) = $this->renderer->getAssets(null, JavascriptRenderer::RELATIVE_URL); + foreach ((array)$css_files as $css) { + $assets->addCss($css); + } + + $assets->addCss('/system/assets/debugger.css'); + + foreach ((array)$js_files as $js) { + $assets->addJs($js); + } + } + + return $this; + } + + public function getCaller($ignore = 2) + { + $trace = debug_backtrace(false, $ignore); + + return array_pop($trace); + } + + /** + * Adds a data collector + * + * @param $collector + * + * @return $this + * @throws \DebugBar\DebugBarException + */ + public function addCollector($collector) + { + $this->debugbar->addCollector($collector); + + return $this; + } + + /** + * Returns a data collector + * + * @param $collector + * + * @return \DebugBar\DataCollector\DataCollectorInterface + * @throws \DebugBar\DebugBarException + */ + public function getCollector($collector) + { + return $this->debugbar->getCollector($collector); + } + + /** + * Displays the debug bar + * + * @return $this + */ + public function render() + { + if ($this->enabled()) { + // Only add assets if Page is HTML + $page = $this->grav['page']; + if (!$this->renderer || $page->templateFormat() !== 'html') { + return $this; + } + + echo $this->renderer->render(); + } + + return $this; + } + + /** + * Sends the data through the HTTP headers + * + * @return $this + */ + public function sendDataInHeaders() + { + if ($this->enabled()) { + $this->debugbar->sendDataInHeaders(); + } + + return $this; + } + + /** + * Returns collected debugger data. + * + * @return array + */ + public function getData() + { + if (!$this->enabled()) { + return null; + } + + $this->timers = []; + + return $this->debugbar->getData(); + } + + /** + * Start a timer with an associated name and description + * + * @param $name + * @param string|null $description + * + * @return $this + */ + public function startTimer($name, $description = null) + { + if ($name[0] === '_' || $this->enabled()) { + $this->debugbar['time']->startMeasure($name, $description); + $this->timers[] = $name; + } + + return $this; + } + + /** + * Stop the named timer + * + * @param string $name + * + * @return $this + */ + public function stopTimer($name) + { + if (in_array($name, $this->timers, true) && ($name[0] === '_' || $this->enabled())) { + $this->debugbar['time']->stopMeasure($name); + } + + return $this; + } + + /** + * Dump variables into the Messages tab of the Debug Bar + * + * @param $message + * @param string $label + * @param bool $isString + * + * @return $this + */ + public function addMessage($message, $label = 'info', $isString = true) + { + if ($this->enabled()) { + $this->debugbar['messages']->addMessage($message, $label, $isString); + } + + return $this; + } + + /** + * Dump exception into the Messages tab of the Debug Bar + * + * @param \Exception $e + * @return Debugger + */ + public function addException(\Exception $e) + { + if ($this->enabled()) { + $this->debugbar['exceptions']->addException($e); + } + + return $this; + } +} diff --git a/system/src/Grav/Common/Errors/BareHandler.php b/system/src/Grav/Common/Errors/BareHandler.php new file mode 100644 index 0000000..5d8ef9a --- /dev/null +++ b/system/src/Grav/Common/Errors/BareHandler.php @@ -0,0 +1,24 @@ +get('system.errors'); + $jsonRequest = $_SERVER && isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] == 'application/json'; + + // Setup Whoops-based error handler + $system = new SystemFacade; + $whoops = new \Whoops\Run($system); + + $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(); + } +} diff --git a/system/src/Grav/Common/Errors/Resources/error.css b/system/src/Grav/Common/Errors/Resources/error.css new file mode 100644 index 0000000..11ce3fd --- /dev/null +++ b/system/src/Grav/Common/Errors/Resources/error.css @@ -0,0 +1,52 @@ +html, body { + height: 100% +} +body { + margin:0 3rem; + padding:0; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 1.5rem; + line-height: 1.4; + display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */ + display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */ + display: -ms-flexbox; /* TWEENER - IE 10 */ + display: -webkit-flex; /* NEW - Chrome */ + display: flex; + -webkit-align-items: center; + align-items: center; + -webkit-justify-content: center; + justify-content: center; +} +.container { + margin: 0rem; + max-width: 600px; + padding-bottom:5rem; +} + +header { + color: #000; + font-size: 4rem; + letter-spacing: 2px; + line-height: 1.1; + margin-bottom: 2rem; +} +p { + font-family: Optima, Segoe, "Segoe UI", Candara, Calibri, Arial, sans-serif; + color: #666; +} + +h5 { + font-weight: normal; + color: #999; + font-size: 1rem; +} + +h6 { + font-weight: normal; + color: #999; +} + +code { + font-weight: bold; + font-family: Menlo, Monaco, Consolas, "Courier New", monospace; +} diff --git a/system/src/Grav/Common/Errors/Resources/layout.html.php b/system/src/Grav/Common/Errors/Resources/layout.html.php new file mode 100644 index 0000000..6699959 --- /dev/null +++ b/system/src/Grav/Common/Errors/Resources/layout.html.php @@ -0,0 +1,30 @@ + + + + + + Whoops there was an error! + + + +
+
+
+ Server Error +
+ + + +

Sorry, something went terribly wrong!

+ +

-

+ +
For further details please review your logs/ folder, or enable displaying of errors in your system configuration.
+
+
+ + diff --git a/system/src/Grav/Common/Errors/SimplePageHandler.php b/system/src/Grav/Common/Errors/SimplePageHandler.php new file mode 100644 index 0000000..fb2e73f --- /dev/null +++ b/system/src/Grav/Common/Errors/SimplePageHandler.php @@ -0,0 +1,103 @@ +searchPaths[] = __DIR__ . "/Resources"; + } + + /** + * @return int|null + */ + public function handle() + { + $inspector = $this->getInspector(); + + $helper = new TemplateHelper(); + $templateFile = $this->getResource("layout.html.php"); + $cssFile = $this->getResource("error.css"); + + $code = $inspector->getException()->getCode(); + $message = $inspector->getException()->getMessage(); + + if ($inspector->getException() instanceof \ErrorException) { + $code = Misc::translateErrorCode($code); + } + + $vars = array( + "stylesheet" => file_get_contents($cssFile), + "code" => $code, + "message" => filter_var(rawurldecode($message), FILTER_SANITIZE_STRING), + ); + + $helper->setVariables($vars); + $helper->render($templateFile); + + return Handler::QUIT; + } + + /** + * @param $resource + * + * @return string + * @throws \RuntimeException + */ + protected function getResource($resource) + { + // If the resource was found before, we can speed things up + // by caching its absolute, resolved path: + if (isset($this->resourceCache[$resource])) { + return $this->resourceCache[$resource]; + } + + // Search through available search paths, until we find the + // resource we're after: + foreach ($this->searchPaths as $path) { + $fullPath = $path . "/$resource"; + + if (is_file($fullPath)) { + // Cache the result: + $this->resourceCache[$resource] = $fullPath; + return $fullPath; + } + } + + // If we got this far, nothing was found. + throw new \RuntimeException( + "Could not find resource '{$resource}' in any resource paths (searched: " . implode(', ', $this->searchPaths). ')' + ); + } + + public function addResourcePath($path) + { + if (!is_dir($path)) { + throw new \InvalidArgumentException( + "'{$path}' is not a valid directory" + ); + } + + array_unshift($this->searchPaths, $path); + } + + public function getResourcePaths() + { + return $this->searchPaths; + } +} diff --git a/system/src/Grav/Common/Errors/SystemFacade.php b/system/src/Grav/Common/Errors/SystemFacade.php new file mode 100644 index 0000000..5b73a2b --- /dev/null +++ b/system/src/Grav/Common/Errors/SystemFacade.php @@ -0,0 +1,39 @@ +whoopsShutdownHandler = $function; + register_shutdown_function([$this, 'handleShutdown']); + } + + /** + * Special case to deal with Fatal errors and the like. + */ + public function handleShutdown() + { + $error = $this->getLastError(); + + // Ignore core warnings and errors. + if ($error && !($error['type'] & (E_CORE_WARNING | E_CORE_ERROR))) { + $handler = $this->whoopsShutdownHandler; + $handler(); + } + } +} diff --git a/system/src/Grav/Common/File/CompiledFile.php b/system/src/Grav/Common/File/CompiledFile.php new file mode 100644 index 0000000..a0e230f --- /dev/null +++ b/system/src/Grav/Common/File/CompiledFile.php @@ -0,0 +1,88 @@ +settings(['native' => true, 'compat' => true]); + + try { + // If nothing has been loaded, attempt to get pre-compiled version of the file first. + if ($var === null && $this->raw === null && $this->content === null) { + $key = md5($this->filename); + $file = PhpFile::instance(CACHE_DIR . "compiled/files/{$key}{$this->extension}.php"); + + $modified = $this->modified(); + + if (!$modified) { + return $this->decode($this->raw()); + } + + $class = get_class($this); + + $cache = $file->exists() ? $file->content() : null; + + // Load real file if cache isn't up to date (or is invalid). + if ( + !isset($cache['@class']) + || $cache['@class'] !== $class + || $cache['modified'] !== $modified + || $cache['filename'] !== $this->filename + ) { + // Attempt to lock the file for writing. + try { + $file->lock(false); + } catch (\Exception $e) { + // Another process has locked the file; we will check this in a bit. + } + + // Decode RAW file into compiled array. + $data = (array)$this->decode($this->raw()); + $cache = [ + '@class' => $class, + 'filename' => $this->filename, + 'modified' => $modified, + 'data' => $data + ]; + + // If compiled file wasn't already locked by another process, save it. + if ($file->locked() !== false) { + $file->save($cache); + $file->unlock(); + + // Compile cached file into bytecode cache + if (function_exists('opcache_invalidate')) { + // Silence error if function exists, but is restricted. + @opcache_invalidate($file->filename(), true); + } + } + } + $file->free(); + + $this->content = $cache['data']; + } + + } catch (\Exception $e) { + throw new \RuntimeException(sprintf('Failed to read %s: %s', basename($this->filename), $e->getMessage()), 500, $e); + } + + return parent::content($var); + } +} diff --git a/system/src/Grav/Common/File/CompiledJsonFile.php b/system/src/Grav/Common/File/CompiledJsonFile.php new file mode 100644 index 0000000..c2a9a32 --- /dev/null +++ b/system/src/Grav/Common/File/CompiledJsonFile.php @@ -0,0 +1,28 @@ +isStream($path)) { + $directory = $locator->getRecursiveIterator($path, $flags); + } else { + $directory = new \RecursiveDirectoryIterator($path, $flags); + } + $filter = new RecursiveFolderFilterIterator($directory); + $iterator = new \RecursiveIteratorIterator($filter, \RecursiveIteratorIterator::SELF_FIRST); + + /** @var \RecursiveDirectoryIterator $file */ + foreach ($iterator as $dir) { + $dir_modified = $dir->getMTime(); + if ($dir_modified > $last_modified) { + $last_modified = $dir_modified; + } + } + + return $last_modified; + } + + /** + * Recursively find the last modified time under given path by file. + * + * @param string $path + * @param string $extensions which files to search for specifically + * + * @return int + */ + public static function lastModifiedFile($path, $extensions = 'md|yaml') + { + $last_modified = 0; + + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + $flags = \RecursiveDirectoryIterator::SKIP_DOTS; + if ($locator->isStream($path)) { + $directory = $locator->getRecursiveIterator($path, $flags); + } else { + $directory = new \RecursiveDirectoryIterator($path, $flags); + } + $recursive = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::SELF_FIRST); + $iterator = new \RegexIterator($recursive, '/^.+\.'.$extensions.'$/i'); + + /** @var \RecursiveDirectoryIterator $file */ + foreach ($iterator as $filepath => $file) { + try { + $file_modified = $file->getMTime(); + if ($file_modified > $last_modified) { + $last_modified = $file_modified; + } + } catch (\Exception $e) { + Grav::instance()['log']->error('Could not process file: ' . $e->getMessage()); + } + } + + return $last_modified; + } + + /** + * Recursively md5 hash all files in a path + * + * @param $path + * @return string + */ + public static function hashAllFiles($path) + { + $flags = \RecursiveDirectoryIterator::SKIP_DOTS; + $files = []; + + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + if ($locator->isStream($path)) { + $directory = $locator->getRecursiveIterator($path, $flags); + } else { + $directory = new \RecursiveDirectoryIterator($path, $flags); + } + + $iterator = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::SELF_FIRST); + + foreach ($iterator as $file) { + $files[] = $file->getPathname() . '?'. $file->getMTime(); + } + + return md5(serialize($files)); + } + + /** + * Get relative path between target and base path. If path isn't relative, return full path. + * + * @param string $path + * @param mixed|string $base + * + * @return string + */ + public static function getRelativePath($path, $base = GRAV_ROOT) + { + if ($base) { + $base = preg_replace('![\\\/]+!', '/', $base); + $path = preg_replace('![\\\/]+!', '/', $path); + if (strpos($path, $base) === 0) { + $path = ltrim(substr($path, strlen($base)), '/'); + } + } + + return $path; + } + + /** + * Get relative path between target and base path. If path isn't relative, return full path. + * + * @param string $path + * @param string $base + * @return string + */ + public static function getRelativePathDotDot($path, $base) + { + $base = preg_replace('![\\\/]+!', '/', $base); + $path = preg_replace('![\\\/]+!', '/', $path); + + if ($path === $base) { + return ''; + } + + $baseParts = explode('/', isset($base[0]) && '/' === $base[0] ? substr($base, 1) : $base); + $pathParts = explode('/', isset($path[0]) && '/' === $path[0] ? substr($path, 1) : $path); + + array_pop($baseParts); + $lastPart = array_pop($pathParts); + foreach ($baseParts as $i => $directory) { + if (isset($pathParts[$i]) && $pathParts[$i] === $directory) { + unset($baseParts[$i], $pathParts[$i]); + } else { + break; + } + } + $pathParts[] = $lastPart; + $path = str_repeat('../', count($baseParts)) . implode('/', $pathParts); + + return '' === $path + || '/' === $path[0] + || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) + ? "./$path" : $path; + } + + /** + * Shift first directory out of the path. + * + * @param string $path + * @return string + */ + public static function shift(&$path) + { + $parts = explode('/', trim($path, '/'), 2); + $result = array_shift($parts); + $path = array_shift($parts); + + return $result ?: null; + } + + /** + * Return recursive list of all files and directories under given path. + * + * @param string $path + * @param array $params + * @return array + * @throws \RuntimeException + */ + public static function all($path, array $params = []) + { + if ($path === false) { + throw new \RuntimeException("Path doesn't exist."); + } + + $compare = isset($params['compare']) ? 'get' . $params['compare'] : null; + $pattern = isset($params['pattern']) ? $params['pattern'] : null; + $filters = isset($params['filters']) ? $params['filters'] : null; + $recursive = isset($params['recursive']) ? $params['recursive'] : true; + $levels = isset($params['levels']) ? $params['levels'] : -1; + $key = isset($params['key']) ? 'get' . $params['key'] : null; + $value = isset($params['value']) ? 'get' . $params['value'] : ($recursive ? 'getSubPathname' : 'getFilename'); + $folders = isset($params['folders']) ? $params['folders'] : true; + $files = isset($params['files']) ? $params['files'] : true; + + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + if ($recursive) { + $flags = \RecursiveDirectoryIterator::SKIP_DOTS + \FilesystemIterator::UNIX_PATHS + + \FilesystemIterator::CURRENT_AS_SELF + \FilesystemIterator::FOLLOW_SYMLINKS; + if ($locator->isStream($path)) { + $directory = $locator->getRecursiveIterator($path, $flags); + } else { + $directory = new \RecursiveDirectoryIterator($path, $flags); + } + $iterator = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::SELF_FIRST); + $iterator->setMaxDepth(max($levels, -1)); + } else { + if ($locator->isStream($path)) { + $iterator = $locator->getIterator($path); + } else { + $iterator = new \FilesystemIterator($path); + } + } + + $results = []; + + /** @var \RecursiveDirectoryIterator $file */ + foreach ($iterator as $file) { + // Ignore hidden files. + if ($file->getFilename()[0] === '.') { + continue; + } + if (!$folders && $file->isDir()) { + continue; + } + if (!$files && $file->isFile()) { + continue; + } + if ($compare && $pattern && !preg_match($pattern, $file->{$compare}())) { + continue; + } + $fileKey = $key ? $file->{$key}() : null; + $filePath = $file->{$value}(); + if ($filters) { + if (isset($filters['key'])) { + $pre = !empty($filters['pre-key']) ? $filters['pre-key'] : ''; + $fileKey = $pre . preg_replace($filters['key'], '', $fileKey); + } + if (isset($filters['value'])) { + $filter = $filters['value']; + if (is_callable($filter)) { + $filePath = call_user_func($filter, $file); + } else { + $filePath = preg_replace($filter, '', $filePath); + } + } + } + + if ($fileKey !== null) { + $results[$fileKey] = $filePath; + } else { + $results[] = $filePath; + } + } + + return $results; + } + + /** + * Recursively copy directory in filesystem. + * + * @param string $source + * @param string $target + * @param string $ignore Ignore files matching pattern (regular expression). + * @throws \RuntimeException + */ + public static function copy($source, $target, $ignore = null) + { + $source = rtrim($source, '\\/'); + $target = rtrim($target, '\\/'); + + if (!is_dir($source)) { + throw new \RuntimeException('Cannot copy non-existing folder.'); + } + + // Make sure that path to the target exists before copying. + self::create($target); + + $success = true; + + // Go through all sub-directories and copy everything. + $files = self::all($source); + foreach ($files as $file) { + if ($ignore && preg_match($ignore, $file)) { + continue; + } + $src = $source .'/'. $file; + $dst = $target .'/'. $file; + + if (is_dir($src)) { + // Create current directory (if it doesn't exist). + if (!is_dir($dst)) { + $success &= @mkdir($dst, 0777, true); + } + } else { + // Or copy current file. + $success &= @copy($src, $dst); + } + } + + if (!$success) { + $error = error_get_last(); + throw new \RuntimeException($error['message']); + } + + // Make sure that the change will be detected when caching. + @touch(dirname($target)); + } + + /** + * Move directory in filesystem. + * + * @param string $source + * @param string $target + * @throws \RuntimeException + */ + public static function move($source, $target) + { + if (!file_exists($source) || !is_dir($source)) { + // Rename fails if source folder does not exist. + throw new \RuntimeException('Cannot move non-existing folder.'); + } + + // Don't do anything if the source is the same as the new target + if ($source === $target) { + return; + } + + if (file_exists($target)) { + // Rename fails if target folder exists. + throw new \RuntimeException('Cannot move files to existing folder/file.'); + } + + // Make sure that path to the target exists before moving. + self::create(dirname($target)); + + // Silence warnings (chmod failed etc). + @rename($source, $target); + + // Rename function can fail while still succeeding, so let's check if the folder exists. + if (!file_exists($target) || !is_dir($target)) { + // In some rare cases rename() creates file, not a folder. Get rid of it. + if (file_exists($target)) { + @unlink($target); + } + // Rename doesn't support moving folders across filesystems. Use copy instead. + self::copy($source, $target); + self::delete($source); + } + + // Make sure that the change will be detected when caching. + @touch(dirname($source)); + @touch(dirname($target)); + @touch($target); + } + + /** + * Recursively delete directory from filesystem. + * + * @param string $target + * @param bool $include_target + * @return bool + * @throws \RuntimeException + */ + public static function delete($target, $include_target = true) + { + if (!is_dir($target)) { + return false; + } + + $success = self::doDelete($target, $include_target); + + if (!$success) { + $error = error_get_last(); + throw new \RuntimeException($error['message']); + } + + // Make sure that the change will be detected when caching. + if ($include_target) { + @touch(dirname($target)); + } else { + @touch($target); + } + + return $success; + } + + /** + * @param string $folder + * @throws \RuntimeException + */ + public static function mkdir($folder) + { + self::create($folder); + } + + /** + * @param string $folder + * @throws \RuntimeException + */ + public static function create($folder) + { + if (is_dir($folder)) { + return; + } + + $success = @mkdir($folder, 0777, true); + + if (!$success) { + $error = error_get_last(); + throw new \RuntimeException($error['message']); + } + } + + /** + * Recursive copy of one directory to another + * + * @param $src + * @param $dest + * + * @return bool + * @throws \RuntimeException + */ + public static function rcopy($src, $dest) + { + + // If the src is not a directory do a simple file copy + if (!is_dir($src)) { + copy($src, $dest); + return true; + } + + // If the destination directory does not exist create it + if (!is_dir($dest)) { + static::mkdir($dest); + } + + // Open the source directory to read in files + $i = new \DirectoryIterator($src); + /** @var \DirectoryIterator $f */ + foreach ($i as $f) { + if ($f->isFile()) { + copy($f->getRealPath(), "{$dest}/" . $f->getFilename()); + } else { + if (!$f->isDot() && $f->isDir()) { + static::rcopy($f->getRealPath(), "{$dest}/{$f}"); + } + } + } + return true; + } + + /** + * @param string $folder + * @param bool $include_target + * @return bool + * @internal + */ + protected static function doDelete($folder, $include_target = true) + { + // Special case for symbolic links. + if (is_link($folder)) { + return @unlink($folder); + } + + // Go through all items in filesystem and recursively remove everything. + $files = array_diff(scandir($folder, SCANDIR_SORT_NONE), array('.', '..')); + foreach ($files as $file) { + $path = "{$folder}/{$file}"; + is_dir($path) ? self::doDelete($path) : @unlink($path); + } + + return $include_target ? @rmdir($folder) : true; + } +} diff --git a/system/src/Grav/Common/Filesystem/RecursiveFolderFilterIterator.php b/system/src/Grav/Common/Filesystem/RecursiveFolderFilterIterator.php new file mode 100644 index 0000000..3972074 --- /dev/null +++ b/system/src/Grav/Common/Filesystem/RecursiveFolderFilterIterator.php @@ -0,0 +1,45 @@ +get('system.pages.ignore_folders'); + } + } + + /** + * Check whether the current element of the iterator is acceptable + * + * @return bool true if the current element is acceptable, otherwise false. + */ + public function accept() + { + /** @var $current \SplFileInfo */ + $current = $this->current(); + + if ($current->isDir() && !in_array($current->getFilename(), $this::$folder_ignores, true)) { + return true; + } + return false; + } +} diff --git a/system/src/Grav/Common/GPM/AbstractCollection.php b/system/src/Grav/Common/GPM/AbstractCollection.php new file mode 100644 index 0000000..3430a6a --- /dev/null +++ b/system/src/Grav/Common/GPM/AbstractCollection.php @@ -0,0 +1,36 @@ +items as $name => $package) { + $items[$name] = $package->toArray(); + } + + return json_encode($items); + } + + public function toArray() + { + $items = []; + + foreach ($this->items as $name => $package) { + $items[$name] = $package->toArray(); + } + + return $items; + } +} diff --git a/system/src/Grav/Common/GPM/Common/AbstractPackageCollection.php b/system/src/Grav/Common/GPM/Common/AbstractPackageCollection.php new file mode 100644 index 0000000..78d93bc --- /dev/null +++ b/system/src/Grav/Common/GPM/Common/AbstractPackageCollection.php @@ -0,0 +1,38 @@ +items as $name => $package) { + $items[$name] = $package->toArray(); + } + + return json_encode($items); + } + + public function toArray() + { + $items = []; + + foreach ($this->items as $name => $package) { + $items[$name] = $package->toArray(); + } + + return $items; + } +} diff --git a/system/src/Grav/Common/GPM/Common/CachedCollection.php b/system/src/Grav/Common/GPM/Common/CachedCollection.php new file mode 100644 index 0000000..0244692 --- /dev/null +++ b/system/src/Grav/Common/GPM/Common/CachedCollection.php @@ -0,0 +1,28 @@ + $item) { + $this->append([$name => $item]); + } + } +} diff --git a/system/src/Grav/Common/GPM/Common/Package.php b/system/src/Grav/Common/GPM/Common/Package.php new file mode 100644 index 0000000..fe4618a --- /dev/null +++ b/system/src/Grav/Common/GPM/Common/Package.php @@ -0,0 +1,49 @@ +data = $package; + + if ($type) { + $this->data->set('package_type', $type); + } + } + + public function getData() { + return $this->data; + } + + public function __get($key) { + return $this->data->get($key); + } + + public function __isset($key) { + return isset($this->data->$key); + } + + public function __toString() { + return $this->toJson(); + } + + public function toJson() { + return $this->data->toJson(); + } + + public function toArray() { + return $this->data->toArray(); + } + +} diff --git a/system/src/Grav/Common/GPM/GPM.php b/system/src/Grav/Common/GPM/GPM.php new file mode 100644 index 0000000..a7cbee4 --- /dev/null +++ b/system/src/Grav/Common/GPM/GPM.php @@ -0,0 +1,1148 @@ + 'user/plugins/%name%', + 'themes' => 'user/themes/%name%', + 'skeletons' => 'user/' + ]; + + /** + * Creates a new GPM instance with Local and Remote packages available + * @param boolean $refresh Applies to Remote Packages only and forces a refetch of data + * @param callable $callback Either a function or callback in array notation + */ + public function __construct($refresh = false, $callback = null) + { + $this->installed = new Local\Packages(); + try { + $this->repository = new Remote\Packages($refresh, $callback); + $this->grav = new Remote\GravCore($refresh, $callback); + } catch (\Exception $e) { + } + } + + /** + * Return the locally installed packages + * + * @return Local\Packages + */ + public function getInstalled() + { + return $this->installed; + } + + /** + * Returns the Locally installable packages + * + * @param array $list_type_installed + * @return array The installed packages + */ + public function getInstallable($list_type_installed = ['plugins' => true, 'themes' => true]) + { + $items = ['total' => 0]; + foreach ($list_type_installed as $type => $type_installed) { + if ($type_installed === false) { + continue; + } + $methodInstallableType = 'getInstalled' . ucfirst($type); + $to_install = $this->$methodInstallableType(); + $items[$type] = $to_install; + $items['total'] += count($to_install); + } + return $items; + } + + /** + * Returns the amount of locally installed packages + * @return integer Amount of installed packages + */ + public function countInstalled() + { + $installed = $this->getInstalled(); + + return count($installed['plugins']) + count($installed['themes']); + } + + /** + * Return the instance of a specific Package + * + * @param string $slug The slug of the Package + * @return Local\Package The instance of the Package + */ + public function getInstalledPackage($slug) + { + if (isset($this->installed['plugins'][$slug])) { + return $this->installed['plugins'][$slug]; + } + + if (isset($this->installed['themes'][$slug])) { + return $this->installed['themes'][$slug]; + } + + return null; + } + + /** + * Return the instance of a specific Plugin + * @param string $slug The slug of the Plugin + * @return Local\Package The instance of the Plugin + */ + public function getInstalledPlugin($slug) + { + return $this->installed['plugins'][$slug]; + } + + /** + * Returns the Locally installed plugins + * @return Iterator The installed plugins + */ + public function getInstalledPlugins() + { + return $this->installed['plugins']; + } + + /** + * Checks if a Plugin is installed + * @param string $slug The slug of the Plugin + * @return boolean True if the Plugin has been installed. False otherwise + */ + public function isPluginInstalled($slug) + { + return isset($this->installed['plugins'][$slug]); + } + + public function isPluginInstalledAsSymlink($slug) + { + return $this->installed['plugins'][$slug]->symlink; + } + + /** + * Return the instance of a specific Theme + * @param string $slug The slug of the Theme + * @return Local\Package The instance of the Theme + */ + public function getInstalledTheme($slug) + { + return $this->installed['themes'][$slug]; + } + + /** + * Returns the Locally installed themes + * @return Iterator The installed themes + */ + public function getInstalledThemes() + { + return $this->installed['themes']; + } + + /** + * Checks if a Theme is installed + * @param string $slug The slug of the Theme + * @return boolean True if the Theme has been installed. False otherwise + */ + public function isThemeInstalled($slug) + { + return isset($this->installed['themes'][$slug]); + } + + /** + * Returns the amount of updates available + * @return integer Amount of available updates + */ + public function countUpdates() + { + $count = 0; + + $count += count($this->getUpdatablePlugins()); + $count += count($this->getUpdatableThemes()); + + return $count; + } + + /** + * Returns an array of Plugins and Themes that can be updated. + * Plugins and Themes are extended with the `available` property that relies to the remote version + * @param array $list_type_update specifies what type of package to update + * @return array Array of updatable Plugins and Themes. + * Format: ['total' => int, 'plugins' => array, 'themes' => array] + */ + public function getUpdatable($list_type_update = ['plugins' => true, 'themes' => true]) + { + + $items = ['total' => 0]; + foreach ($list_type_update as $type => $type_updatable) { + if ($type_updatable === false) { + continue; + } + $methodUpdatableType = 'getUpdatable' . ucfirst($type); + $to_update = $this->$methodUpdatableType(); + $items[$type] = $to_update; + $items['total'] += count($to_update); + } + return $items; + } + + /** + * Returns an array of Plugins that can be updated. + * The Plugins are extended with the `available` property that relies to the remote version + * @return array Array of updatable Plugins + */ + public function getUpdatablePlugins() + { + $items = []; + $repository = $this->repository['plugins']; + + // local cache to speed things up + if (isset($this->cache[__METHOD__])) { + return $this->cache[__METHOD__]; + } + + foreach ($this->installed['plugins'] as $slug => $plugin) { + if (!isset($repository[$slug]) || $plugin->symlink || !$plugin->version || $plugin->gpm === false) { + continue; + } + + $local_version = $plugin->version ? $plugin->version : 'Unknown'; + $remote_version = $repository[$slug]->version; + + if (version_compare($local_version, $remote_version) < 0) { + $repository[$slug]->available = $remote_version; + $repository[$slug]->version = $local_version; + $repository[$slug]->name = $repository[$slug]->name; + $repository[$slug]->type = $repository[$slug]->release_type; + $items[$slug] = $repository[$slug]; + } + } + + $this->cache[__METHOD__] = $items; + + return $items; + } + + /** + * Get the latest release of a package from the GPM + * + * @param $package_name + * + * @return string|null + */ + public function getLatestVersionOfPackage($package_name) + { + $repository = $this->repository['plugins']; + if (isset($repository[$package_name])) { + return $repository[$package_name]->available ?: $repository[$package_name]->version; + } + + //Not a plugin, it's a theme? + $repository = $this->repository['themes']; + if (isset($repository[$package_name])) { + return $repository[$package_name]->available ?: $repository[$package_name]->version; + } + + return null; + } + + /** + * Check if a Plugin or Theme is updatable + * @param string $slug The slug of the package + * @return boolean True if updatable. False otherwise or if not found + */ + public function isUpdatable($slug) + { + return $this->isPluginUpdatable($slug) || $this->isThemeUpdatable($slug); + } + + /** + * Checks if a Plugin is updatable + * @param string $plugin The slug of the Plugin + * @return boolean True if the Plugin is updatable. False otherwise + */ + public function isPluginUpdatable($plugin) + { + return array_key_exists($plugin, (array)$this->getUpdatablePlugins()); + } + + /** + * Returns an array of Themes that can be updated. + * The Themes are extended with the `available` property that relies to the remote version + * @return array Array of updatable Themes + */ + public function getUpdatableThemes() + { + $items = []; + $repository = $this->repository['themes']; + + // local cache to speed things up + if (isset($this->cache[__METHOD__])) { + return $this->cache[__METHOD__]; + } + + foreach ($this->installed['themes'] as $slug => $plugin) { + if (!isset($repository[$slug]) || $plugin->symlink || !$plugin->version || $plugin->gpm === false) { + continue; + } + + $local_version = $plugin->version ? $plugin->version : 'Unknown'; + $remote_version = $repository[$slug]->version; + + if (version_compare($local_version, $remote_version) < 0) { + $repository[$slug]->available = $remote_version; + $repository[$slug]->version = $local_version; + $repository[$slug]->type = $repository[$slug]->release_type; + $items[$slug] = $repository[$slug]; + } + } + + $this->cache[__METHOD__] = $items; + + return $items; + } + + /** + * Checks if a Theme is Updatable + * @param string $theme The slug of the Theme + * @return boolean True if the Theme is updatable. False otherwise + */ + public function isThemeUpdatable($theme) + { + return array_key_exists($theme, (array)$this->getUpdatableThemes()); + } + + /** + * Get the release type of a package (stable / testing) + * + * @param $package_name + * + * @return string|null + */ + public function getReleaseType($package_name) + { + $repository = $this->repository['plugins']; + if (isset($repository[$package_name])) { + return $repository[$package_name]->release_type; + } + + //Not a plugin, it's a theme? + $repository = $this->repository['themes']; + if (isset($repository[$package_name])) { + return $repository[$package_name]->release_type; + } + + return null; + } + + /** + * Returns true if the package latest release is stable + * + * @param $package_name + * + * @return boolean + */ + public function isStableRelease($package_name) + { + return $this->getReleaseType($package_name) === 'stable'; + } + + /** + * Returns true if the package latest release is testing + * + * @param $package_name + * + * @return boolean + */ + public function isTestingRelease($package_name) + { + $hasTesting = isset($this->getInstalledPackage($package_name)->testing); + $testing = $hasTesting ? $this->getInstalledPackage($package_name)->testing : false; + + return $this->getReleaseType($package_name) === 'testing' || $testing; + } + + /** + * Returns a Plugin from the repository + * @param string $slug The slug of the Plugin + * @return mixed Package if found, NULL if not + */ + public function getRepositoryPlugin($slug) + { + return @$this->repository['plugins'][$slug]; + } + + /** + * Returns the list of Plugins available in the repository + * @return Iterator The Plugins remotely available + */ + public function getRepositoryPlugins() + { + return $this->repository['plugins']; + } + + /** + * Returns a Theme from the repository + * @param string $slug The slug of the Theme + * @return mixed Package if found, NULL if not + */ + public function getRepositoryTheme($slug) + { + return @$this->repository['themes'][$slug]; + } + + /** + * Returns the list of Themes available in the repository + * @return Iterator The Themes remotely available + */ + public function getRepositoryThemes() + { + return $this->repository['themes']; + } + + /** + * Returns the list of Plugins and Themes available in the repository + * @return Remote\Packages Available Plugins and Themes + * Format: ['plugins' => array, 'themes' => array] + */ + public function getRepository() + { + return $this->repository; + } + + /** + * Searches for a Package in the repository + * @param string $search Can be either the slug or the name + * @param bool $ignore_exception True if should not fire an exception (for use in Twig) + * @return Remote\Package|bool Package if found, FALSE if not + */ + public function findPackage($search, $ignore_exception = false) + { + $search = strtolower($search); + + $found = $this->getRepositoryTheme($search); + if ($found) { + return $found; + } + + $found = $this->getRepositoryPlugin($search); + if ($found) { + return $found; + } + + $themes = $this->getRepositoryThemes(); + $plugins = $this->getRepositoryPlugins(); + + if (!$themes && !$plugins) { + if (!is_writable(ROOT_DIR . '/cache/gpm')) { + throw new \RuntimeException("The cache/gpm folder is not writable. Please check the folder permissions."); + } + + if ($ignore_exception) { + return false; + } + + throw new \RuntimeException("GPM not reachable. Please check your internet connection or check the Grav site is reachable"); + } + + if ($themes) { + foreach ($themes as $slug => $theme) { + if ($search == $slug || $search == $theme->name) { + return $theme; + } + } + } + + if ($plugins) { + foreach ($plugins as $slug => $plugin) { + if ($search == $slug || $search == $plugin->name) { + return $plugin; + } + } + } + + return false; + } + + /** + * Download the zip package via the URL + * + * @param $package_file + * @param $tmp + * @return null|string + */ + public static function downloadPackage($package_file, $tmp) + { + $package = parse_url($package_file); + $filename = basename($package['path']); + + if (Grav::instance()['config']->get('system.gpm.official_gpm_only') && $package['host'] !== 'getgrav.org') { + throw new \RuntimeException("Only official GPM URLs are allowed. You can modify this behavior in the System configuration."); + } + + $output = Response::get($package_file, []); + + if ($output) { + Folder::mkdir($tmp); + file_put_contents($tmp . DS . $filename, $output); + return $tmp . DS . $filename; + } + + return null; + } + + /** + * Copy the local zip package to tmp + * + * @param $package_file + * @param $tmp + * @return null|string + */ + public static function copyPackage($package_file, $tmp) + { + $package_file = realpath($package_file); + + if (file_exists($package_file)) { + $filename = basename($package_file); + Folder::mkdir($tmp); + copy(realpath($package_file), $tmp . DS . $filename); + return $tmp . DS . $filename; + } + + return null; + } + + /** + * Try to guess the package type from the source files + * + * @param $source + * @return bool|string + */ + public static function getPackageType($source) + { + $plugin_regex = '/^class\\s{1,}[a-zA-Z0-9]{1,}\\s{1,}extends.+Plugin/m'; + $theme_regex = '/^class\\s{1,}[a-zA-Z0-9]{1,}\\s{1,}extends.+Theme/m'; + + if ( + file_exists($source . 'system/defines.php') && + file_exists($source . 'system/config/system.yaml') + ) { + return 'grav'; + } else { + // must have a blueprint + if (!file_exists($source . 'blueprints.yaml')) { + return false; + } + + // either theme or plugin + $name = basename($source); + if (Utils::contains($name, 'theme')) { + return 'theme'; + } elseif (Utils::contains($name, 'plugin')) { + return 'plugin'; + } + foreach (glob($source . "*.php") as $filename) { + $contents = file_get_contents($filename); + if (preg_match($theme_regex, $contents)) { + return 'theme'; + } elseif (preg_match($plugin_regex, $contents)) { + return 'plugin'; + } + } + + // Assume it's a theme + return 'theme'; + } + } + + /** + * Try to guess the package name from the source files + * + * @param $source + * @return bool|string + */ + public static function getPackageName($source) + { + $ignore_yaml_files = ['blueprints', 'languages']; + + foreach (glob($source . "*.yaml") as $filename) { + $name = strtolower(basename($filename, '.yaml')); + if (in_array($name, $ignore_yaml_files)) { + continue; + } + return $name; + } + return false; + } + + /** + * Find/Parse the blueprint file + * + * @param $source + * @return array|bool + */ + public static function getBlueprints($source) + { + $blueprint_file = $source . 'blueprints.yaml'; + if (!file_exists($blueprint_file)) { + return false; + } + + $blueprint = (array)Yaml::parse(file_get_contents($blueprint_file)); + return $blueprint; + } + + /** + * Get the install path for a name and a particular type of package + * + * @param $type + * @param $name + * @return string + */ + public static function getInstallPath($type, $name) + { + $locator = Grav::instance()['locator']; + + if ($type == 'theme') { + $install_path = $locator->findResource('themes://', false) . DS . $name; + } else { + $install_path = $locator->findResource('plugins://', false) . DS . $name; + } + return $install_path; + } + + /** + * Searches for a list of Packages in the repository + * @param array $searches An array of either slugs or names + * @return array Array of found Packages + * Format: ['total' => int, 'not_found' => array, ] + */ + public function findPackages($searches = []) + { + $packages = ['total' => 0, 'not_found' => []]; + $inflector = new Inflector(); + + foreach ($searches as $search) { + $repository = ''; + // if this is an object, get the search data from the key + if (is_object($search)) { + $search = (array)$search; + $key = key($search); + $repository = $search[$key]; + $search = $key; + } + + $found = $this->findPackage($search); + if ($found) { + // set override repository if provided + if ($repository) { + $found->override_repository = $repository; + } + if (!isset($packages[$found->package_type])) { + $packages[$found->package_type] = []; + } + + $packages[$found->package_type][$found->slug] = $found; + $packages['total']++; + } else { + // make a best guess at the type based on the repo URL + if (Utils::contains($repository, '-theme')) { + $type = 'themes'; + } else { + $type = 'plugins'; + } + + $not_found = new \stdClass(); + $not_found->name = $inflector->camelize($search); + $not_found->slug = $search; + $not_found->package_type = $type; + $not_found->install_path = str_replace('%name%', $search, $this->install_paths[$type]); + $not_found->override_repository = $repository; + $packages['not_found'][$search] = $not_found; + } + } + + return $packages; + } + + /** + * Return the list of packages that have the passed one as dependency + * + * @param string $slug The slug name of the package + * + * @return array + */ + public function getPackagesThatDependOnPackage($slug) + { + $plugins = $this->getInstalledPlugins(); + $themes = $this->getInstalledThemes(); + $packages = array_merge($plugins->toArray(), $themes->toArray()); + + $dependent_packages = []; + + foreach ($packages as $package_name => $package) { + if (isset($package['dependencies'])) { + foreach ($package['dependencies'] as $dependency) { + if (is_array($dependency) && isset($dependency['name'])) { + $dependency = $dependency['name']; + } + + if ($dependency == $slug) { + $dependent_packages[] = $package_name; + } + } + } + } + + return $dependent_packages; + } + + + /** + * Get the required version of a dependency of a package + * + * @param $package_slug + * @param $dependency_slug + * + * @return mixed + */ + public function getVersionOfDependencyRequiredByPackage($package_slug, $dependency_slug) + { + $dependencies = $this->getInstalledPackage($package_slug)->dependencies; + foreach ($dependencies as $dependency) { + if (isset($dependency[$dependency_slug])) { + return $dependency[$dependency_slug]; + } + } + + return null; + } + + /** + * Check the package identified by $slug can be updated to the version passed as argument. + * Thrown an exception if it cannot be updated because another package installed requires it to be at an older version. + * + * @param string $slug + * @param string $version_with_operator + * @param array $ignore_packages_list + * + * @return bool + * @throws \Exception + */ + public function checkNoOtherPackageNeedsThisDependencyInALowerVersion( + $slug, + $version_with_operator, + $ignore_packages_list + ) { + + // check if any of the currently installed package need this in a lower version than the one we need. In case, abort and tell which package + $dependent_packages = $this->getPackagesThatDependOnPackage($slug); + $version = $this->calculateVersionNumberFromDependencyVersion($version_with_operator); + + if (count($dependent_packages)) { + foreach ($dependent_packages as $dependent_package) { + $other_dependency_version_with_operator = $this->getVersionOfDependencyRequiredByPackage($dependent_package, + $slug); + $other_dependency_version = $this->calculateVersionNumberFromDependencyVersion($other_dependency_version_with_operator); + + // check version is compatible with the one needed by the current package + if ($this->versionFormatIsNextSignificantRelease($other_dependency_version_with_operator)) { + $compatible = $this->checkNextSignificantReleasesAreCompatible($version, + $other_dependency_version); + if (!$compatible) { + if (!in_array($dependent_package, $ignore_packages_list)) { + throw new \Exception("Package $slug is required in an older version by package $dependent_package. This package needs a newer version, and because of this it cannot be installed. The $dependent_package package must be updated to use a newer release of $slug.", + 2); + } + } + } + } + } + + return true; + } + + /** + * Check the passed packages list can be updated + * + * @param $packages_names_list + * + * @throws \Exception + */ + public function checkPackagesCanBeInstalled($packages_names_list) + { + foreach ($packages_names_list as $package_name) { + $this->checkNoOtherPackageNeedsThisDependencyInALowerVersion($package_name, + $this->getLatestVersionOfPackage($package_name), $packages_names_list); + } + } + + /** + * Fetch the dependencies, check the installed packages and return an array with + * the list of packages with associated an information on what to do: install, update or ignore. + * + * `ignore` means the package is already installed and can be safely left as-is. + * `install` means the package is not installed and must be installed. + * `update` means the package is already installed and must be updated as a dependency needs a higher version. + * + * @param array $packages + * + * @return mixed + * @throws \Exception + */ + public function getDependencies($packages) + { + $dependencies = $this->calculateMergedDependenciesOfPackages($packages); + foreach ($dependencies as $dependency_slug => $dependencyVersionWithOperator) { + if (in_array($dependency_slug, $packages)) { + unset($dependencies[$dependency_slug]); + continue; + } + + // Check PHP version + if ($dependency_slug == 'php') { + $current_php_version = phpversion(); + if (version_compare($this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator), + $current_php_version) === 1 + ) { + //Needs a Grav update first + throw new \Exception("One of the packages require PHP " . $dependencies['php'] . ". Please update PHP to resolve this"); + } else { + unset($dependencies[$dependency_slug]); + continue; + } + } + + //First, check for Grav dependency. If a dependency requires Grav > the current version, abort and tell. + if ($dependency_slug == 'grav') { + if (version_compare($this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator), + GRAV_VERSION) === 1 + ) { + //Needs a Grav update first + throw new \Exception("One of the packages require Grav " . $dependencies['grav'] . ". Please update Grav to the latest release."); + } else { + unset($dependencies[$dependency_slug]); + continue; + } + } + + if ($this->isPluginInstalled($dependency_slug)) { + if ($this->isPluginInstalledAsSymlink($dependency_slug)) { + unset($dependencies[$dependency_slug]); + continue; + } + + $dependencyVersion = $this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator); + + // get currently installed version + $locator = Grav::instance()['locator']; + $blueprints_path = $locator->findResource('plugins://' . $dependency_slug . DS . 'blueprints.yaml'); + $package_yaml = Yaml::parse(file_get_contents($blueprints_path)); + $currentlyInstalledVersion = $package_yaml['version']; + + // if requirement is next significant release, check is compatible with currently installed version, might not be + if ($this->versionFormatIsNextSignificantRelease($dependencyVersionWithOperator)) { + if ($this->firstVersionIsLower($dependencyVersion, $currentlyInstalledVersion)) { + $compatible = $this->checkNextSignificantReleasesAreCompatible($dependencyVersion, + $currentlyInstalledVersion); + + if (!$compatible) { + throw new \Exception('Dependency ' . $dependency_slug . ' is required in an older version than the one installed. This package must be updated. Please get in touch with its developer.', + 2); + } + } + } + + //if I already have the latest release, remove the dependency + $latestRelease = $this->getLatestVersionOfPackage($dependency_slug); + + if ($this->firstVersionIsLower($latestRelease, $dependencyVersion)) { + //throw an exception if a required version cannot be found in the GPM yet + throw new \Exception('Dependency ' . $package_yaml['name'] . ' is required in version ' . $dependencyVersion . ' which is higher than the latest release, ' . $latestRelease . '. Try running `bin/gpm -f index` to force a refresh of the GPM cache', + 1); + } + + if ($this->firstVersionIsLower($currentlyInstalledVersion, $dependencyVersion)) { + $dependencies[$dependency_slug] = 'update'; + } else { + if ($currentlyInstalledVersion == $latestRelease) { + unset($dependencies[$dependency_slug]); + } else { + // an update is not strictly required mark as 'ignore' + $dependencies[$dependency_slug] = 'ignore'; + } + } + } else { + $dependencyVersion = $this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator); + + // if requirement is next significant release, check is compatible with latest available version, might not be + if ($this->versionFormatIsNextSignificantRelease($dependencyVersionWithOperator)) { + $latestVersionOfPackage = $this->getLatestVersionOfPackage($dependency_slug); + if ($this->firstVersionIsLower($dependencyVersion, $latestVersionOfPackage)) { + $compatible = $this->checkNextSignificantReleasesAreCompatible($dependencyVersion, + $latestVersionOfPackage); + + if (!$compatible) { + throw new \Exception('Dependency ' . $dependency_slug . ' is required in an older version than the latest release available, and it cannot be installed. This package must be updated. Please get in touch with its developer.', + 2); + } + } + } + + $dependencies[$dependency_slug] = 'install'; + } + } + + $dependencies_slugs = array_keys($dependencies); + $this->checkNoOtherPackageNeedsTheseDependenciesInALowerVersion(array_merge($packages, $dependencies_slugs)); + + return $dependencies; + } + + public function checkNoOtherPackageNeedsTheseDependenciesInALowerVersion($dependencies_slugs) + { + foreach ($dependencies_slugs as $dependency_slug) { + $this->checkNoOtherPackageNeedsThisDependencyInALowerVersion($dependency_slug, + $this->getLatestVersionOfPackage($dependency_slug), $dependencies_slugs); + } + } + + private function firstVersionIsLower($firstVersion, $secondVersion) + { + return version_compare($firstVersion, $secondVersion) == -1; + } + + /** + * Calculates and merges the dependencies of a package + * + * @param string $packageName The package information + * + * @param array $dependencies The dependencies array + * + * @return array + * @throws \Exception + */ + private function calculateMergedDependenciesOfPackage($packageName, $dependencies) + { + $packageData = $this->findPackage($packageName); + + //Check for dependencies + if (isset($packageData->dependencies)) { + foreach ($packageData->dependencies as $dependency) { + $current_package_name = $dependency['name']; + if (isset($dependency['version'])) { + $current_package_version_information = $dependency['version']; + } + + if (!isset($dependencies[$current_package_name])) { + // Dependency added for the first time + + if (!isset($current_package_version_information)) { + $dependencies[$current_package_name] = '*'; + } else { + $dependencies[$current_package_name] = $current_package_version_information; + } + + //Factor in the package dependencies too + $dependencies = $this->calculateMergedDependenciesOfPackage($current_package_name, $dependencies); + } else { + // Dependency already added by another package + //if this package requires a version higher than the currently stored one, store this requirement instead + if (isset($current_package_version_information) && $current_package_version_information !== '*') { + + $currently_stored_version_information = $dependencies[$current_package_name]; + $currently_stored_version_number = $this->calculateVersionNumberFromDependencyVersion($currently_stored_version_information); + + $currently_stored_version_is_in_next_significant_release_format = false; + if ($this->versionFormatIsNextSignificantRelease($currently_stored_version_information)) { + $currently_stored_version_is_in_next_significant_release_format = true; + } + + if (!$currently_stored_version_number) { + $currently_stored_version_number = '*'; + } + + $current_package_version_number = $this->calculateVersionNumberFromDependencyVersion($current_package_version_information); + if (!$current_package_version_number) { + throw new \Exception('Bad format for version of dependency ' . $current_package_name . ' for package ' . $packageName, + 1); + } + + $current_package_version_is_in_next_significant_release_format = false; + if ($this->versionFormatIsNextSignificantRelease($current_package_version_information)) { + $current_package_version_is_in_next_significant_release_format = true; + } + + //If I had stored '*', change right away with the more specific version required + if ($currently_stored_version_number === '*') { + $dependencies[$current_package_name] = $current_package_version_information; + } else { + if (!$currently_stored_version_is_in_next_significant_release_format && !$current_package_version_is_in_next_significant_release_format) { + //Comparing versions equals or higher, a simple version_compare is enough + if (version_compare($currently_stored_version_number, + $current_package_version_number) == -1 + ) { //Current package version is higher + $dependencies[$current_package_name] = $current_package_version_information; + } + } else { + $compatible = $this->checkNextSignificantReleasesAreCompatible($currently_stored_version_number, + $current_package_version_number); + if (!$compatible) { + throw new \Exception('Dependency ' . $current_package_name . ' is required in two incompatible versions', + 2); + } + } + } + } + } + } + } + + return $dependencies; + } + + /** + * Calculates and merges the dependencies of the passed packages + * + * @param array $packages + * + * @return mixed + * @throws \Exception + */ + public function calculateMergedDependenciesOfPackages($packages) + { + $dependencies = []; + + foreach ($packages as $package) { + $dependencies = $this->calculateMergedDependenciesOfPackage($package, $dependencies); + } + + return $dependencies; + } + + /** + * Returns the actual version from a dependency version string. + * Examples: + * $versionInformation == '~2.0' => returns '2.0' + * $versionInformation == '>=2.0.2' => returns '2.0.2' + * $versionInformation == '2.0.2' => returns '2.0.2' + * $versionInformation == '*' => returns null + * $versionInformation == '' => returns null + * + * @param string $version + * + * @return null|string + */ + public function calculateVersionNumberFromDependencyVersion($version) + { + if ($version == '*') { + return null; + } elseif ($version == '') { + return null; + } elseif ($this->versionFormatIsNextSignificantRelease($version)) { + return trim(substr($version, 1)); + } elseif ($this->versionFormatIsEqualOrHigher($version)) { + return trim(substr($version, 2)); + } else { + return $version; + } + } + + /** + * Check if the passed version information contains next significant release (tilde) operator + * + * Example: returns true for $version: '~2.0' + * + * @param $version + * + * @return bool + */ + public function versionFormatIsNextSignificantRelease($version) + { + return substr($version, 0, 1) == '~'; + } + + /** + * Check if the passed version information contains equal or higher operator + * + * Example: returns true for $version: '>=2.0' + * + * @param $version + * + * @return bool + */ + public function versionFormatIsEqualOrHigher($version) + { + return substr($version, 0, 2) == '>='; + } + + /** + * Check if two releases are compatible by next significant release + * + * ~1.2 is equivalent to >=1.2 <2.0.0 + * ~1.2.3 is equivalent to >=1.2.3 <1.3.0 + * + * In short, allows the last digit specified to go up + * + * @param string $version1 the version string (e.g. '2.0.0' or '1.0') + * @param string $version2 the version string (e.g. '2.0.0' or '1.0') + * + * @return bool + */ + public function checkNextSignificantReleasesAreCompatible($version1, $version2) + { + $version1array = explode('.', $version1); + $version2array = explode('.', $version2); + + if (count($version1array) > count($version2array)) { + list($version1array, $version2array) = [$version2array, $version1array]; + } + + $i = 0; + while ($i < count($version1array) - 1) { + if ($version1array[$i] != $version2array[$i]) { + return false; + } + $i++; + } + + return true; + } + +} diff --git a/system/src/Grav/Common/GPM/Installer.php b/system/src/Grav/Common/GPM/Installer.php new file mode 100644 index 0000000..6c385b8 --- /dev/null +++ b/system/src/Grav/Common/GPM/Installer.php @@ -0,0 +1,533 @@ + true, + 'ignore_symlinks' => true, + 'sophisticated' => false, + 'theme' => false, + 'install_path' => '', + 'ignores' => [], + 'exclude_checks' => [self::EXISTS, self::NOT_FOUND, self::IS_LINK] + ]; + + /** + * Installs a given package to a given destination. + * + * @param string $zip the local path to ZIP package + * @param string $destination The local path to the Grav Instance + * @param array $options Options to use for installing. ie, ['install_path' => 'user/themes/antimatter'] + * @param string $extracted The local path to the extacted ZIP package + * @return bool True if everything went fine, False otherwise. + */ + public static function install($zip, $destination, $options = [], $extracted = null) + { + $destination = rtrim($destination, DS); + $options = array_merge(self::$options, $options); + $install_path = rtrim($destination . DS . ltrim($options['install_path'], DS), DS); + + if (!self::isGravInstance($destination) || !self::isValidDestination($install_path, + $options['exclude_checks']) + ) { + return false; + } + + if (self::lastErrorCode() == self::IS_LINK && $options['ignore_symlinks'] || + self::lastErrorCode() == self::EXISTS && !$options['overwrite'] + ) { + return false; + } + + // Create a tmp location + $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true); + $tmp = $tmp_dir . '/Grav-' . uniqid(); + + if (!$extracted) { + $extracted = self::unZip($zip, $tmp); + if (!$extracted) { + Folder::delete($tmp); + return false; + } + } + + if (!file_exists($extracted)) { + self::$error = self::INVALID_SOURCE; + return false; + } + + + $is_install = true; + $installer = self::loadInstaller($extracted, $is_install); + + if (isset($options['is_update']) && $options['is_update'] === true) { + $method = 'preUpdate'; + } else { + $method = 'preInstall'; + } + + if ($installer && method_exists($installer, $method)) { + $method_result = $installer::$method(); + if ($method_result !== true) { + self::$error = 'An error occurred'; + if (is_string($method_result)) { + self::$error = $method_result; + } + + return false; + } + } + + if (!$options['sophisticated']) { + if ($options['theme']) { + self::copyInstall($extracted, $install_path); + } else { + self::moveInstall($extracted, $install_path); + } + } else { + self::sophisticatedInstall($extracted, $install_path, $options['ignores']); + } + + Folder::delete($tmp); + + if (isset($options['is_update']) && $options['is_update'] === true) { + $method = 'postUpdate'; + } else { + $method = 'postInstall'; + } + + self::$message = ''; + if ($installer && method_exists($installer, $method)) { + self::$message = $installer::$method(); + } + + self::$error = self::OK; + + return true; + + } + + /** + * Unzip a file to somewhere + * + * @param $zip_file + * @param $destination + * @return bool|string + */ + public static function unZip($zip_file, $destination) + { + $zip = new \ZipArchive(); + $archive = $zip->open($zip_file); + + if ($archive === true) { + Folder::mkdir($destination); + + $unzip = $zip->extractTo($destination); + + + if (!$unzip) { + self::$error = self::ZIP_EXTRACT_ERROR; + Folder::delete($destination); + $zip->close(); + return false; + } + + $package_folder_name = preg_replace('#\./$#', '', $zip->getNameIndex(0)); + $zip->close(); + $extracted_folder = $destination . '/' . $package_folder_name; + + return $extracted_folder; + } + + self::$error = self::ZIP_EXTRACT_ERROR; + self::$error_zip = $archive; + return false; + } + + /** + * Instantiates and returns the package installer class + * + * @param string $installer_file_folder The folder path that contains install.php + * @param bool $is_install True if install, false if removal + * + * @return null|string + */ + private static function loadInstaller($installer_file_folder, $is_install) + { + $installer = null; + + $installer_file_folder = rtrim($installer_file_folder, DS); + + $install_file = $installer_file_folder . DS . 'install.php'; + + if (file_exists($install_file)) { + require_once($install_file); + } else { + return null; + } + + if ($is_install) { + $slug = ''; + if (($pos = strpos($installer_file_folder, 'grav-plugin-')) !== false) { + $slug = substr($installer_file_folder, $pos + strlen('grav-plugin-')); + } elseif (($pos = strpos($installer_file_folder, 'grav-theme-')) !== false) { + $slug = substr($installer_file_folder, $pos + strlen('grav-theme-')); + } + } else { + $path_elements = explode('/', $installer_file_folder); + $slug = end($path_elements); + } + + if (!$slug) { + return null; + } + + $class_name = ucfirst($slug) . 'Install'; + + if (class_exists($class_name)) { + return $class_name; + } + + $class_name_alphanumeric = preg_replace('/[^a-zA-Z0-9]+/', '', $class_name); + + if (class_exists($class_name_alphanumeric)) { + return $class_name_alphanumeric; + } + + return $installer; + } + + /** + * @param $source_path + * @param $install_path + * + * @return bool + */ + public static function moveInstall($source_path, $install_path) + { + if (file_exists($install_path)) { + Folder::delete($install_path); + } + + Folder::move($source_path, $install_path); + + return true; + } + + /** + * @param $source_path + * @param $install_path + * + * @return bool + */ + public static function copyInstall($source_path, $install_path) + { + if (empty($source_path)) { + throw new \RuntimeException("Directory $source_path is missing"); + } else { + Folder::rcopy($source_path, $install_path); + } + + return true; + } + + /** + * @param $source_path + * @param $install_path + * + * @return bool + */ + public static function sophisticatedInstall($source_path, $install_path, $ignores = []) + { + foreach (new \DirectoryIterator($source_path) as $file) { + + if ($file->isLink() || $file->isDot() || in_array($file->getBasename(),$ignores)) { + continue; + } + + $path = $install_path . DS . $file->getBasename(); + + if ($file->isDir()) { + Folder::delete($path); + Folder::move($file->getPathname(), $path); + + if ($file->getBasename() == 'bin') { + foreach (glob($path . DS . '*') as $bin_file) { + @chmod($bin_file, 0755); + } + } + } else { + @unlink($path); + @copy($file->getPathname(), $path); + } + } + + return true; + } + + /** + * Uninstalls one or more given package + * + * @param string $path The slug of the package(s) + * @param array $options Options to use for uninstalling + * + * @return boolean True if everything went fine, False otherwise. + */ + public static function uninstall($path, $options = []) + { + $options = array_merge(self::$options, $options); + if (!self::isValidDestination($path, $options['exclude_checks']) + ) { + return false; + } + + $installer_file_folder = $path; + $is_install = false; + $installer = self::loadInstaller($installer_file_folder, $is_install); + + if ($installer && method_exists($installer, 'preUninstall')) { + $method_result = $installer::preUninstall(); + if ($method_result !== true) { + self::$error = 'An error occurred'; + if (is_string($method_result)) { + self::$error = $method_result; + } + + return false; + } + } + + $result = Folder::delete($path); + + self::$message = ''; + if ($result && $installer && method_exists($installer, 'postUninstall')) { + self::$message = $installer::postUninstall(); + } + + return $result; + } + + /** + * Runs a set of checks on the destination and sets the Error if any + * + * @param string $destination The directory to run validations at + * @param array $exclude An array of constants to exclude from the validation + * + * @return boolean True if validation passed. False otherwise + */ + public static function isValidDestination($destination, $exclude = []) + { + self::$error = 0; + self::$target = $destination; + + if (is_link($destination)) { + self::$error = self::IS_LINK; + } elseif (file_exists($destination)) { + self::$error = self::EXISTS; + } elseif (!file_exists($destination)) { + self::$error = self::NOT_FOUND; + } elseif (!is_dir($destination)) { + self::$error = self::NOT_DIRECTORY; + } + + if (count($exclude) && in_array(self::$error, $exclude)) { + return true; + } + + return !(self::$error); + } + + /** + * Validates if the given path is a Grav Instance + * + * @param string $target The local path to the Grav Instance + * + * @return boolean True if is a Grav Instance. False otherwise + */ + public static function isGravInstance($target) + { + self::$error = 0; + self::$target = $target; + + if ( + !file_exists($target . DS . 'index.php') || + !file_exists($target . DS . 'bin') || + !file_exists($target . DS . 'user') || + !file_exists($target . DS . 'system' . DS . 'config' . DS . 'system.yaml') + ) { + self::$error = self::NOT_GRAV_ROOT; + } + + return !self::$error; + } + + /** + * Returns the last message added by the installer + * @return string The message + */ + public static function getMessage() + { + return self::$message; + } + + /** + * Returns the last error occurred in a string message format + * @return string The message of the last error + */ + public static function lastErrorMsg() + { + if (is_string(self::$error)) { + return self::$error; + } + + switch (self::$error) { + case 0: + $msg = 'No Error'; + break; + + case self::EXISTS: + $msg = 'The target path "' . self::$target . '" already exists'; + break; + + case self::IS_LINK: + $msg = 'The target path "' . self::$target . '" is a symbolic link'; + break; + + case self::NOT_FOUND: + $msg = 'The target path "' . self::$target . '" does not appear to exist'; + break; + + case self::NOT_DIRECTORY: + $msg = 'The target path "' . self::$target . '" does not appear to be a folder'; + break; + + case self::NOT_GRAV_ROOT: + $msg = 'The target path "' . self::$target . '" does not appear to be a Grav instance'; + break; + + case self::ZIP_OPEN_ERROR: + $msg = 'Unable to open the package file'; + break; + + case self::ZIP_EXTRACT_ERROR: + $msg = 'Unable to extract the package. '; + if (self::$error_zip) { + switch(self::$error_zip) { + case \ZipArchive::ER_EXISTS: + $msg .= "File already exists."; + break; + + case \ZipArchive::ER_INCONS: + $msg .= "Zip archive inconsistent."; + break; + + case \ZipArchive::ER_MEMORY: + $msg .= "Malloc failure."; + break; + + case \ZipArchive::ER_NOENT: + $msg .= "No such file."; + break; + + case \ZipArchive::ER_NOZIP: + $msg .= "Not a zip archive."; + break; + + case \ZipArchive::ER_OPEN: + $msg .= "Can't open file."; + break; + + case \ZipArchive::ER_READ: + $msg .= "Read error."; + break; + + case \ZipArchive::ER_SEEK: + $msg .= "Seek error."; + break; + } + } + break; + + default: + $msg = 'Unknown Error'; + break; + } + + return $msg; + } + + /** + * Returns the last error code of the occurred error + * @return integer The code of the last error + */ + public static function lastErrorCode() + { + return self::$error; + } + + /** + * Allows to manually set an error + * + * @param int|string $error the Error code + */ + + public static function setError($error) + { + self::$error = $error; + } +} diff --git a/system/src/Grav/Common/GPM/Licenses.php b/system/src/Grav/Common/GPM/Licenses.php new file mode 100644 index 0000000..fed5b64 --- /dev/null +++ b/system/src/Grav/Common/GPM/Licenses.php @@ -0,0 +1,126 @@ +content(); + $slug = strtolower($slug); + + if ($license && !self::validate($license)) { + return false; + } + + if (!is_string($license)) { + if (isset($data['licenses'][$slug])) { + unset($data['licenses'][$slug]); + } else { + return false; + } + } else { + $data['licenses'][$slug] = $license; + } + + $licenses->save($data); + $licenses->free(); + + return true; + } + + /** + * Returns the license for a Premium package + * + * @param $slug + * + * @return string + */ + public static function get($slug = null) + { + $licenses = self::getLicenseFile(); + $data = $licenses->content(); + $licenses->free(); + $slug = strtolower($slug); + + if (!$slug) { + return isset($data['licenses']) ? $data['licenses'] : []; + } + + if (!isset($data['licenses']) || !isset($data['licenses'][$slug])) { + return ''; + } + + return $data['licenses'][$slug]; + } + + + /** + * Validates the License format + * + * @param $license + * + * @return bool + */ + public static function validate($license = null) + { + if (!is_string($license)) { + return false; + } + + return preg_match('#' . self::$regex. '#', $license); + } + + /** + * Get's the License File object + * + * @return \RocketTheme\Toolbox\File\FileInterface + */ + public static function getLicenseFile() + + { + if (!isset(self::$file)) { + $path = Grav::instance()['locator']->findResource('user://data') . '/licenses.yaml';; + if (!file_exists($path)) { + touch($path); + } + self::$file = CompiledYamlFile::instance($path); + } + + return self::$file; + } +} diff --git a/system/src/Grav/Common/GPM/Local/AbstractPackageCollection.php b/system/src/Grav/Common/GPM/Local/AbstractPackageCollection.php new file mode 100644 index 0000000..b976208 --- /dev/null +++ b/system/src/Grav/Common/GPM/Local/AbstractPackageCollection.php @@ -0,0 +1,22 @@ + $data) { + $data->set('slug', $name); + $this->items[$name] = new Package($data, $this->type); + } + } +} diff --git a/system/src/Grav/Common/GPM/Local/Package.php b/system/src/Grav/Common/GPM/Local/Package.php new file mode 100644 index 0000000..d0fae3a --- /dev/null +++ b/system/src/Grav/Common/GPM/Local/Package.php @@ -0,0 +1,39 @@ +blueprints()->toArray()); + parent::__construct($data, $package_type); + + $this->settings = $package->toArray(); + + $html_description = \Parsedown::instance()->line($this->description); + $this->data->set('slug', $package->slug); + $this->data->set('description_html', $html_description); + $this->data->set('description_plain', strip_tags($html_description)); + $this->data->set('symlink', is_link(USER_DIR . $package_type . DS . $this->slug)); + } + + /** + * @return mixed + */ + public function isEnabled() + { + return $this->settings['enabled']; + } +} diff --git a/system/src/Grav/Common/GPM/Local/Packages.php b/system/src/Grav/Common/GPM/Local/Packages.php new file mode 100644 index 0000000..3120d21 --- /dev/null +++ b/system/src/Grav/Common/GPM/Local/Packages.php @@ -0,0 +1,24 @@ + new Plugins(), + 'themes' => new Themes() + ]; + + parent::__construct($items); + } +} diff --git a/system/src/Grav/Common/GPM/Local/Plugins.php b/system/src/Grav/Common/GPM/Local/Plugins.php new file mode 100644 index 0000000..e97aa59 --- /dev/null +++ b/system/src/Grav/Common/GPM/Local/Plugins.php @@ -0,0 +1,29 @@ +all()); + } +} diff --git a/system/src/Grav/Common/GPM/Local/Themes.php b/system/src/Grav/Common/GPM/Local/Themes.php new file mode 100644 index 0000000..9b557af --- /dev/null +++ b/system/src/Grav/Common/GPM/Local/Themes.php @@ -0,0 +1,27 @@ +all()); + } +} diff --git a/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php b/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php new file mode 100644 index 0000000..ffdd90c --- /dev/null +++ b/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php @@ -0,0 +1,75 @@ +get('system.gpm.releases', 'stable'); + $cache_dir = Grav::instance()['locator']->findResource('cache://gpm', true, true); + $this->cache = new FilesystemCache($cache_dir); + + $this->repository = $repository . '?v=' . GRAV_VERSION . '&' . $channel . '=1'; + $this->raw = $this->cache->fetch(md5($this->repository)); + + $this->fetch($refresh, $callback); + foreach (json_decode($this->raw, true) as $slug => $data) { + // Temporarily fix for using multisites + if (isset($data['install_path'])) { + $path = preg_replace('~^user/~i', 'user://', $data['install_path']); + $data['install_path'] = Grav::instance()['locator']->findResource($path, false, true); + } + $this->items[$slug] = new Package($data, $this->type); + } + } + + public function fetch($refresh = false, $callback = null) + { + if (!$this->raw || $refresh) { + $response = Response::get($this->repository, [], $callback); + $this->raw = $response; + $this->cache->save(md5($this->repository), $this->raw, $this->lifetime); + } + + return $this->raw; + } +} diff --git a/system/src/Grav/Common/GPM/Remote/GravCore.php b/system/src/Grav/Common/GPM/Remote/GravCore.php new file mode 100644 index 0000000..ab5287f --- /dev/null +++ b/system/src/Grav/Common/GPM/Remote/GravCore.php @@ -0,0 +1,140 @@ +get('system.gpm.releases', 'stable'); + $cache_dir = Grav::instance()['locator']->findResource('cache://gpm', true, true); + $this->cache = new FilesystemCache($cache_dir); + $this->repository .= '?v=' . GRAV_VERSION . '&' . $channel . '=1'; + $this->raw = $this->cache->fetch(md5($this->repository)); + + $this->fetch($refresh, $callback); + + $this->data = json_decode($this->raw, true); + $this->version = isset($this->data['version']) ? $this->data['version'] : '-'; + $this->date = isset($this->data['date']) ? $this->data['date'] : '-'; + $this->min_php = isset($this->data['min_php']) ? $this->data['min_php'] : null; + + if (isset($this->data['assets'])) { + foreach ((array)$this->data['assets'] as $slug => $data) { + $this->items[$slug] = new Package($data); + } + } + } + + /** + * Returns the list of assets associated to the latest version of Grav + * + * @return array list of assets + */ + public function getAssets() + { + return $this->data['assets']; + } + + /** + * Returns the changelog list for each version of Grav + * + * @param string $diff the version number to start the diff from + * + * @return array changelog list for each version + */ + public function getChangelog($diff = null) + { + if (!$diff) { + return $this->data['changelog']; + } + + $diffLog = []; + foreach ((array)$this->data['changelog'] as $version => $changelog) { + preg_match("/[\w-\.]+/", $version, $cleanVersion); + + if (!$cleanVersion || version_compare($diff, $cleanVersion[0], '>=')) { + continue; + } + + $diffLog[$version] = $changelog; + } + + return $diffLog; + } + + /** + * Return the release date of the latest Grav + * + * @return string + */ + public function getDate() + { + return $this->date; + } + + /** + * Determine if this version of Grav is eligible to be updated + * + * @return mixed + */ + public function isUpdatable() + { + return version_compare(GRAV_VERSION, $this->getVersion(), '<'); + } + + /** + * Returns the latest version of Grav available remotely + * + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * Returns the minimum PHP version + * + * @return null|string + */ + public function getMinPHPVersion() + { + // If non min set, assume current PHP version + if (is_null($this->min_php)) { + $this->min_php = phpversion(); + } + return $this->min_php; + } + + /** + * Is this installation symlinked? + * + * @return bool + */ + public function isSymlink() + { + return is_link(GRAV_ROOT . DS . 'index.php'); + } +} diff --git a/system/src/Grav/Common/GPM/Remote/Package.php b/system/src/Grav/Common/GPM/Remote/Package.php new file mode 100644 index 0000000..830f63d --- /dev/null +++ b/system/src/Grav/Common/GPM/Remote/Package.php @@ -0,0 +1,19 @@ + new Plugins($refresh, $callback), + 'themes' => new Themes($refresh, $callback) + ]; + + parent::__construct($items); + } +} diff --git a/system/src/Grav/Common/GPM/Remote/Plugins.php b/system/src/Grav/Common/GPM/Remote/Plugins.php new file mode 100644 index 0000000..74e5ffb --- /dev/null +++ b/system/src/Grav/Common/GPM/Remote/Plugins.php @@ -0,0 +1,29 @@ +repository, $refresh, $callback); + } +} diff --git a/system/src/Grav/Common/GPM/Remote/Themes.php b/system/src/Grav/Common/GPM/Remote/Themes.php new file mode 100644 index 0000000..3f3f96c --- /dev/null +++ b/system/src/Grav/Common/GPM/Remote/Themes.php @@ -0,0 +1,29 @@ +repository, $refresh, $callback); + } +} diff --git a/system/src/Grav/Common/GPM/Response.php b/system/src/Grav/Common/GPM/Response.php new file mode 100644 index 0000000..d62acd2 --- /dev/null +++ b/system/src/Grav/Common/GPM/Response.php @@ -0,0 +1,432 @@ + [ + CURLOPT_REFERER => 'Grav GPM', + CURLOPT_USERAGENT => 'Grav GPM', + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_FAILONERROR => true, + CURLOPT_TIMEOUT => 15, + CURLOPT_HEADER => false, + //CURLOPT_SSL_VERIFYPEER => true, // this is set in the constructor since it's a setting + /** + * Example of callback parameters from within your own class + */ + //CURLOPT_NOPROGRESS => false, + //CURLOPT_PROGRESSFUNCTION => [$this, 'progress'] + ], + 'fopen' => [ + 'method' => 'GET', + 'user_agent' => 'Grav GPM', + 'max_redirects' => 5, + 'follow_location' => 1, + 'timeout' => 15, + /* // this is set in the constructor since it's a setting + 'ssl' => [ + 'verify_peer' => true, + 'verify_peer_name' => true, + ], + */ + /** + * Example of callback parameters from within your own class + */ + //'notification' => [$this, 'progress'] + ] + ]; + + /** + * Sets the preferred method to use for making HTTP calls. + * + * @param string $method Default is `auto` + * + * @return Response + */ + public static function setMethod($method = 'auto') + { + if (!in_array($method, ['auto', 'curl', 'fopen'])) { + $method = 'auto'; + } + + self::$method = $method; + + return new self(); + } + + /** + * Makes a request to the URL by using the preferred method + * + * @param string $uri URL to call + * @param array $options An array of parameters for both `curl` and `fopen` + * @param callable $callback Either a function or callback in array notation + * + * @return string The response of the request + */ + public static function get($uri = '', $options = [], $callback = null) + { + if (!self::isCurlAvailable() && !self::isFopenAvailable()) { + throw new \RuntimeException('Could not start an HTTP request. `allow_url_open` is disabled and `cURL` is not available'); + } + + // check if this function is available, if so use it to stop any timeouts + try { + if (!Utils::isFunctionDisabled('set_time_limit') && !ini_get('safe_mode') && function_exists('set_time_limit')) { + set_time_limit(0); + } + } catch (\Exception $e) { + } + + $config = Grav::instance()['config']; + $overrides = []; + + // Override CA Bundle + $caPathOrFile = \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(); + if (is_dir($caPathOrFile) || (is_link($caPathOrFile) && is_dir(readlink($caPathOrFile)))) { + $overrides['curl'][CURLOPT_CAPATH] = $caPathOrFile; + $overrides['fopen']['ssl']['capath'] = $caPathOrFile; + } else { + $overrides['curl'][CURLOPT_CAINFO] = $caPathOrFile; + $overrides['fopen']['ssl']['cafile'] = $caPathOrFile; + } + + // SSL Verify Peer and Proxy Setting + $settings = [ + 'method' => $config->get('system.gpm.method', self::$method), + 'verify_peer' => $config->get('system.gpm.verify_peer', true), + // `system.proxy_url` is for fallback + // introduced with 1.1.0-beta.1 probably safe to remove at some point + 'proxy_url' => $config->get('system.gpm.proxy_url', $config->get('system.proxy_url', false)), + ]; + + if (!$settings['verify_peer']) { + $overrides = array_replace_recursive([], $overrides, [ + 'curl' => [ + CURLOPT_SSL_VERIFYPEER => $settings['verify_peer'] + ], + 'fopen' => [ + 'ssl' => [ + 'verify_peer' => $settings['verify_peer'], + 'verify_peer_name' => $settings['verify_peer'], + ] + ] + ]); + } + + // Proxy Setting + if ($settings['proxy_url']) { + $proxy = parse_url($settings['proxy_url']); + $fopen_proxy = ($proxy['scheme'] ?: 'http') . '://' . $proxy['host'] . (isset($proxy['port']) ? ':' . $proxy['port'] : ''); + + $overrides = array_replace_recursive([], $overrides, [ + 'curl' => [ + CURLOPT_PROXY => $proxy['host'], + CURLOPT_PROXYTYPE => 'HTTP' + ], + 'fopen' => [ + 'proxy' => $fopen_proxy, + 'request_fulluri' => true + ] + ]); + + if (isset($proxy['port'])) { + $overrides['curl'][CURLOPT_PROXYPORT] = $proxy['port']; + } + + if (isset($proxy['user']) && isset($proxy['pass'])) { + $fopen_auth = $auth = base64_encode($proxy['user'] . ':' . $proxy['pass']); + $overrides['curl'][CURLOPT_PROXYUSERPWD] = $proxy['user'] . ':' . $proxy['pass']; + $overrides['fopen']['header'] = "Proxy-Authorization: Basic $fopen_auth"; + } + } + + $options = array_replace_recursive(self::$defaults, $options, $overrides); + $method = 'get' . ucfirst(strtolower($settings['method'])); + + self::$callback = $callback; + return static::$method($uri, $options, $callback); + } + + /** + * Checks if cURL is available + * + * @return boolean + */ + public static function isCurlAvailable() + { + return function_exists('curl_version'); + } + + /** + * Checks if the remote fopen request is enabled in PHP + * + * @return boolean + */ + public static function isFopenAvailable() + { + return preg_match('/1|yes|on|true/i', ini_get('allow_url_fopen')); + } + + /** + * Is this a remote file or not + * + * @param $file + * @return bool + */ + public static function isRemote($file) + { + return (bool) filter_var($file, FILTER_VALIDATE_URL); + } + + /** + * Progress normalized for cURL and Fopen + * Accepts a variable length of arguments passed in by stream method + */ + public static function progress() + { + static $filesize = null; + + $args = func_get_args(); + $isCurlResource = is_resource($args[0]) && get_resource_type($args[0]) == 'curl'; + + $notification_code = !$isCurlResource ? $args[0] : false; + $bytes_transferred = $isCurlResource ? $args[2] : $args[4]; + + if ($isCurlResource) { + $filesize = $args[1]; + } elseif ($notification_code == STREAM_NOTIFY_FILE_SIZE_IS) { + $filesize = $args[5]; + } + + if ($bytes_transferred > 0) { + if ($notification_code == STREAM_NOTIFY_PROGRESS | STREAM_NOTIFY_COMPLETED || $isCurlResource) { + + $progress = [ + 'code' => $notification_code, + 'filesize' => $filesize, + 'transferred' => $bytes_transferred, + 'percent' => $filesize <= 0 ? '-' : round(($bytes_transferred * 100) / $filesize, 1) + ]; + + if (self::$callback !== null) { + call_user_func_array(self::$callback, [$progress]); + } + } + } + } + + /** + * Automatically picks the preferred method + * + * @return string The response of the request + */ + private static function getAuto() + { + if (!ini_get('open_basedir') && self::isFopenAvailable()) { + return self::getFopen(func_get_args()); + } + + if (self::isCurlAvailable()) { + return self::getCurl(func_get_args()); + } + + return null; + } + + /** + * Starts a HTTP request via fopen + * + * @return string The response of the request + */ + private static function getFopen() + { + if (count($args = func_get_args()) == 1) { + $args = $args[0]; + } + + $uri = $args[0]; + $options = $args[1]; + $callback = $args[2]; + + if ($callback) { + $options['fopen']['notification'] = ['self', 'progress']; + } + + if (isset($options['fopen']['ssl'])) { + $ssl = $options['fopen']['ssl']; + unset($options['fopen']['ssl']); + + $stream = stream_context_create([ + 'http' => $options['fopen'], + 'ssl' => $ssl + ], $options['fopen']); + } else { + $stream = stream_context_create(['http' => $options['fopen']], $options['fopen']); + } + + + $content = @file_get_contents($uri, false, $stream); + + if ($content === false) { + $code = null; + if (isset($http_response_header)) { + $code = explode(' ', $http_response_header[0])[1]; + } + + switch ($code) { + case '404': + throw new \RuntimeException("Page not found"); + case '401': + throw new \RuntimeException("Invalid LICENSE"); + default: + throw new \RuntimeException("Error while trying to download (code: $code): $uri \n"); + } + } + + return $content; + } + + /** + * Starts a HTTP request via cURL + * + * @return string The response of the request + */ + private static function getCurl() + { + $args = func_get_args(); + $args = count($args) > 1 ? $args : array_shift($args); + + $uri = $args[0]; + $options = $args[1]; + $callback = $args[2]; + + $ch = curl_init($uri); + + $response = static::curlExecFollow($ch, $options, $callback); + $errno = curl_errno($ch); + + if ($errno) { + $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $error_message = curl_strerror($errno) . "\n" . curl_error($ch); + + switch ($code) { + case '404': + throw new \RuntimeException("Page not found"); + case '401': + throw new \RuntimeException("Invalid LICENSE"); + default: + throw new \RuntimeException("Error while trying to download (code: $code): $uri \nMessage: $error_message"); + } + } + + curl_close($ch); + + return $response; + } + + /** + * @param $ch + * @param $options + * @param $callback + * + * @return bool|mixed + */ + private static function curlExecFollow($ch, $options, $callback) + { + if ($callback) { + curl_setopt_array( + $ch, + [ + CURLOPT_NOPROGRESS => false, + CURLOPT_PROGRESSFUNCTION => ['self', 'progress'] + ] + ); + } + + // no open_basedir set, we can proceed normally + if (!ini_get('open_basedir')) { + curl_setopt_array($ch, $options['curl']); + return curl_exec($ch); + } + + $max_redirects = isset($options['curl'][CURLOPT_MAXREDIRS]) ? $options['curl'][CURLOPT_MAXREDIRS] : 5; + $options['curl'][CURLOPT_FOLLOWLOCATION] = false; + + // open_basedir set but no redirects to follow, we can disable followlocation and proceed normally + curl_setopt_array($ch, $options['curl']); + if ($max_redirects <= 0) { + return curl_exec($ch); + } + + $uri = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); + $rch = curl_copy_handle($ch); + + curl_setopt($rch, CURLOPT_HEADER, true); + curl_setopt($rch, CURLOPT_NOBODY, true); + curl_setopt($rch, CURLOPT_FORBID_REUSE, false); + curl_setopt($rch, CURLOPT_RETURNTRANSFER, true); + + do { + curl_setopt($rch, CURLOPT_URL, $uri); + $header = curl_exec($rch); + + if (curl_errno($rch)) { + $code = 0; + } else { + $code = curl_getinfo($rch, CURLINFO_HTTP_CODE); + if ($code == 301 || $code == 302 || $code == 303) { + preg_match('/Location:(.*?)\n/', $header, $matches); + $uri = trim(array_pop($matches)); + } else { + $code = 0; + } + } + } while ($code && --$max_redirects); + + curl_close($rch); + + if (!$max_redirects) { + if ($max_redirects === null) { + trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING); + } + + return false; + } + + curl_setopt($ch, CURLOPT_URL, $uri); + + return curl_exec($ch); + } +} diff --git a/system/src/Grav/Common/GPM/Upgrader.php b/system/src/Grav/Common/GPM/Upgrader.php new file mode 100644 index 0000000..1c995bc --- /dev/null +++ b/system/src/Grav/Common/GPM/Upgrader.php @@ -0,0 +1,141 @@ +remote = new Remote\GravCore($refresh, $callback); + } + + /** + * Returns the release date of the latest version of Grav + * + * @return string + */ + public function getReleaseDate() + { + return $this->remote->getDate(); + } + + /** + * Returns the version of the installed Grav + * + * @return string + */ + public function getLocalVersion() + { + return GRAV_VERSION; + } + + /** + * Returns the version of the remotely available Grav + * + * @return string + */ + public function getRemoteVersion() + { + return $this->remote->getVersion(); + } + + /** + * Returns an array of assets available to download remotely + * + * @return array + */ + public function getAssets() + { + return $this->remote->getAssets(); + } + + /** + * Returns the changelog list for each version of Grav + * + * @param string $diff the version number to start the diff from + * + * @return array return the changelog list for each version + */ + public function getChangelog($diff = null) + { + return $this->remote->getChangelog($diff); + } + + /** + * Make sure this meets minimum PHP requirements + * + * @return bool + */ + public function meetsRequirements() + { + $current_php_version = phpversion(); + if (version_compare($current_php_version, $this->minPHPVersion(), '<')) { + return false; + } + + return true; + } + + /** + * Get minimum PHP version from remote + * + * @return null + */ + public function minPHPVersion() + { + if (is_null($this->min_php)) { + $this->min_php = $this->remote->getMinPHPVersion(); + } + return $this->min_php; + } + + /** + * Checks if the currently installed Grav is upgradable to a newer version + * + * @return boolean True if it's upgradable, False otherwise. + */ + public function isUpgradable() + { + return version_compare($this->getLocalVersion(), $this->getRemoteVersion(), "<"); + } + + /** + * Checks if Grav is currently symbolically linked + * + * @return boolean True if Grav is symlinked, False otherwise. + */ + + public function isSymlink() + { + return $this->remote->isSymlink(); + } +} diff --git a/system/src/Grav/Common/Getters.php b/system/src/Grav/Common/Getters.php new file mode 100644 index 0000000..6f58fba --- /dev/null +++ b/system/src/Grav/Common/Getters.php @@ -0,0 +1,160 @@ +offsetSet($offset, $value); + } + + /** + * Magic getter method + * + * @param mixed $offset Medium name value + * + * @return mixed Medium value + */ + public function __get($offset) + { + return $this->offsetGet($offset); + } + + /** + * Magic method to determine if the attribute is set + * + * @param mixed $offset Medium name value + * + * @return boolean True if the value is set + */ + public function __isset($offset) + { + return $this->offsetExists($offset); + } + + /** + * Magic method to unset the attribute + * + * @param mixed $offset The name value to unset + */ + public function __unset($offset) + { + $this->offsetUnset($offset); + } + + /** + * @param mixed $offset + * + * @return bool + */ + public function offsetExists($offset) + { + if ($this->gettersVariable) { + $var = $this->gettersVariable; + + return isset($this->{$var}[$offset]); + } else { + return isset($this->{$offset}); + } + } + + /** + * @param mixed $offset + * + * @return mixed + */ + public function offsetGet($offset) + { + if ($this->gettersVariable) { + $var = $this->gettersVariable; + + return isset($this->{$var}[$offset]) ? $this->{$var}[$offset] : null; + } else { + return isset($this->{$offset}) ? $this->{$offset} : null; + } + } + + /** + * @param mixed $offset + * @param mixed $value + */ + public function offsetSet($offset, $value) + { + if ($this->gettersVariable) { + $var = $this->gettersVariable; + $this->{$var}[$offset] = $value; + } else { + $this->{$offset} = $value; + } + } + + /** + * @param mixed $offset + */ + public function offsetUnset($offset) + { + if ($this->gettersVariable) { + $var = $this->gettersVariable; + unset($this->{$var}[$offset]); + } else { + unset($this->{$offset}); + } + } + + /** + * @return int + */ + public function count() + { + if ($this->gettersVariable) { + $var = $this->gettersVariable; + count($this->{$var}); + } else { + count($this->toArray()); + } + } + + /** + * Returns an associative array of object properties. + * + * @return array + */ + public function toArray() + { + if ($this->gettersVariable) { + $var = $this->gettersVariable; + + return $this->{$var}; + } else { + $properties = (array)$this; + $list = []; + foreach ($properties as $property => $value) { + if ($property[0] != "\0") { + $list[$property] = $value; + } + } + + return $list; + } + } +} diff --git a/system/src/Grav/Common/Grav.php b/system/src/Grav/Common/Grav.php new file mode 100644 index 0000000..e6a49a1 --- /dev/null +++ b/system/src/Grav/Common/Grav.php @@ -0,0 +1,505 @@ + 'Grav\Common\Uri', + 'events' => 'RocketTheme\Toolbox\Event\EventDispatcher', + 'cache' => 'Grav\Common\Cache', + 'Grav\Common\Service\SessionServiceProvider', + 'plugins' => 'Grav\Common\Plugins', + 'themes' => 'Grav\Common\Themes', + 'twig' => 'Grav\Common\Twig\Twig', + 'taxonomy' => 'Grav\Common\Taxonomy', + 'language' => 'Grav\Common\Language\Language', + 'pages' => 'Grav\Common\Page\Pages', + 'Grav\Common\Service\TaskServiceProvider', + 'Grav\Common\Service\AssetsServiceProvider', + 'Grav\Common\Service\PageServiceProvider', + 'Grav\Common\Service\OutputServiceProvider', + 'browser' => 'Grav\Common\Browser', + 'exif' => 'Grav\Common\Helpers\Exif', + 'Grav\Common\Service\StreamsServiceProvider', + 'Grav\Common\Service\ConfigServiceProvider', + 'inflector' => 'Grav\Common\Inflector', + 'siteSetupProcessor' => 'Grav\Common\Processors\SiteSetupProcessor', + 'configurationProcessor' => 'Grav\Common\Processors\ConfigurationProcessor', + 'errorsProcessor' => 'Grav\Common\Processors\ErrorsProcessor', + 'debuggerInitProcessor' => 'Grav\Common\Processors\DebuggerInitProcessor', + 'initializeProcessor' => 'Grav\Common\Processors\InitializeProcessor', + 'pluginsProcessor' => 'Grav\Common\Processors\PluginsProcessor', + 'themesProcessor' => 'Grav\Common\Processors\ThemesProcessor', + 'tasksProcessor' => 'Grav\Common\Processors\TasksProcessor', + 'assetsProcessor' => 'Grav\Common\Processors\AssetsProcessor', + 'twigProcessor' => 'Grav\Common\Processors\TwigProcessor', + 'pagesProcessor' => 'Grav\Common\Processors\PagesProcessor', + 'debuggerAssetsProcessor' => 'Grav\Common\Processors\DebuggerAssetsProcessor', + 'renderProcessor' => 'Grav\Common\Processors\RenderProcessor', + ]; + + /** + * @var array All processors that are processed in $this->process() + */ + protected $processors = [ + 'siteSetupProcessor', + 'configurationProcessor', + 'errorsProcessor', + 'debuggerInitProcessor', + 'initializeProcessor', + 'pluginsProcessor', + 'themesProcessor', + 'tasksProcessor', + 'assetsProcessor', + 'twigProcessor', + 'pagesProcessor', + 'debuggerAssetsProcessor', + 'renderProcessor', + ]; + + /** + * Reset the Grav instance. + */ + public static function resetInstance() + { + if (self::$instance) { + self::$instance = null; + } + } + + /** + * Return the Grav instance. Create it if it's not already instanced + * + * @param array $values + * + * @return Grav + */ + public static function instance(array $values = []) + { + if (!self::$instance) { + self::$instance = static::load($values); + } elseif ($values) { + $instance = self::$instance; + foreach ($values as $key => $value) { + $instance->offsetSet($key, $value); + } + } + + return self::$instance; + } + + /** + * Process a request + */ + public function process() + { + // process all processors (e.g. config, initialize, assets, ..., render) + foreach ($this->processors as $processor) { + $processor = $this[$processor]; + $this->measureTime($processor->id, $processor->title, function () use ($processor) { + $processor->process(); + }); + } + + /** @var Debugger $debugger */ + $debugger = $this['debugger']; + $debugger->render(); + + register_shutdown_function([$this, 'shutdown']); + } + + /** + * Set the system locale based on the language and configuration + */ + public function setLocale() + { + // Initialize Locale if set and configured. + if ($this['language']->enabled() && $this['config']->get('system.languages.override_locale')) { + $language = $this['language']->getLanguage(); + setlocale(LC_ALL, strlen($language) < 3 ? ($language . '_' . strtoupper($language)) : $language); + } elseif ($this['config']->get('system.default_locale')) { + setlocale(LC_ALL, $this['config']->get('system.default_locale')); + } + } + + /** + * Redirect browser to another location. + * + * @param string $route Internal route. + * @param int $code Redirection code (30x) + */ + public function redirect($route, $code = null) + { + /** @var Uri $uri */ + $uri = $this['uri']; + + //Check for code in route + $regex = '/.*(\[(30[1-7])\])$/'; + preg_match($regex, $route, $matches); + if ($matches) { + $route = str_replace($matches[1], '', $matches[0]); + $code = $matches[2]; + } + + if ($code === null) { + $code = $this['config']->get('system.pages.redirect_default_code', 302); + } + + if (isset($this['session'])) { + $this['session']->close(); + } + + if ($uri->isExternal($route)) { + $url = $route; + } else { + $url = rtrim($uri->rootUrl(), '/') . '/'; + + if ($this['config']->get('system.pages.redirect_trailing_slash', true)) { + $url .= trim($route, '/'); // Remove trailing slash + } else { + $url .= ltrim($route, '/'); // Support trailing slash default routes + } + } + + header("Location: {$url}", true, $code); + exit(); + } + + /** + * Redirect browser to another location taking language into account (preferred) + * + * @param string $route Internal route. + * @param int $code Redirection code (30x) + */ + public function redirectLangSafe($route, $code = null) + { + /** @var Language $language */ + $language = $this['language']; + + if (!$this['uri']->isExternal($route) && $language->enabled() && $language->isIncludeDefaultLanguage()) { + $this->redirect($language->getLanguage() . $route, $code); + } else { + $this->redirect($route, $code); + } + } + + /** + * Set response header. + */ + public function header() + { + /** @var Page $page */ + $page = $this['page']; + + $format = $page->templateFormat(); + + header('Content-type: ' . Utils::getMimeByExtension($format, 'text/html')); + + $cache_control = $page->cacheControl(); + + // Calculate Expires Headers if set to > 0 + $expires = $page->expires(); + + if ($expires > 0) { + $expires_date = gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT'; + if (!$cache_control) { + header('Cache-Control: max-age=' . $expires); + } + header('Expires: ' . $expires_date); + } + + // Set cache-control header + if ($cache_control) { + header('Cache-Control: ' . strtolower($cache_control)); + } + + // Set the last modified time + if ($page->lastModified()) { + $last_modified_date = gmdate('D, d M Y H:i:s', $page->modified()) . ' GMT'; + header('Last-Modified: ' . $last_modified_date); + } + + // Calculate a Hash based on the raw file + if ($page->eTag()) { + header('ETag: "' . md5($page->raw() . $page->modified()).'"'); + } + + // Set HTTP response code + if (isset($this['page']->header()->http_response_code)) { + http_response_code($this['page']->header()->http_response_code); + } + + // Vary: Accept-Encoding + if ($this['config']->get('system.pages.vary_accept_encoding', false)) { + header('Vary: Accept-Encoding'); + } + } + + /** + * Fires an event with optional parameters. + * + * @param string $eventName + * @param Event $event + * + * @return Event + */ + public function fireEvent($eventName, Event $event = null) + { + /** @var EventDispatcher $events */ + $events = $this['events']; + + return $events->dispatch($eventName, $event); + } + + /** + * Set the final content length for the page and flush the buffer + * + */ + public function shutdown() + { + // Prevent user abort allowing onShutdown event to run without interruptions. + if (function_exists('ignore_user_abort')) { + @ignore_user_abort(true); + } + + // Close the session allowing new requests to be handled. + if (isset($this['session'])) { + $this['session']->close(); + } + + if ($this['config']->get('system.debugger.shutdown.close_connection', true)) { + // Flush the response and close the connection to allow time consuming tasks to be performed without leaving + // the connection to the client open. This will make page loads to feel much faster. + + // FastCGI allows us to flush all response data to the client and finish the request. + $success = function_exists('fastcgi_finish_request') ? @fastcgi_finish_request() : false; + + if (!$success) { + // Unfortunately without FastCGI there is no way to force close the connection. + // We need to ask browser to close the connection for us. + if ($this['config']->get('system.cache.gzip')) { + // Flush gzhandler buffer if gzip setting was enabled. + ob_end_flush(); + + } else { + // Without gzip we have no other choice than to prevent server from compressing the output. + // This action turns off mod_deflate which would prevent us from closing the connection. + if ($this['config']->get('system.cache.allow_webserver_gzip')) { + header('Content-Encoding: identity'); + } else { + header('Content-Encoding: none'); + } + + } + + + // Get length and close the connection. + header('Content-Length: ' . ob_get_length()); + header("Connection: close"); + + ob_end_flush(); + @ob_flush(); + flush(); + } + } + + // Run any time consuming tasks. + $this->fireEvent('onShutdown'); + } + + /** + * Magic Catch All Function + * Used to call closures like measureTime on the instance. + * Source: http://stackoverflow.com/questions/419804/closures-as-class-members + */ + public function __call($method, $args) + { + $closure = $this->$method; + call_user_func_array($closure, $args); + } + + /** + * Initialize and return a Grav instance + * + * @param array $values + * + * @return static + */ + protected static function load(array $values) + { + $container = new static($values); + + $container['grav'] = $container; + + $container['debugger'] = new Debugger(); + $debugger = $container['debugger']; + + // closure that measures time by wrapping a function into startTimer and stopTimer + // The debugger can be passed to the closure. Should be more performant + // then to get it from the container all time. + $container->measureTime = function ($timerId, $timerTitle, $callback) use ($debugger) { + $debugger->startTimer($timerId, $timerTitle); + $callback(); + $debugger->stopTimer($timerId); + }; + + $container->measureTime('_services', 'Services', function () use ($container) { + $container->registerServices($container); + }); + + return $container; + } + + /** + * Register all services + * Services are defined in the diMap. They can either only the class + * of a Service Provider or a pair of serviceKey => serviceClass that + * gets directly mapped into the container. + * + * @return void + */ + protected function registerServices() + { + foreach (self::$diMap as $serviceKey => $serviceClass) { + if (is_int($serviceKey)) { + $this->registerServiceProvider($serviceClass); + } else { + $this->registerService($serviceKey, $serviceClass); + } + } + } + + /** + * Register a service provider with the container. + * + * @param string $serviceClass + * + * @return void + */ + protected function registerServiceProvider($serviceClass) + { + $this->register(new $serviceClass); + } + + /** + * Register a service with the container. + * + * @param string $serviceKey + * @param string $serviceClass + * + * @return void + */ + protected function registerService($serviceKey, $serviceClass) + { + $this[$serviceKey] = function ($c) use ($serviceClass) { + return new $serviceClass($c); + }; + } + + /** + * This attempts to find media, other files, and download them + * + * @param $path + */ + public function fallbackUrl($path) + { + $this->fireEvent('onPageFallBackUrl'); + + /** @var Uri $uri */ + $uri = $this['uri']; + + /** @var Config $config */ + $config = $this['config']; + + $uri_extension = $uri->extension(); + $fallback_types = $config->get('system.media.allowed_fallback_types', null); + $supported_types = $config->get('media.types'); + + // Check whitelist first, then ensure extension is a valid media type + if (!empty($fallback_types) && !\in_array($uri_extension, $fallback_types, true)) { + return false; + } + if (!array_key_exists($uri_extension, $supported_types)) { + return false; + } + + $path_parts = pathinfo($path); + + /** @var Page $page */ + $page = $this['pages']->dispatch($path_parts['dirname'], true); + + if ($page) { + $media = $page->media()->all(); + $parsed_url = parse_url(rawurldecode($uri->basename())); + $media_file = $parsed_url['path']; + + // if this is a media object, try actions first + if (isset($media[$media_file])) { + /** @var Medium $medium */ + $medium = $media[$media_file]; + foreach ($uri->query(null, true) as $action => $params) { + if (in_array($action, ImageMedium::$magic_actions)) { + call_user_func_array([&$medium, $action], explode(',', $params)); + } + } + Utils::download($medium->path(), false); + } + + // unsupported media type, try to download it... + if ($uri_extension) { + $extension = $uri_extension; + } else { + if (isset($path_parts['extension'])) { + $extension = $path_parts['extension']; + } else { + $extension = null; + } + } + + if ($extension) { + $download = true; + if (in_array(ltrim($extension, '.'), $config->get('system.media.unsupported_inline_types', []))) { + $download = false; + } + Utils::download($page->path() . DIRECTORY_SEPARATOR . $uri->basename(), $download); + } + + // Nothing found + return false; + } + + return $page; + } +} diff --git a/system/src/Grav/Common/GravTrait.php b/system/src/Grav/Common/GravTrait.php new file mode 100644 index 0000000..7ff04e6 --- /dev/null +++ b/system/src/Grav/Common/GravTrait.php @@ -0,0 +1,32 @@ +getCaller(); + self::$grav['debugger']->addMessage("Deprecated GravTrait used in {$caller['file']}", 'deprecated'); + + return self::$grav; + } +} diff --git a/system/src/Grav/Common/Helpers/Base32.php b/system/src/Grav/Common/Helpers/Base32.php new file mode 100644 index 0000000..f212e58 --- /dev/null +++ b/system/src/Grav/Common/Helpers/Base32.php @@ -0,0 +1,103 @@ +', '?' + 0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G' + 0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O' + 0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W' + 0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF, // 'X', 'Y', 'Z', '[', '\', ']', '^', '_' + 0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g' + 0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o' + 0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' + 0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF // 'x', 'y', 'z', '{', '|', '}', '~', 'DEL' + ); + + /** + * Encode in Base32 + * + * @param $bytes + * @return string + */ + public static function encode( $bytes ) { + $i = 0; $index = 0; $digit = 0; + $base32 = ''; + $bytes_len = strlen($bytes); + while( $i < $bytes_len ) { + $currByte = ord($bytes{$i}); + /* Is the current digit going to span a byte boundary? */ + if( $index > 3 ) { + if( ($i + 1) < $bytes_len ) { + $nextByte = ord($bytes{$i+1}); + } else { + $nextByte = 0; + } + $digit = $currByte & (0xFF >> $index); + $index = ($index + 5) % 8; + $digit <<= $index; + $digit |= $nextByte >> (8 - $index); + $i++; + } else { + $digit = ($currByte >> (8 - ($index + 5))) & 0x1F; + $index = ($index + 5) % 8; + if( $index === 0 ) $i++; + } + $base32 .= self::$base32Chars{$digit}; + } + return $base32; + } + + /** + * Decode in Base32 + * + * @param $base32 + * @return string + */ + public static function decode( $base32 ) { + $bytes = array(); + $base32_len = strlen($base32); + for( $i=$base32_len*5/8-1; $i>=0; --$i ) { + $bytes[] = 0; + } + for( $i = 0, $index = 0, $offset = 0; $i < $base32_len; $i++ ) { + $lookup = ord($base32{$i}) - ord('0'); + /* Skip chars outside the lookup table */ + if( $lookup < 0 || $lookup >= count(self::$base32Lookup) ) { + continue; + } + $digit = self::$base32Lookup[$lookup]; + /* If this digit is not in the table, ignore it */ + if( $digit == 0xFF ) continue; + if( $index <= 3 ) { + $index = ($index + 5) % 8; + if( $index == 0) { + $bytes[$offset] |= $digit; + $offset++; + if( $offset >= count($bytes) ) break; + } else { + $bytes[$offset] |= $digit << (8 - $index); + } + } else { + $index = ($index + 5) % 8; + $bytes[$offset] |= ($digit >> $index); + $offset++; + if ($offset >= count($bytes) ) break; + $bytes[$offset] |= $digit << (8 - $index); + } + } + $bites = ''; + foreach( $bytes as $byte ) $bites .= chr($byte); + return $bites; + } +} diff --git a/system/src/Grav/Common/Helpers/Excerpts.php b/system/src/Grav/Common/Helpers/Excerpts.php new file mode 100644 index 0000000..3561bc3 --- /dev/null +++ b/system/src/Grav/Common/Helpers/Excerpts.php @@ -0,0 +1,363 @@ +` + * @param Page $page The current page object + * @return string Returns final HTML string + */ + public static function processImageHtml($html, Page $page) + { + $excerpt = static::getExcerptFromHtml($html, 'img'); + + $original_src = $excerpt['element']['attributes']['src']; + $excerpt['element']['attributes']['href'] = $original_src; + + $excerpt = static::processLinkExcerpt($excerpt, $page, 'image'); + + $excerpt['element']['attributes']['src'] = $excerpt['element']['attributes']['href']; + unset ($excerpt['element']['attributes']['href']); + + $excerpt = static::processImageExcerpt($excerpt, $page); + + $excerpt['element']['attributes']['data-src'] = $original_src; + + $html = static::getHtmlFromExcerpt($excerpt); + + return $html; + } + + /** + * Get an Excerpt array from a chunk of HTML + * + * @param string $html Chunk of HTML + * @param string $tag A tag, for example `img` + * @return array|null returns nested array excerpt + */ + public static function getExcerptFromHtml($html, $tag) + { + $doc = new \DOMDocument(); + $doc->loadHTML($html); + $images = $doc->getElementsByTagName($tag); + $excerpt = null; + + foreach ($images as $image) { + $attributes = []; + foreach ($image->attributes as $name => $value) { + $attributes[$name] = $value->value; + } + $excerpt = [ + 'element' => [ + 'name' => $image->tagName, + 'attributes' => $attributes + ] + ]; + } + + return $excerpt; + } + + /** + * Rebuild HTML tag from an excerpt array + * + * @param $excerpt + * @return string + */ + public static function getHtmlFromExcerpt($excerpt) + { + $element = $excerpt['element']; + $html = '<'.$element['name']; + + if (isset($element['attributes'])) { + foreach ($element['attributes'] as $name => $value) { + if ($value === null) { + continue; + } + $html .= ' '.$name.'="'.$value.'"'; + } + } + + if (isset($element['text'])) { + $html .= '>'; + $html .= $element['text']; + $html .= ''; + } else { + $html .= ' />'; + } + + return $html; + } + + /** + * Process a Link excerpt + * + * @param $excerpt + * @param Page $page + * @param string $type + * @return mixed + */ + public static function processLinkExcerpt($excerpt, Page $page, $type = 'link') + { + $url = htmlspecialchars_decode(urldecode($excerpt['element']['attributes']['href'])); + + $url_parts = static::parseUrl($url); + + // If there is a query, then parse it and build action calls. + if (isset($url_parts['query'])) { + $actions = array_reduce(explode('&', $url_parts['query']), function ($carry, $item) { + $parts = explode('=', $item, 2); + $value = isset($parts[1]) ? rawurldecode($parts[1]) : true; + $carry[$parts[0]] = $value; + + return $carry; + }, []); + + // Valid attributes supported. + $valid_attributes = ['rel', 'target', 'id', 'class', 'classes']; + + // Unless told to not process, go through actions. + if (array_key_exists('noprocess', $actions)) { + unset($actions['noprocess']); + } else { + // Loop through actions for the image and call them. + foreach ($actions as $attrib => $value) { + $key = $attrib; + + if (in_array($attrib, $valid_attributes, true)) { + // support both class and classes. + if ($attrib === 'classes') { + $attrib = 'class'; + } + $excerpt['element']['attributes'][$attrib] = str_replace(',', ' ', $value); + unset($actions[$key]); + } + } + } + + $url_parts['query'] = http_build_query($actions, null, '&', PHP_QUERY_RFC3986); + } + + // If no query elements left, unset query. + if (empty($url_parts['query'])) { + unset ($url_parts['query']); + } + + // Set path to / if not set. + if (empty($url_parts['path'])) { + $url_parts['path'] = ''; + } + + // If scheme isn't http(s).. + if (!empty($url_parts['scheme']) && !in_array($url_parts['scheme'], ['http', 'https'])) { + // Handle custom streams. + if ($type !== 'image' && !empty($url_parts['stream']) && !empty($url_parts['path'])) { + $url_parts['path'] = Grav::instance()['base_url_relative'] . '/' . static::resolveStream("{$url_parts['scheme']}://{$url_parts['path']}"); + unset($url_parts['stream'], $url_parts['scheme']); + + $excerpt['element']['attributes']['href'] = Uri::buildUrl($url_parts); + } + + return $excerpt; + } + + // Handle paths and such. + $url_parts = Uri::convertUrl($page, $url_parts, $type); + + // Build the URL from the component parts and set it on the element. + $excerpt['element']['attributes']['href'] = Uri::buildUrl($url_parts); + + return $excerpt; + } + + /** + * Process an image excerpt + * + * @param array $excerpt + * @param Page $page + * @return mixed + */ + public static function processImageExcerpt(array $excerpt, Page $page) + { + $url = htmlspecialchars_decode(urldecode($excerpt['element']['attributes']['src'])); + $url_parts = static::parseUrl($url); + + $media = null; + $filename = null; + + if (!empty($url_parts['stream'])) { + $filename = $url_parts['scheme'] . '://' . (isset($url_parts['path']) ? $url_parts['path'] : ''); + + $media = $page->media(); + + } else { + // File is also local if scheme is http(s) and host matches. + $local_file = isset($url_parts['path']) + && (empty($url_parts['scheme']) || in_array($url_parts['scheme'], ['http', 'https'], true)) + && (empty($url_parts['host']) || $url_parts['host'] === Grav::instance()['uri']->host()); + + if ($local_file) { + $filename = basename($url_parts['path']); + $folder = dirname($url_parts['path']); + + // Get the local path to page media if possible. + if ($folder === $page->url(false, false, false)) { + // Get the media objects for this page. + $media = $page->media(); + } else { + // see if this is an external page to this one + $base_url = rtrim(Grav::instance()['base_url_relative'] . Grav::instance()['pages']->base(), '/'); + $page_route = '/' . ltrim(str_replace($base_url, '', $folder), '/'); + + /** @var Page $ext_page */ + $ext_page = Grav::instance()['pages']->dispatch($page_route, true); + if ($ext_page) { + $media = $ext_page->media(); + } else { + Grav::instance()->fireEvent('onMediaLocate', new Event(['route' => $page_route, 'media' => &$media])); + } + } + } + } + + // If there is a media file that matches the path referenced.. + if ($media && $filename && isset($media[$filename])) { + // Get the medium object. + /** @var Medium $medium */ + $medium = $media[$filename]; + + // Process operations + $medium = static::processMediaActions($medium, $url_parts); + $element_excerpt = $excerpt['element']['attributes']; + + $alt = isset($element_excerpt['alt']) ? $element_excerpt['alt'] : ''; + $title = isset($element_excerpt['title']) ? $element_excerpt['title'] : ''; + $class = isset($element_excerpt['class']) ? $element_excerpt['class'] : ''; + $id = isset($element_excerpt['id']) ? $element_excerpt['id'] : ''; + + $excerpt['element'] = $medium->parsedownElement($title, $alt, $class, $id, true); + + } else { + // Not a current page media file, see if it needs converting to relative. + $excerpt['element']['attributes']['src'] = Uri::buildUrl($url_parts); + } + + return $excerpt; + } + + /** + * Process media actions + * + * @param $medium + * @param $url + * @return mixed + */ + public static function processMediaActions($medium, $url) + { + if (!is_array($url)) { + $url_parts = parse_url($url); + } else { + $url_parts = $url; + } + + $actions = []; + + // if there is a query, then parse it and build action calls + if (isset($url_parts['query'])) { + $actions = array_reduce(explode('&', $url_parts['query']), function ($carry, $item) { + $parts = explode('=', $item, 2); + $value = isset($parts[1]) ? $parts[1] : null; + $carry[] = ['method' => $parts[0], 'params' => $value]; + + return $carry; + }, []); + } + + if (Grav::instance()['config']->get('system.images.auto_fix_orientation')) { + $actions[] = ['method' => 'fixOrientation', 'params' => '']; + } + $defaults = Grav::instance()['config']->get('system.images.defaults'); + if (is_array($defaults) && count($defaults)) { + foreach ($defaults as $method => $params) { + $actions[] = [ + 'method' => $method, + 'params' => $params, + ]; + } + } + + // loop through actions for the image and call them + foreach ($actions as $action) { + $matches = []; + + if (preg_match('/\[(.*)\]/', $action['params'], $matches)) { + $args = [explode(',', $matches[1])]; + } else { + $args = explode(',', $action['params']); + } + + $medium = call_user_func_array([$medium, $action['method']], $args); + } + + if (isset($url_parts['fragment'])) { + $medium->urlHash($url_parts['fragment']); + } + + return $medium; + } + + /** + * Variation of parse_url() which works also with local streams. + * + * @param string $url + * @return array|bool + */ + protected static function parseUrl($url) + { + $url_parts = Utils::multibyteParseUrl($url); + + if (isset($url_parts['scheme'])) { + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + + // Special handling for the streams. + if ($locator->schemeExists($url_parts['scheme'])) { + if (isset($url_parts['host'])) { + // Merge host and path into a path. + $url_parts['path'] = $url_parts['host'] . (isset($url_parts['path']) ? '/' . $url_parts['path'] : ''); + unset($url_parts['host']); + } + + $url_parts['stream'] = true; + } + } + + return $url_parts; + } + + protected static function resolveStream($url) + { + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + + return $locator->isStream($url) ? ($locator->findResource($url, false) ?: $locator->findResource($url, false, true)) : $url; + } +} diff --git a/system/src/Grav/Common/Helpers/Exif.php b/system/src/Grav/Common/Helpers/Exif.php new file mode 100644 index 0000000..ee0c4ca --- /dev/null +++ b/system/src/Grav/Common/Helpers/Exif.php @@ -0,0 +1,41 @@ +get('system.media.auto_metadata_exif')) { + if (function_exists('exif_read_data') && class_exists('\PHPExif\Reader\Reader')) { + $this->reader = \PHPExif\Reader\Reader::factory(\PHPExif\Reader\Reader::TYPE_NATIVE); + } else { + throw new \RuntimeException('Please enable the Exif extension for PHP or disable Exif support in Grav system configuration'); + } + } + } + + public function getReader() + { + if ($this->reader) { + return $this->reader; + } + + return false; + } +} diff --git a/system/src/Grav/Common/Helpers/Truncator.php b/system/src/Grav/Common/Helpers/Truncator.php new file mode 100644 index 0000000..b2a19db --- /dev/null +++ b/system/src/Grav/Common/Helpers/Truncator.php @@ -0,0 +1,234 @@ +getElementsByTagName("body")->item(0); + + // Iterate over words. + $words = new DOMWordsIterator($body); + $truncated = false; + foreach ($words as $word) { + + // If we have exceeded the limit, we delete the remainder of the content. + if ($words->key() >= $limit) { + + // Grab current position. + $currentWordPosition = $words->currentWordPosition(); + $curNode = $currentWordPosition[0]; + $offset = $currentWordPosition[1]; + $words = $currentWordPosition[2]; + + $curNode->nodeValue = substr( + $curNode->nodeValue, + 0, + $words[$offset][1] + strlen($words[$offset][0]) + ); + + self::removeProceedingNodes($curNode, $body); + + if (!empty($ellipsis)) { + self::insertEllipsis($curNode, $ellipsis); + } + + $truncated = true; + + break; + } + + } + + // Return original HTML if not truncated. + if ($truncated) { + return self::innerHTML($body); + } else { + return $html; + } + } + + /** + * Safely truncates HTML by a given number of letters. + * @param string $html Input HTML. + * @param integer $limit Limit to how many letters we preserve. + * @param string $ellipsis String to use as ellipsis (if any). + * @return string Safe truncated HTML. + */ + public static function truncateLetters($html, $limit = 0, $ellipsis = "") + { + if ($limit <= 0) { + return $html; + } + + $dom = self::htmlToDomDocument($html); + + // Grab the body of our DOM. + $body = $dom->getElementsByTagName('body')->item(0); + + // Iterate over letters. + $letters = new DOMLettersIterator($body); + $truncated = false; + foreach ($letters as $letter) { + + // If we have exceeded the limit, we want to delete the remainder of this document. + if ($letters->key() >= $limit) { + + $currentText = $letters->currentTextPosition(); + $currentText[0]->nodeValue = substr($currentText[0]->nodeValue, 0, $currentText[1] + 1); + self::removeProceedingNodes($currentText[0], $body); + + if (!empty($ellipsis)) { + self::insertEllipsis($currentText[0], $ellipsis); + } + + $truncated = true; + + break; + } + } + + // Return original HTML if not truncated. + if ($truncated) { + return self::innerHTML($body); + } else { + return $html; + } + } + + /** + * Builds a DOMDocument object from a string containing HTML. + * @param string $html HTML to load + * @returns DOMDocument Returns a DOMDocument object. + */ + public static function htmlToDomDocument($html) + { + if (!$html) { + $html = '

'; + } + + // Transform multibyte entities which otherwise display incorrectly. + $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'); + + // Internal errors enabled as HTML5 not fully supported. + libxml_use_internal_errors(true); + + // Instantiate new DOMDocument object, and then load in UTF-8 HTML. + $dom = new DOMDocument(); + $dom->encoding = 'UTF-8'; + $dom->loadHTML($html); + + return $dom; + } + + /** + * Removes all nodes after the current node. + * @param DOMNode|DOMElement $domNode + * @param DOMNode|DOMElement $topNode + * @return void + */ + private static function removeProceedingNodes($domNode, $topNode) + { + $nextNode = $domNode->nextSibling; + + if ($nextNode !== null) { + self::removeProceedingNodes($nextNode, $topNode); + $domNode->parentNode->removeChild($nextNode); + } else { + //scan upwards till we find a sibling + $curNode = $domNode->parentNode; + while ($curNode !== $topNode) { + if ($curNode->nextSibling !== null) { + $curNode = $curNode->nextSibling; + self::removeProceedingNodes($curNode, $topNode); + $curNode->parentNode->removeChild($curNode); + break; + } + $curNode = $curNode->parentNode; + } + } + } + + /** + * Inserts an ellipsis + * @param DOMNode|DOMElement $domNode Element to insert after. + * @param string $ellipsis Text used to suffix our document. + * @return void + */ + private static function insertEllipsis($domNode, $ellipsis) + { + $avoid = array('a', 'strong', 'em', 'h1', 'h2', 'h3', 'h4', 'h5'); //html tags to avoid appending the ellipsis to + + if ($domNode->parentNode->parentNode !== null && in_array($domNode->parentNode->nodeName, $avoid, true)) { + // Append as text node to parent instead + $textNode = new DOMText($ellipsis); + + if ($domNode->parentNode->parentNode->nextSibling) { + $domNode->parentNode->parentNode->insertBefore($textNode, $domNode->parentNode->parentNode->nextSibling); + } else { + $domNode->parentNode->parentNode->appendChild($textNode); + } + + } else { + // Append to current node + $domNode->nodeValue = rtrim($domNode->nodeValue) . $ellipsis; + } + } + + /** + * Returns the innerHTML of a particular DOMElement + * + * @param $element + * @return string + */ + private static function innerHTML($element) { + $innerHTML = ''; + $children = $element->childNodes; + foreach ($children as $child) + { + $tmp_dom = new DOMDocument(); + $tmp_dom->appendChild($tmp_dom->importNode($child, true)); + $innerHTML.=trim($tmp_dom->saveHTML()); + } + return $innerHTML; + } + +} diff --git a/system/src/Grav/Common/Inflector.php b/system/src/Grav/Common/Inflector.php new file mode 100644 index 0000000..f4a17ba --- /dev/null +++ b/system/src/Grav/Common/Inflector.php @@ -0,0 +1,332 @@ +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) ?: []; + } + } + + /** + * Pluralizes English nouns. + * + * @param string $word English noun to pluralize + * @param int $count The count + * + * @return string Plural noun + */ + public function pluralize($word, $count = 2) + { + $this->init(); + + if ($count == 1) { + return $word; + } + + $lowercased_word = strtolower($word); + + foreach ($this->uncountable as $_uncountable) { + if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) { + return $word; + } + } + + foreach ($this->irregular as $_plural => $_singular) { + if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) { + return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word); + } + } + + foreach ($this->plural as $rule => $replacement) { + if (preg_match($rule, $word)) { + return preg_replace($rule, $replacement, $word); + } + } + + return false; + + } + + /** + * Singularizes English nouns. + * + * @param string $word English noun to singularize + * @param int $count + * + * @return string Singular noun. + */ + public function singularize($word, $count = 1) + { + $this->init(); + + if ($count != 1) { + return $word; + } + + $lowercased_word = strtolower($word); + foreach ($this->uncountable as $_uncountable) { + if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) { + return $word; + } + } + + foreach ($this->irregular as $_plural => $_singular) { + if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) { + return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word); + } + } + + foreach ($this->singular as $rule => $replacement) { + if (preg_match($rule, $word)) { + return preg_replace($rule, $replacement, $word); + } + } + + return $word; + } + + /** + * Converts an underscored or CamelCase word into a English + * sentence. + * + * The titleize public function converts text like "WelcomePage", + * "welcome_page" or "welcome page" to this "Welcome + * Page". + * If second parameter is set to 'first' it will only + * capitalize the first character of the title. + * + * @param string $word Word to format as tile + * @param string $uppercase If set to 'first' it will only uppercase the + * first character. Otherwise it will uppercase all + * the words in the title. + * + * @return string Text formatted as title + */ + public function titleize($word, $uppercase = '') + { + $uppercase = $uppercase == 'first' ? 'ucfirst' : 'ucwords'; + + return $uppercase($this->humanize($this->underscorize($word))); + } + + /** + * Returns given word as CamelCased + * + * Converts a word like "send_email" to "SendEmail". It + * will remove non alphanumeric character from the word, so + * "who's online" will be converted to "WhoSOnline" + * + * @see variablize + * + * @param string $word Word to convert to camel case + * + * @return string UpperCamelCasedWord + */ + public function camelize($word) + { + return str_replace(' ', '', ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', $word))); + } + + /** + * Converts a word "into_it_s_underscored_version" + * + * Convert any "CamelCased" or "ordinary Word" into an + * "underscored_word". + * + * This can be really useful for creating friendly URLs. + * + * @param string $word Word to underscore + * + * @return string Underscored word + */ + public function underscorize($word) + { + $regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', $word); + $regex2 = preg_replace('/([a-zd])([A-Z])/', '\1_\2', $regex1); + $regex3 = preg_replace('/[^A-Z^a-z^0-9]+/', '_', $regex2); + + return strtolower($regex3); + } + + /** + * Converts a word "into-it-s-hyphenated-version" + * + * Convert any "CamelCased" or "ordinary Word" into an + * "hyphenated-word". + * + * This can be really useful for creating friendly URLs. + * + * @param string $word Word to hyphenate + * + * @return string hyphenized word + */ + public function hyphenize($word) + { + $regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1-\2', $word); + $regex2 = preg_replace('/([a-zd])([A-Z])/', '\1-\2', $regex1); + $regex3 = preg_replace('/[^A-Z^a-z^0-9]+/', '-', $regex2); + + return strtolower($regex3); + } + + /** + * Returns a human-readable string from $word + * + * Returns a human-readable string from $word, by replacing + * underscores with a space, and by upper-casing the initial + * character by default. + * + * If you need to uppercase all the words you just have to + * pass 'all' as a second parameter. + * + * @param string $word String to "humanize" + * @param string $uppercase If set to 'all' it will uppercase all the words + * instead of just the first one. + * + * @return string Human-readable word + */ + public function humanize($word, $uppercase = '') + { + $uppercase = $uppercase == 'all' ? 'ucwords' : 'ucfirst'; + + return $uppercase(str_replace('_', ' ', preg_replace('/_id$/', '', $word))); + } + + /** + * Same as camelize but first char is underscored + * + * Converts a word like "send_email" to "sendEmail". It + * will remove non alphanumeric character from the word, so + * "who's online" will be converted to "whoSOnline" + * + * @see camelize + * + * @param string $word Word to lowerCamelCase + * + * @return string Returns a lowerCamelCasedWord + */ + public function variablize($word) + { + $word = $this->camelize($word); + + return strtolower($word[0]) . substr($word, 1); + } + + /** + * Converts a class name to its table name according to rails + * naming conventions. + * + * Converts "Person" to "people" + * + * @see classify + * + * @param string $class_name Class name for getting related table_name. + * + * @return string plural_table_name + */ + public function tableize($class_name) + { + return $this->pluralize($this->underscorize($class_name)); + } + + /** + * Converts a table name to its class name according to rails + * naming conventions. + * + * Converts "people" to "Person" + * + * @see tableize + * + * @param string $table_name Table name for getting related ClassName. + * + * @return string SingularClassName + */ + public function classify($table_name) + { + return $this->camelize($this->singularize($table_name)); + } + + /** + * Converts number to its ordinal English form. + * + * This method converts 13 to 13th, 2 to 2nd ... + * + * @param integer $number Number to get its ordinal value + * + * @return string Ordinal representation of given string. + */ + public function ordinalize($number) + { + $this->init(); + + if (in_array(($number % 100), range(11, 13))) { + return $number . $this->ordinals['default']; + } else { + switch (($number % 10)) { + case 1: + return $number . $this->ordinals['first']; + break; + case 2: + return $number . $this->ordinals['second']; + break; + case 3: + return $number . $this->ordinals['third']; + break; + default: + return $number . $this->ordinals['default']; + break; + } + } + } + + /** + * Converts a number of days to a number of months + * + * @param int $days + * + * @return int + */ + public function monthize($days) + { + $now = new \DateTime(); + $end = new \DateTime(); + + $duration = new \DateInterval("P{$days}D"); + + $diff = $end->add($duration)->diff($now); + + // handle years + if ($diff->y > 0) { + $diff->m = $diff->m + 12 * $diff->y; + } + + return $diff->m; + } +} diff --git a/system/src/Grav/Common/Iterator.php b/system/src/Grav/Common/Iterator.php new file mode 100644 index 0000000..99fc0c4 --- /dev/null +++ b/system/src/Grav/Common/Iterator.php @@ -0,0 +1,263 @@ +items[$key])) ? $this->items[$key] : null; + } + + /** + * Clone the iterator. + */ + public function __clone() + { + foreach ($this as $key => $value) { + if (is_object($value)) { + $this->$key = clone $this->$key; + } + } + } + + /** + * Convents iterator to a comma separated list. + * + * @return string + */ + public function __toString() + { + return implode(',', $this->items); + } + + /** + * Remove item from the list. + * + * @param $key + */ + public function remove($key) + { + $this->offsetUnset($key); + } + + /** + * Return previous item. + * + * @return mixed + */ + public function prev() + { + return prev($this->items); + } + + /** + * Return nth item. + * + * @param int $key + * + * @return mixed|bool + */ + public function nth($key) + { + $items = array_keys($this->items); + + return (isset($items[$key])) ? $this->offsetGet($items[$key]) : false; + } + + /** + * Get the first item + * + * @return mixed + */ + public function first() + { + $items = array_keys($this->items); + + return $this->offsetGet(array_shift($items)); + } + + /** + * Get the last item + * + * @return mixed + */ + public function last() + { + $items = array_keys($this->items); + + return $this->offsetGet(array_pop($items)); + } + + /** + * Reverse the Iterator + * + * @return $this + */ + public function reverse() + { + $this->items = array_reverse($this->items); + + return $this; + } + + /** + * @param mixed $needle Searched value. + * + * @return string|bool Key if found, otherwise false. + */ + public function indexOf($needle) + { + foreach (array_values($this->items) as $key => $value) { + if ($value === $needle) { + return $key; + } + } + + return false; + } + + /** + * Shuffle items. + * + * @return $this + */ + public function shuffle() + { + $keys = array_keys($this->items); + shuffle($keys); + + $new = []; + foreach ($keys as $key) { + $new[$key] = $this->items[$key]; + } + + $this->items = $new; + + return $this; + } + + /** + * Slice the list. + * + * @param int $offset + * @param int $length + * + * @return $this + */ + public function slice($offset, $length = null) + { + $this->items = array_slice($this->items, $offset, $length); + + return $this; + } + + /** + * Pick one or more random entries. + * + * @param int $num Specifies how many entries should be picked. + * + * @return $this + */ + public function random($num = 1) + { + if ($num > count($this->items)) { + $num = count($this->items); + } + + $this->items = array_intersect_key($this->items, array_flip((array)array_rand($this->items, $num))); + + return $this; + } + + /** + * Append new elements to the list. + * + * @param array|Iterator $items Items to be appended. Existing keys will be overridden with the new values. + * + * @return $this + */ + public function append($items) + { + if ($items instanceof static) { + $items = $items->toArray(); + } + $this->items = array_merge($this->items, (array)$items); + + return $this; + } + + /** + * Filter elements from the list + * + * @param callable|null $callback A function the receives ($value, $key) and must return a boolean to indicate + * filter status + * + * @return $this + */ + public function filter(callable $callback = null) + { + foreach ($this->items as $key => $value) { + if ( + ($callback && !call_user_func($callback, $value, $key)) || + (!$callback && !(bool)$value) + ) { + unset($this->items[$key]); + } + } + + return $this; + } + + + /** + * Sorts elements from the list and returns a copy of the list in the proper order + * + * @param callable|null $callback + * + * @param bool $desc + * + * @return $this|array + * @internal param bool $asc + * + */ + public function sort(callable $callback = null, $desc = false) + { + if (!$callback || !is_callable($callback)) { + return $this; + } + + $items = $this->items; + uasort($items, $callback); + + return !$desc ? $items : array_reverse($items, true); + } +} diff --git a/system/src/Grav/Common/Language/Language.php b/system/src/Grav/Common/Language/Language.php new file mode 100644 index 0000000..173a4a7 --- /dev/null +++ b/system/src/Grav/Common/Language/Language.php @@ -0,0 +1,507 @@ +grav = $grav; + $this->config = $grav['config']; + $this->languages = $this->config->get('system.languages.supported', []); + $this->init(); + } + + /** + * Initialize the default and enabled languages + */ + public function init() + { + $this->default = reset($this->languages); + + if (empty($this->languages)) { + $this->enabled = false; + } + } + + /** + * Ensure that languages are enabled + * + * @return bool + */ + public function enabled() + { + return $this->enabled; + } + + /** + * Gets the array of supported languages + * + * @return array + */ + public function getLanguages() + { + return $this->languages; + } + + /** + * Sets the current supported languages manually + * + * @param $langs + */ + public function setLanguages($langs) + { + $this->languages = $langs; + $this->init(); + } + + /** + * Gets a pipe-separated string of available languages + * + * @return string + */ + public function getAvailable() + { + $languagesArray = $this->languages; //Make local copy + sort($languagesArray); + return implode('|', array_reverse($languagesArray)); + } + + /** + * Gets language, active if set, else default + * + * @return mixed + */ + public function getLanguage() + { + return $this->active ? $this->active : $this->default; + } + + /** + * Gets current default language + * + * @return mixed + */ + public function getDefault() + { + return $this->default; + } + + /** + * Sets default language manually + * + * @param $lang + * + * @return bool + */ + public function setDefault($lang) + { + if ($this->validate($lang)) { + $this->default = $lang; + + return $lang; + } + + return false; + } + + /** + * Gets current active language + * + * @return mixed + */ + public function getActive() + { + return $this->active; + } + + /** + * Sets active language manually + * + * @param $lang + * + * @return bool + */ + public function setActive($lang) + { + if ($this->validate($lang)) { + $this->active = $lang; + + return $lang; + } + + return false; + } + + /** + * Sets the active language based on the first part of the URL + * + * @param $uri + * + * @return mixed + */ + public function setActiveFromUri($uri) + { + $regex = '/(^\/(' . $this->getAvailable() . '))(?:\/|\?|$)/i'; + + // if languages set + if ($this->enabled()) { + // Try setting language from prefix of URL (/en/blah/blah). + if (preg_match($regex, $uri, $matches)) { + $this->lang_in_url = true; + $this->active = $matches[2]; + $uri = preg_replace("/\\" . $matches[1] . '/', '', $uri, 1); + + // Store in session if language is different. + if (isset($this->grav['session']) && $this->grav['session']->started() + && $this->config->get('system.languages.session_store_active', true) + && $this->grav['session']->active_language != $this->active + ) { + $this->grav['session']->active_language = $this->active; + } + } else { + // Try getting language from the session, else no active. + if (isset($this->grav['session']) && $this->grav['session']->started() + && $this->config->get('system.languages.session_store_active', true)) { + $this->active = $this->grav['session']->active_language ?: null; + } + // if still null, try from http_accept_language header + if ($this->active === null && $this->config->get('system.languages.http_accept_language')) { + $preferred = $this->getBrowserLanguages(); + foreach ($preferred as $lang) { + if ($this->validate($lang)) { + $this->active = $lang; + break; + } + } + + // Repeat if not found, try base language only - fixes Safari sending the language code always + // with a locale (e.g. it-it or fr-fr). + foreach ($preferred as $lang) { + $lang = substr($lang, 0, 2); + if ($this->validate($lang)) { + $this->active = $lang; + break; + } + } + } + } + } + + return $uri; + } + + /** + * Get's a URL prefix based on configuration + * + * @param null $lang + * @return string + */ + public function getLanguageURLPrefix($lang = null) + { + // if active lang is not passed in, use current active + if (!$lang) { + $lang = $this->getLanguage(); + } + + return $this->isIncludeDefaultLanguage($lang) ? '/' . $lang : ''; + } + + /** + * Test to see if language is default and language should be included in the URL + * + * @param null $lang + * @return bool + */ + public function isIncludeDefaultLanguage($lang = null) + { + // if active lang is not passed in, use current active + if (!$lang) { + $lang = $this->getLanguage(); + } + + if ($this->default == $lang && $this->config->get('system.languages.include_default_lang') === false) { + return false; + } else { + return true; + } + } + + /** + * Simple getter to tell if a language was found in the URL + * + * @return bool + */ + public function isLanguageInUrl() + { + return (bool) $this->lang_in_url; + } + + + /** + * Gets an array of valid extensions with active first, then fallback extensions + * + * @param string|null $file_ext + * + * @return array + */ + public function getFallbackPageExtensions($file_ext = null) + { + if (empty($this->page_extensions)) { + if (empty($file_ext)) { + $file_ext = CONTENT_EXT; + } + + if ($this->enabled()) { + $valid_lang_extensions = []; + foreach ($this->languages as $lang) { + $valid_lang_extensions[] = '.' . $lang . $file_ext; + } + + if ($this->active) { + $active_extension = '.' . $this->active . $file_ext; + $key = array_search($active_extension, $valid_lang_extensions); + unset($valid_lang_extensions[$key]); + array_unshift($valid_lang_extensions, $active_extension); + } + + $this->page_extensions = array_merge($valid_lang_extensions, (array)$file_ext); + } else { + $this->page_extensions = (array)$file_ext; + } + } + + return $this->page_extensions; + } + + /** + * Resets the page_extensions value. + * + * Useful to re-initialize the pages and change site language at runtime, example: + * + * ``` + * $this->grav['language']->setActive('it'); + * $this->grav['language']->resetFallbackPageExtensions(); + * $this->grav['pages']->init(); + * ``` + */ + public function resetFallbackPageExtensions() { + $this->page_extensions = null; + } + + /** + * Gets an array of languages with active first, then fallback languages + * + * @return array + */ + public function getFallbackLanguages() + { + if (empty($this->fallback_languages)) { + if ($this->enabled()) { + $fallback_languages = $this->languages; + + if ($this->active) { + $active_extension = $this->active; + $key = array_search($active_extension, $fallback_languages); + unset($fallback_languages[$key]); + array_unshift($fallback_languages, $active_extension); + } + $this->fallback_languages = $fallback_languages; + } + // always add english in case a translation doesn't exist + $this->fallback_languages[] = 'en'; + } + + return $this->fallback_languages; + } + + /** + * Ensures the language is valid and supported + * + * @param $lang + * + * @return bool + */ + public function validate($lang) + { + if (in_array($lang, $this->languages)) { + return true; + } + + return false; + } + + /** + * Translate a key and possibly arguments into a string using current lang and fallbacks + * + * @param mixed $args The first argument is the lookup key value + * Other arguments can be passed and replaced in the translation with sprintf syntax + * @param array $languages + * @param bool $array_support + * @param bool $html_out + * + * @return string + */ + public function translate($args, array $languages = null, $array_support = false, $html_out = false) + { + if (is_array($args)) { + $lookup = array_shift($args); + } else { + $lookup = $args; + $args = []; + } + + if ($this->config->get('system.languages.translations', true)) { + if ($this->enabled() && $lookup) { + if (empty($languages)) { + if ($this->config->get('system.languages.translations_fallback', true)) { + $languages = $this->getFallbackLanguages(); + } else { + $languages = (array)$this->getLanguage(); + } + } + } else { + $languages = ['en']; + } + + foreach ((array)$languages as $lang) { + $translation = $this->getTranslation($lang, $lookup, $array_support); + + if ($translation) { + if (count($args) >= 1) { + return vsprintf($translation, $args); + } else { + return $translation; + } + } + } + } + + if ($html_out) { + return '' . $lookup . ''; + } else { + return $lookup; + } + } + + /** + * Translate Array + * + * @param $key + * @param $index + * @param null $languages + * @param bool $html_out + * + * @return string + */ + public function translateArray($key, $index, $languages = null, $html_out = false) + { + if ($this->config->get('system.languages.translations', true)) { + if ($this->enabled() && $key) { + if (empty($languages)) { + if ($this->config->get('system.languages.translations_fallback', true)) { + $languages = $this->getFallbackLanguages(); + } else { + $languages = (array)$this->getDefault(); + } + } + } else { + $languages = ['en']; + } + + foreach ((array)$languages as $lang) { + $translation_array = (array)Grav::instance()['languages']->get($lang . '.' . $key, null); + if ($translation_array && array_key_exists($index, $translation_array)) { + return $translation_array[$index]; + } + } + } + + if ($html_out) { + return '' . $key . '[' . $index . ']'; + } else { + return $key . '[' . $index . ']'; + } + } + + /** + * Lookup the translation text for a given lang and key + * + * @param string $lang lang code + * @param string $key key to lookup with + * @param bool $array_support + * + * @return string + */ + public function getTranslation($lang, $key, $array_support = false) + { + $translation = Grav::instance()['languages']->get($lang . '.' . $key, null); + if (!$array_support && is_array($translation)) { + return (string)array_shift($translation); + } + + return $translation; + } + + /** + * Get the browser accepted languages + * + * @param array $accept_langs + * + * @return array + */ + public function getBrowserLanguages($accept_langs = []) + { + if (empty($this->http_accept_language)) { + if (empty($accept_langs) && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { + $accept_langs = $_SERVER['HTTP_ACCEPT_LANGUAGE']; + } else { + return $accept_langs; + } + + foreach (explode(',', $accept_langs) as $k => $pref) { + // split $pref again by ';q=' + // and decorate the language entries by inverted position + if (false !== ($i = strpos($pref, ';q='))) { + $langs[substr($pref, 0, $i)] = [(float)substr($pref, $i + 3), -$k]; + } else { + $langs[$pref] = [1, -$k]; + } + } + arsort($langs); + + // no need to undecorate, because we're only interested in the keys + $this->http_accept_language = array_keys($langs); + } + return $this->http_accept_language; + } + +} diff --git a/system/src/Grav/Common/Language/LanguageCodes.php b/system/src/Grav/Common/Language/LanguageCodes.php new file mode 100644 index 0000000..063d41d --- /dev/null +++ b/system/src/Grav/Common/Language/LanguageCodes.php @@ -0,0 +1,207 @@ + [ 'name' => 'Afrikaans', 'nativeName' => 'Afrikaans' ], + 'ak' => [ 'name' => 'Akan', 'nativeName' => 'Akan' ], // unverified native name + 'ast' => [ 'name' => 'Asturian', 'nativeName' => 'Asturianu' ], + 'ar' => [ 'name' => 'Arabic', 'nativeName' => 'عربي', 'orientation' => 'rtl'], + 'as' => [ 'name' => 'Assamese', 'nativeName' => 'অসমীয়া' ], + 'be' => [ 'name' => 'Belarusian', 'nativeName' => 'Беларуская' ], + 'bg' => [ 'name' => 'Bulgarian', 'nativeName' => 'Български' ], + 'bn' => [ 'name' => 'Bengali', 'nativeName' => 'বাংলা' ], + 'bn-BD' => [ 'name' => 'Bengali (Bangladesh)', 'nativeName' => 'বাংলা (বাংলাদেশ)' ], + 'bn-IN' => [ 'name' => 'Bengali (India)', 'nativeName' => 'বাংলা (ভারত)' ], + 'br' => [ 'name' => 'Breton', 'nativeName' => 'Brezhoneg' ], + 'bs' => [ 'name' => 'Bosnian', 'nativeName' => 'Bosanski' ], + 'ca' => [ 'name' => 'Catalan', 'nativeName' => 'Català' ], + 'ca-valencia'=> [ 'name' => 'Catalan (Valencian)', 'nativeName' => 'Català (valencià)' ], // not iso-639-1. a=l10n-drivers + 'cs' => [ 'name' => 'Czech', 'nativeName' => 'Čeština' ], + 'cy' => [ 'name' => 'Welsh', 'nativeName' => 'Cymraeg' ], + 'da' => [ 'name' => 'Danish', 'nativeName' => 'Dansk' ], + 'de' => [ 'name' => 'German', 'nativeName' => 'Deutsch' ], + 'de-AT' => [ 'name' => 'German (Austria)', 'nativeName' => 'Deutsch (Österreich)' ], + 'de-CH' => [ 'name' => 'German (Switzerland)', 'nativeName' => 'Deutsch (Schweiz)' ], + 'de-DE' => [ 'name' => 'German (Germany)', 'nativeName' => 'Deutsch (Deutschland)' ], + 'dsb' => [ 'name' => 'Lower Sorbian', 'nativeName' => 'Dolnoserbšćina' ], // iso-639-2 + 'el' => [ 'name' => 'Greek', 'nativeName' => 'Ελληνικά' ], + 'en' => [ 'name' => 'English', 'nativeName' => 'English' ], + 'en-AU' => [ 'name' => 'English (Australian)', 'nativeName' => 'English (Australian)' ], + 'en-CA' => [ 'name' => 'English (Canadian)', 'nativeName' => 'English (Canadian)' ], + 'en-GB' => [ 'name' => 'English (British)', 'nativeName' => 'English (British)' ], + 'en-NZ' => [ 'name' => 'English (New Zealand)', 'nativeName' => 'English (New Zealand)' ], + 'en-US' => [ 'name' => 'English (US)', 'nativeName' => 'English (US)' ], + 'en-ZA' => [ 'name' => 'English (South African)', 'nativeName' => 'English (South African)' ], + 'eo' => [ 'name' => 'Esperanto', 'nativeName' => 'Esperanto' ], + 'es' => [ 'name' => 'Spanish', 'nativeName' => 'Español' ], + 'es-AR' => [ 'name' => 'Spanish (Argentina)', 'nativeName' => 'Español (de Argentina)' ], + 'es-CL' => [ 'name' => 'Spanish (Chile)', 'nativeName' => 'Español (de Chile)' ], + 'es-ES' => [ 'name' => 'Spanish (Spain)', 'nativeName' => 'Español (de España)' ], + 'es-MX' => [ 'name' => 'Spanish (Mexico)', 'nativeName' => 'Español (de México)' ], + 'et' => [ 'name' => 'Estonian', 'nativeName' => 'Eesti keel' ], + 'eu' => [ 'name' => 'Basque', 'nativeName' => 'Euskara' ], + 'fa' => [ 'name' => 'Persian', 'nativeName' => 'فارسی' , 'orientation' => 'rtl' ], + 'fi' => [ 'name' => 'Finnish', 'nativeName' => 'Suomi' ], + 'fj-FJ' => [ 'name' => 'Fijian', 'nativeName' => 'Vosa vaka-Viti' ], + 'fr' => [ 'name' => 'French', 'nativeName' => 'Français' ], + 'fr-CA' => [ 'name' => 'French (Canada)', 'nativeName' => 'Français (Canada)' ], + 'fr-FR' => [ 'name' => 'French (France)', 'nativeName' => 'Français (France)' ], + 'fur' => [ 'name' => 'Friulian', 'nativeName' => 'Furlan' ], + 'fur-IT' => [ 'name' => 'Friulian', 'nativeName' => 'Furlan' ], + 'fy' => [ 'name' => 'Frisian', 'nativeName' => 'Frysk' ], + 'fy-NL' => [ 'name' => 'Frisian', 'nativeName' => 'Frysk' ], + 'ga' => [ 'name' => 'Irish', 'nativeName' => 'Gaeilge' ], + 'ga-IE' => [ 'name' => 'Irish (Ireland)', 'nativeName' => 'Gaeilge (Éire)' ], + 'gd' => [ 'name' => 'Gaelic (Scotland)', 'nativeName' => 'Gàidhlig' ], + 'gl' => [ 'name' => 'Galician', 'nativeName' => 'Galego' ], + 'gu' => [ 'name' => 'Gujarati', 'nativeName' => 'ગુજરાતી' ], + 'gu-IN' => [ 'name' => 'Gujarati', 'nativeName' => 'ગુજરાતી' ], + 'he' => [ 'name' => 'Hebrew', 'nativeName' => 'עברית', 'orientation' => 'rtl' ], + 'hi' => [ 'name' => 'Hindi', 'nativeName' => 'हिन्दी' ], + 'hi-IN' => [ 'name' => 'Hindi (India)', 'nativeName' => 'हिन्दी (भारत)' ], + 'hr' => [ 'name' => 'Croatian', 'nativeName' => 'Hrvatski' ], + 'hsb' => [ 'name' => 'Upper Sorbian', 'nativeName' => 'Hornjoserbsce' ], + 'hu' => [ 'name' => 'Hungarian', 'nativeName' => 'Magyar' ], + 'hy' => [ 'name' => 'Armenian', 'nativeName' => 'Հայերեն' ], + 'hy-AM' => [ 'name' => 'Armenian', 'nativeName' => 'Հայերեն' ], + 'id' => [ 'name' => 'Indonesian', 'nativeName' => 'Bahasa Indonesia' ], + 'is' => [ 'name' => 'Icelandic', 'nativeName' => 'íslenska' ], + 'it' => [ 'name' => 'Italian', 'nativeName' => 'Italiano' ], + 'ja' => [ 'name' => 'Japanese', 'nativeName' => '日本語' ], + 'ja-JP' => [ 'name' => 'Japanese', 'nativeName' => '日本語' ], // not iso-639-1 + 'ka' => [ 'name' => 'Georgian', 'nativeName' => 'ქართული' ], + 'kk' => [ 'name' => 'Kazakh', 'nativeName' => 'Қазақ' ], + 'kn' => [ 'name' => 'Kannada', 'nativeName' => 'ಕನ್ನಡ' ], + 'ko' => [ 'name' => 'Korean', 'nativeName' => '한국어' ], + 'ku' => [ 'name' => 'Kurdish', 'nativeName' => 'Kurdî' ], + 'la' => [ 'name' => 'Latin', 'nativeName' => 'Latina' ], + 'lb' => [ 'name' => 'Luxembourgish', 'nativeName' => 'Lëtzebuergesch' ], + 'lg' => [ 'name' => 'Luganda', 'nativeName' => 'Luganda' ], + 'lt' => [ 'name' => 'Lithuanian', 'nativeName' => 'Lietuvių kalba' ], + 'lv' => [ 'name' => 'Latvian', 'nativeName' => 'Latviešu' ], + 'mai' => [ 'name' => 'Maithili', 'nativeName' => 'मैथिली মৈথিলী' ], + 'mg' => [ 'name' => 'Malagasy', 'nativeName' => 'Malagasy' ], + 'mi' => [ 'name' => 'Maori (Aotearoa)', 'nativeName' => 'Māori (Aotearoa)' ], + 'mk' => [ 'name' => 'Macedonian', 'nativeName' => 'Македонски' ], + 'ml' => [ 'name' => 'Malayalam', 'nativeName' => 'മലയാളം' ], + 'mn' => [ 'name' => 'Mongolian', 'nativeName' => 'Монгол' ], + 'mr' => [ 'name' => 'Marathi', 'nativeName' => 'मराठी' ], + 'no' => [ 'name' => 'Norwegian', 'nativeName' => 'Norsk' ], + 'nb' => [ 'name' => 'Norwegian', 'nativeName' => 'Norsk' ], + 'nb-NO' => [ 'name' => 'Norwegian (Bokmål)', 'nativeName' => 'Norsk bokmål' ], + 'ne-NP' => [ 'name' => 'Nepali', 'nativeName' => 'नेपाली' ], + 'nn-NO' => [ 'name' => 'Norwegian (Nynorsk)', 'nativeName' => 'Norsk nynorsk' ], + 'nl' => [ 'name' => 'Dutch', 'nativeName' => 'Nederlands' ], + 'nr' => [ 'name' => 'Ndebele, South', 'nativeName' => 'IsiNdebele' ], + 'nso' => [ 'name' => 'Northern Sotho', 'nativeName' => 'Sepedi' ], + 'oc' => [ 'name' => 'Occitan (Lengadocian)', 'nativeName' => 'Occitan (lengadocian)' ], + 'or' => [ 'name' => 'Oriya', 'nativeName' => 'ଓଡ଼ିଆ' ], + 'pa' => [ 'name' => 'Punjabi', 'nativeName' => 'ਪੰਜਾਬੀ' ], + 'pa-IN' => [ 'name' => 'Punjabi', 'nativeName' => 'ਪੰਜਾਬੀ' ], + 'pl' => [ 'name' => 'Polish', 'nativeName' => 'Polski' ], + 'pt' => [ 'name' => 'Portuguese', 'nativeName' => 'Português' ], + 'pt-BR' => [ 'name' => 'Portuguese (Brazilian)', 'nativeName' => 'Português (do Brasil)' ], + 'pt-PT' => [ 'name' => 'Portuguese (Portugal)', 'nativeName' => 'Português (Europeu)' ], + 'ro' => [ 'name' => 'Romanian', 'nativeName' => 'Română' ], + 'rm' => [ 'name' => 'Romansh', 'nativeName' => 'Rumantsch' ], + 'ru' => [ 'name' => 'Russian', 'nativeName' => 'Русский' ], + 'rw' => [ 'name' => 'Kinyarwanda', 'nativeName' => 'Ikinyarwanda' ], + 'si' => [ 'name' => 'Sinhala', 'nativeName' => 'සිංහල' ], + 'sk' => [ 'name' => 'Slovak', 'nativeName' => 'Slovenčina' ], + 'sl' => [ 'name' => 'Slovenian', 'nativeName' => 'Slovensko' ], + 'son' => [ 'name' => 'Songhai', 'nativeName' => 'Soŋay' ], + 'sq' => [ 'name' => 'Albanian', 'nativeName' => 'Shqip' ], + 'sr' => [ 'name' => 'Serbian', 'nativeName' => 'Српски' ], + 'sr-Latn' => [ 'name' => 'Serbian', 'nativeName' => 'Srpski' ], // follows RFC 4646 + 'ss' => [ 'name' => 'Siswati', 'nativeName' => 'siSwati' ], + 'st' => [ 'name' => 'Southern Sotho', 'nativeName' => 'Sesotho' ], + 'sv' => [ 'name' => 'Swedish', 'nativeName' => 'Svenska' ], + 'sv-SE' => [ 'name' => 'Swedish', 'nativeName' => 'Svenska' ], + 'ta' => [ 'name' => 'Tamil', 'nativeName' => 'தமிழ்' ], + 'ta-IN' => [ 'name' => 'Tamil (India)', 'nativeName' => 'தமிழ் (இந்தியா)' ], + 'ta-LK' => [ 'name' => 'Tamil (Sri Lanka)', 'nativeName' => 'தமிழ் (இலங்கை)' ], + 'te' => [ 'name' => 'Telugu', 'nativeName' => 'తెలుగు' ], + 'th' => [ 'name' => 'Thai', 'nativeName' => 'ไทย' ], + 'tlh' => [ 'name' => 'Klingon', 'nativeName' => 'Klingon' ], + 'tn' => [ 'name' => 'Tswana', 'nativeName' => 'Setswana' ], + 'tr' => [ 'name' => 'Turkish', 'nativeName' => 'Türkçe' ], + 'ts' => [ 'name' => 'Tsonga', 'nativeName' => 'Xitsonga' ], + 'tt' => [ 'name' => 'Tatar', 'nativeName' => 'Tatarça' ], + 'tt-RU' => [ 'name' => 'Tatar', 'nativeName' => 'Tatarça' ], + 'uk' => [ 'name' => 'Ukrainian', 'nativeName' => 'Українська' ], + 'ur' => [ 'name' => 'Urdu', 'nativeName' => 'اُردو', 'orientation' => 'rtl' ], + 've' => [ 'name' => 'Venda', 'nativeName' => 'Tshivenḓa' ], + 'vi' => [ 'name' => 'Vietnamese', 'nativeName' => 'Tiếng Việt' ], + 'wo' => [ 'name' => 'Wolof', 'nativeName' => 'Wolof' ], + 'xh' => [ 'name' => 'Xhosa', 'nativeName' => 'isiXhosa' ], + 'zh' => [ 'name' => 'Chinese (Simplified)', 'nativeName' => '中文 (简体)' ], + 'zh-CN' => [ 'name' => 'Chinese (Simplified)', 'nativeName' => '中文 (简体)' ], + 'zh-TW' => [ 'name' => 'Chinese (Traditional)', 'nativeName' => '正體中文 (繁體)' ], + 'zu' => [ 'name' => 'Zulu', 'nativeName' => 'isiZulu' ] + ]; + + public static function getName($code) + { + return static::get($code, 'name'); + } + + public static function getNativeName($code) + { + if (isset(static::$codes[$code])) { + return static::get($code, 'nativeName'); + } + + if (preg_match('/[a-zA-Z]{2}-[a-zA-Z]{2}/', $code)) { + return static::get(substr($code, 0, 2), 'nativeName') . ' (' . substr($code, -2) . ')'; + } + + return $code; + } + + public static function getOrientation($code) + { + if (isset(static::$codes[$code])) { + if (isset(static::$codes[$code]['orientation'])) { + return static::get($code, 'orientation'); + } + } + return 'ltr'; + } + + public static function isRtl($code) + { + if (static::getOrientation($code) === 'rtl') { + return true; + } + return false; + } + + public static function getNames(array $keys) + { + $results = []; + foreach ($keys as $key) { + if (isset(static::$codes[$key])) { + $results[$key] = static::$codes[$key]; + } + } + return $results; + } + + protected static function get($code, $type) + { + if (isset(static::$codes[$code][$type])) { + return static::$codes[$code][$type]; + } + + return false; + } +} diff --git a/system/src/Grav/Common/Markdown/Parsedown.php b/system/src/Grav/Common/Markdown/Parsedown.php new file mode 100644 index 0000000..b066ad3 --- /dev/null +++ b/system/src/Grav/Common/Markdown/Parsedown.php @@ -0,0 +1,26 @@ +init($page, $defaults); + } + +} diff --git a/system/src/Grav/Common/Markdown/ParsedownExtra.php b/system/src/Grav/Common/Markdown/ParsedownExtra.php new file mode 100644 index 0000000..481c52f --- /dev/null +++ b/system/src/Grav/Common/Markdown/ParsedownExtra.php @@ -0,0 +1,28 @@ +init($page, $defaults); + } +} diff --git a/system/src/Grav/Common/Markdown/ParsedownGravTrait.php b/system/src/Grav/Common/Markdown/ParsedownGravTrait.php new file mode 100644 index 0000000..59be69b --- /dev/null +++ b/system/src/Grav/Common/Markdown/ParsedownGravTrait.php @@ -0,0 +1,257 @@ +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])); + + } + + /** + * Be able to define a new Block type or override an existing one + * + * @param $type + * @param $tag + * @param bool $continuable + * @param bool $completable + * @param $index + */ + public function addBlockType($type, $tag, $continuable = false, $completable = false, $index = null) + { + $block = &$this->unmarkedBlockTypes; + if ($type) { + if (!isset($this->BlockTypes[$type])) { + $this->BlockTypes[$type] = []; + } + $block = &$this->BlockTypes[$type]; + } + + if (null === $index) { + $block[] = $tag; + } else { + array_splice($block, $index, 0, [$tag]); + } + + if ($continuable) { + $this->continuable_blocks[] = $tag; + } + if ($completable) { + $this->completable_blocks[] = $tag; + } + } + + /** + * Be able to define a new Inline type or override an existing one + * + * @param $type + * @param $tag + * @param $index + */ + public function addInlineType($type, $tag, $index = null) + { + if (null === $index || !isset($this->InlineTypes[$type])) { + $this->InlineTypes[$type] [] = $tag; + } else { + array_splice($this->InlineTypes[$type], $index, 0, [$tag]); + } + + if (strpos($this->inlineMarkerList, $type) === false) { + $this->inlineMarkerList .= $type; + } + } + + /** + * Overrides the default behavior to allow for plugin-provided blocks to be continuable + * + * @param $Type + * + * @return bool + */ + protected function isBlockContinuable($Type) + { + $continuable = \in_array($Type, $this->continuable_blocks) || method_exists($this, 'block' . $Type . 'Continue'); + + return $continuable; + } + + /** + * Overrides the default behavior to allow for plugin-provided blocks to be completable + * + * @param $Type + * + * @return bool + */ + protected function isBlockCompletable($Type) + { + $completable = \in_array($Type, $this->completable_blocks) || method_exists($this, 'block' . $Type . 'Complete'); + + return $completable; + } + + + /** + * Make the element function publicly accessible, Medium uses this to render from Twig + * + * @param array $Element + * + * @return string markup + */ + public function elementToHtml(array $Element) + { + return $this->element($Element); + } + + /** + * Setter for special chars + * + * @param $special_chars + * + * @return $this + */ + public function setSpecialChars($special_chars) + { + $this->special_chars = $special_chars; + + return $this; + } + + /** + * Ensure Twig tags are treated as block level items with no

tags + * + * @param array $line + * @return array|null + */ + protected function blockTwigTag($line) + { + if (preg_match('/(?:{{|{%|{#)(.*)(?:}}|%}|#})/', $line['body'], $matches)) { + return ['markup' => $line['body']]; + } + + return null; + } + + protected function inlineSpecialCharacter($excerpt) + { + if ($excerpt['text'][0] === '&' && !preg_match('/^&#?\w+;/', $excerpt['text'])) { + return [ + 'markup' => '&', + 'extent' => 1, + ]; + } + + if (isset($this->special_chars[$excerpt['text'][0]])) { + return [ + 'markup' => '&' . $this->special_chars[$excerpt['text'][0]] . ';', + 'extent' => 1, + ]; + } + + return null; + } + + protected function inlineImage($excerpt) + { + if (preg_match($this->twig_link_regex, $excerpt['text'], $matches)) { + $excerpt['text'] = str_replace($matches[1], '/', $excerpt['text']); + $excerpt = parent::inlineImage($excerpt); + $excerpt['element']['attributes']['src'] = $matches[1]; + $excerpt['extent'] = $excerpt['extent'] + strlen($matches[1]) - 1; + + return $excerpt; + } + + $excerpt['type'] = 'image'; + $excerpt = parent::inlineImage($excerpt); + + // if this is an image process it + if (isset($excerpt['element']['attributes']['src'])) { + $excerpt = Excerpts::processImageExcerpt($excerpt, $this->page); + } + + return $excerpt; + } + + protected function inlineLink($excerpt) + { + if (isset($excerpt['type'])) { + $type = $excerpt['type']; + } else { + $type = 'link'; + } + + // do some trickery to get around Parsedown requirement for valid URL if its Twig in there + if (preg_match($this->twig_link_regex, $excerpt['text'], $matches)) { + $excerpt['text'] = str_replace($matches[1], '/', $excerpt['text']); + $excerpt = parent::inlineLink($excerpt); + $excerpt['element']['attributes']['href'] = $matches[1]; + $excerpt['extent'] = $excerpt['extent'] + strlen($matches[1]) - 1; + + return $excerpt; + } + + $excerpt = parent::inlineLink($excerpt); + + // if this is a link + if (isset($excerpt['element']['attributes']['href'])) { + $excerpt = Excerpts::processLinkExcerpt($excerpt, $this->page, $type); + } + + return $excerpt; + } + + // For extending this class via plugins + public function __call($method, $args) + { + if (isset($this->{$method}) === true) { + $func = $this->{$method}; + + return \call_user_func_array($func, $args); + } + + return null; + } +} diff --git a/system/src/Grav/Common/Page/Collection.php b/system/src/Grav/Common/Page/Collection.php new file mode 100644 index 0000000..5113e81 --- /dev/null +++ b/system/src/Grav/Common/Page/Collection.php @@ -0,0 +1,632 @@ +params = $params; + $this->pages = $pages ? $pages : Grav::instance()->offsetGet('pages'); + } + + /** + * Get the collection params + * + * @return array + */ + public function params() + { + return $this->params; + } + + /** + * Add a single page to a collection + * + * @param Page $page + * + * @return $this + */ + public function addPage(Page $page) + { + $this->items[$page->path()] = ['slug' => $page->slug()]; + + return $this; + } + + /** + * Add a page with path and slug + * + * @param $path + * @param $slug + * @return $this + */ + public function add($path, $slug) + { + $this->items[$path] = ['slug' => $slug]; + + return $this; + } + + /** + * + * Create a copy of this collection + * + * @return static + */ + public function copy() + { + return new static($this->items, $this->params, $this->pages); + } + + /** + * + * Merge another collection with the current collection + * + * @param Collection $collection + * @return $this + */ + public function merge(Collection $collection) + { + foreach($collection as $page) { + $this->addPage($page); + } + return $this; + } + + /** + * Intersect another collection with the current collection + * + * @param Collection $collection + * @return $this + */ + public function intersect(Collection $collection) + { + $array1 = $this->items; + $array2 = $collection->toArray(); + + $this->items = array_uintersect($array1, $array2, function($val1, $val2) { + return strcmp($val1['slug'], $val2['slug']); + }); + return $this; + } + + /** + * Set parameters to the Collection + * + * @param array $params + * + * @return $this + */ + public function setParams(array $params) + { + $this->params = array_merge($this->params, $params); + return $this; + } + + /** + * Returns current page. + * + * @return Page + */ + public function current() + { + $current = parent::key(); + + return $this->pages->get($current); + } + + /** + * Returns current slug. + * + * @return mixed + */ + public function key() + { + $current = parent::current(); + + return $current['slug']; + } + + /** + * Returns the value at specified offset. + * + * @param mixed $offset The offset to retrieve. + * + * @return mixed Can return all value types. + */ + public function offsetGet($offset) + { + return !empty($this->items[$offset]) ? $this->pages->get($offset) : null; + } + + /** + * Split collection into array of smaller collections. + * + * @param $size + * @return array|Collection[] + */ + public function batch($size) + { + $chunks = array_chunk($this->items, $size, true); + + $list = []; + foreach ($chunks as $chunk) { + $list[] = new static($chunk, $this->params, $this->pages); + } + + return $list; + } + + /** + * Remove item from the list. + * + * @param Page|string|null $key + * + * @return $this + * @throws \InvalidArgumentException + */ + public function remove($key = null) + { + if ($key instanceof Page) { + $key = $key->path(); + } elseif (is_null($key)) { + $key = key($this->items); + } + if (!is_string($key)) { + throw new \InvalidArgumentException('Invalid argument $key.'); + } + + parent::remove($key); + + return $this; + } + + /** + * Reorder collection. + * + * @param string $by + * @param string $dir + * @param array $manual + * @param string $sort_flags + * + * @return $this + */ + public function order($by, $dir = 'asc', $manual = null, $sort_flags = null) + { + $this->items = $this->pages->sortCollection($this, $by, $dir, $manual, $sort_flags); + + return $this; + } + + /** + * Check to see if this item is the first in the collection. + * + * @param string $path + * + * @return boolean True if item is first. + */ + public function isFirst($path) + { + if ($this->items && $path == array_keys($this->items)[0]) { + return true; + } else { + return false; + } + } + + /** + * Check to see if this item is the last in the collection. + * + * @param string $path + * + * @return boolean True if item is last. + */ + public function isLast($path) + { + if ($this->items && $path == array_keys($this->items)[count($this->items) - 1]) { + return true; + } else { + return false; + } + } + + /** + * Gets the previous sibling based on current position. + * + * @param string $path + * + * @return Page The previous item. + */ + public function prevSibling($path) + { + return $this->adjacentSibling($path, -1); + } + + /** + * Gets the next sibling based on current position. + * + * @param string $path + * + * @return Page The next item. + */ + public function nextSibling($path) + { + return $this->adjacentSibling($path, 1); + } + + /** + * Returns the adjacent sibling based on a direction. + * + * @param string $path + * @param integer $direction either -1 or +1 + * + * @return Page The sibling item. + */ + public function adjacentSibling($path, $direction = 1) + { + $values = array_keys($this->items); + $keys = array_flip($values); + + if (array_key_exists($path, $keys)) { + $index = $keys[$path] - $direction; + + return isset($values[$index]) ? $this->offsetGet($values[$index]) : $this; + } + + return $this; + + } + + /** + * Returns the item in the current position. + * + * @param string $path the path the item + * + * @return Integer the index of the current page. + */ + public function currentPosition($path) + { + return array_search($path, array_keys($this->items)); + } + + /** + * Returns the items between a set of date ranges of either the page date field (default) or + * an arbitrary datetime page field where end date is optional + * Dates can be passed in as text that strtotime() can process + * http://php.net/manual/en/function.strtotime.php + * + * @param $startDate + * @param bool $endDate + * @param $field + * + * @return $this + * @throws \Exception + */ + public function dateRange($startDate, $endDate = false, $field = false) + { + $start = Utils::date2timestamp($startDate); + $end = $endDate ? Utils::date2timestamp($endDate) : false; + + $date_range = []; + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null) { + $date = $field ? strtotime($page->value($field)) : $page->date(); + + if ($date >= $start && (!$end || $date <= $end)) { + $date_range[$path] = $slug; + } + } + } + + $this->items = $date_range; + return $this; + } + + /** + * Creates new collection with only visible pages + * + * @return Collection The collection with only visible pages + */ + public function visible() + { + $visible = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null && $page->visible()) { + $visible[$path] = $slug; + } + } + $this->items = $visible; + + return $this; + } + + /** + * Creates new collection with only non-visible pages + * + * @return Collection The collection with only non-visible pages + */ + public function nonVisible() + { + $visible = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null && !$page->visible()) { + $visible[$path] = $slug; + } + } + $this->items = $visible; + + return $this; + } + + /** + * Creates new collection with only modular pages + * + * @return Collection The collection with only modular pages + */ + public function modular() + { + $modular = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null && $page->modular()) { + $modular[$path] = $slug; + } + } + $this->items = $modular; + + return $this; + } + + /** + * Creates new collection with only non-modular pages + * + * @return Collection The collection with only non-modular pages + */ + public function nonModular() + { + $modular = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null && !$page->modular()) { + $modular[$path] = $slug; + } + } + $this->items = $modular; + + return $this; + } + + /** + * Creates new collection with only published pages + * + * @return Collection The collection with only published pages + */ + public function published() + { + $published = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null && $page->published()) { + $published[$path] = $slug; + } + } + $this->items = $published; + + return $this; + } + + /** + * Creates new collection with only non-published pages + * + * @return Collection The collection with only non-published pages + */ + public function nonPublished() + { + $published = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null && !$page->published()) { + $published[$path] = $slug; + } + } + $this->items = $published; + + return $this; + } + + /** + * Creates new collection with only routable pages + * + * @return Collection The collection with only routable pages + */ + public function routable() + { + $routable = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + + if ($page !== null && $page->routable()) { + $routable[$path] = $slug; + } + } + + $this->items = $routable; + + return $this; + } + + /** + * Creates new collection with only non-routable pages + * + * @return Collection The collection with only non-routable pages + */ + public function nonRoutable() + { + $routable = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null && !$page->routable()) { + $routable[$path] = $slug; + } + } + $this->items = $routable; + + return $this; + } + + /** + * Creates new collection with only pages of the specified type + * + * @param $type + * + * @return Collection The collection + */ + public function ofType($type) + { + $items = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null && $page->template() == $type) { + $items[$path] = $slug; + } + } + + $this->items = $items; + + return $this; + } + + /** + * Creates new collection with only pages of one of the specified types + * + * @param $types + * + * @return Collection The collection + */ + public function ofOneOfTheseTypes($types) + { + $items = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + if ($page !== null && in_array($page->template(), $types)) { + $items[$path] = $slug; + } + } + + $this->items = $items; + + return $this; + } + + /** + * Creates new collection with only pages of one of the specified access levels + * + * @param $accessLevels + * + * @return Collection The collection + */ + public function ofOneOfTheseAccessLevels($accessLevels) + { + $items = []; + + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + + if ($page !== null && isset($page->header()->access)) { + if (is_array($page->header()->access)) { + //Multiple values for access + $valid = false; + + foreach ($page->header()->access as $index => $accessLevel) { + if (is_array($accessLevel)) { + foreach ($accessLevel as $innerIndex => $innerAccessLevel) { + if (in_array($innerAccessLevel, $accessLevels)) { + $valid = true; + } + } + } else { + if (in_array($index, $accessLevels)) { + $valid = true; + } + } + } + if ($valid) { + $items[$path] = $slug; + } + } else { + //Single value for access + if (in_array($page->header()->access, $accessLevels)) { + $items[$path] = $slug; + } + } + + } + } + + $this->items = $items; + + return $this; + } + + /** + * Get the extended version of this Collection with each page keyed by route + * + * @return array + * @throws \Exception + */ + public function toExtendedArray() + { + $items = []; + foreach ($this->items as $path => $slug) { + $page = $this->pages->get($path); + + if ($page !== null) { + $items[$page->route()] = $page->toArray(); + } + } + return $items; + } +} diff --git a/system/src/Grav/Common/Page/Header.php b/system/src/Grav/Common/Page/Header.php new file mode 100644 index 0000000..7df862b --- /dev/null +++ b/system/src/Grav/Common/Page/Header.php @@ -0,0 +1,17 @@ +path = $path; + + $this->__wakeup(); + $this->init(); + } + + /** + * Initialize static variables on unserialize. + */ + public function __wakeup() + { + if (!isset(static::$global)) { + // Add fallback to global media. + static::$global = new GlobalMedia(); + } + } + + /** + * @param mixed $offset + * + * @return bool + */ + public function offsetExists($offset) + { + return parent::offsetExists($offset) ?: isset(static::$global[$offset]); + } + + /** + * @param mixed $offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return parent::offsetGet($offset) ?: static::$global[$offset]; + } + + /** + * Initialize class. + */ + protected function init() + { + $config = Grav::instance()['config']; + $exif_reader = isset(Grav::instance()['exif']) ? Grav::instance()['exif']->getReader() : false; + $media_types = array_keys(Grav::instance()['config']->get('media.types')); + + // Handle special cases where page doesn't exist in filesystem. + if (!is_dir($this->path)) { + return; + } + + $iterator = new \FilesystemIterator($this->path, \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::SKIP_DOTS); + + $media = []; + + /** @var \DirectoryIterator $info */ + foreach ($iterator as $path => $info) { + // Ignore folders and Markdown files. + if (!$info->isFile() || $info->getExtension() === 'md' || $info->getBasename()[0] === '.') { + continue; + } + + // Find out what type we're dealing with + list($basename, $ext, $type, $extra) = $this->getFileParts($info->getFilename()); + + if (!in_array(strtolower($ext), $media_types)) { + continue; + } + + if ($type === 'alternative') { + $media["{$basename}.{$ext}"][$type][$extra] = [ 'file' => $path, 'size' => $info->getSize() ]; + } else { + $media["{$basename}.{$ext}"][$type] = [ 'file' => $path, 'size' => $info->getSize() ]; + } + } + + foreach ($media as $name => $types) { + // First prepare the alternatives in case there is no base medium + if (!empty($types['alternative'])) { + foreach ($types['alternative'] as $ratio => &$alt) { + $alt['file'] = MediumFactory::fromFile($alt['file']); + + if (!$alt['file']) { + unset($types['alternative'][$ratio]); + } else { + $alt['file']->set('size', $alt['size']); + } + } + } + + $file_path = null; + + // Create the base medium + if (empty($types['base'])) { + if (!isset($types['alternative'])) { + continue; + } + + $max = max(array_keys($types['alternative'])); + $medium = $types['alternative'][$max]['file']; + $file_path = $medium->path(); + $medium = MediumFactory::scaledFromMedium($medium, $max, 1)['file']; + } else { + $medium = MediumFactory::fromFile($types['base']['file']); + $medium && $medium->set('size', $types['base']['size']); + $file_path = $medium->path(); + } + + if (empty($medium)) { + continue; + } + + // metadata file + $meta_path = $file_path . '.meta.yaml'; + + if (file_exists($meta_path)) { + $types['meta']['file'] = $meta_path; + } elseif ($file_path && $medium->get('mime') === 'image/jpeg' && empty($types['meta']) && $config->get('system.media.auto_metadata_exif') && $exif_reader) { + + $meta = $exif_reader->read($file_path); + + if ($meta) { + $meta_data = $meta->getData(); + $meta_trimmed = array_diff_key($meta_data, array_flip($this->standard_exif)); + if ($meta_trimmed) { + $file = File::instance($meta_path); + $file->save(Yaml::dump($meta_trimmed)); + $types['meta']['file'] = $meta_path; + } + } + } + + if (!empty($types['meta'])) { + $medium->addMetaFile($types['meta']['file']); + } + + if (!empty($types['thumb'])) { + // We will not turn it into medium yet because user might never request the thumbnail + // not wasting any resources on that, maybe we should do this for medium in general? + $medium->set('thumbnails.page', $types['thumb']['file']); + } + + // Build missing alternatives + if (!empty($types['alternative'])) { + $alternatives = $types['alternative']; + $max = max(array_keys($alternatives)); + + for ($i=$max; $i > 1; $i--) { + if (isset($alternatives[$i])) { + continue; + } + + $types['alternative'][$i] = MediumFactory::scaledFromMedium($alternatives[$max]['file'], $max, $i); + } + + foreach ($types['alternative'] as $altMedium) { + if ($altMedium['file'] != $medium) { + $altWidth = $altMedium['file']->get('width'); + $medWidth = $medium->get('width'); + if ($altWidth && $medWidth) { + $ratio = $altWidth / $medWidth; + $medium->addAlternative($ratio, $altMedium['file']); + } + } + } + } + + $this->add($name, $medium); + } + } + + /** + * Enable accessing the media path + * + * @return mixed + */ + public function path() + { + return $this->path; + } +} diff --git a/system/src/Grav/Common/Page/Medium/AbstractMedia.php b/system/src/Grav/Common/Page/Medium/AbstractMedia.php new file mode 100644 index 0000000..fe0ac62 --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/AbstractMedia.php @@ -0,0 +1,186 @@ +offsetGet($filename); + } + + /** + * Call object as function to get medium by filename. + * + * @param string $filename + * @return mixed + */ + public function __invoke($filename) + { + return $this->offsetGet($filename); + } + + /** + * Get a list of all media. + * + * @return array|Medium[] + */ + public function all() + { + $this->instances = $this->orderMedia($this->instances); + + return $this->instances; + } + + /** + * Get a list of all image media. + * + * @return array|Medium[] + */ + public function images() + { + $this->images = $this->orderMedia($this->images); + return $this->images; + } + + /** + * Get a list of all video media. + * + * @return array|Medium[] + */ + public function videos() + { + $this->videos = $this->orderMedia($this->videos); + return $this->videos; + } + + /** + * Get a list of all audio media. + * + * @return array|Medium[] + */ + public function audios() + { + $this->audios = $this->orderMedia($this->audios); + return $this->audios; + } + + /** + * Get a list of all file media. + * + * @return array|Medium[] + */ + public function files() + { + $this->files = $this->orderMedia($this->files); + return $this->files; + } + + /** + * @param string $name + * @param Medium $file + */ + protected function add($name, $file) + { + $this->instances[$name] = $file; + switch ($file->type) { + case 'image': + $this->images[$name] = $file; + break; + case 'video': + $this->videos[$name] = $file; + break; + case 'audio': + $this->audios[$name] = $file; + break; + default: + $this->files[$name] = $file; + } + } + + /** + * Order the media based on the page's media_order + * + * @param $media + * @return array + */ + protected function orderMedia($media) + { + $page = Grav::instance()['pages']->get($this->path); + + if ($page && isset($page->header()->media_order)) { + $media_order = array_map('trim', explode(',', $page->header()->media_order)); + $media = Utils::sortArrayByArray($media, $media_order); + } else { + ksort($media, SORT_NATURAL | SORT_FLAG_CASE); + } + return $media; + } + + /** + * Get filename, extension and meta part. + * + * @param string $filename + * @return array + */ + protected function getFileParts($filename) + { + if (preg_match('/(.*)@(\d+)x\.(.*)$/', $filename, $matches)) { + $name = $matches[1]; + $extension = $matches[3]; + $extra = (int) $matches[2]; + $type = 'alternative'; + + if ($extra === 1) { + $type = 'base'; + $extra = null; + } + } else { + $fileParts = explode('.', $filename); + + $name = array_shift($fileParts); + $extension = null; + $extra = null; + $type = 'base'; + + while (($part = array_shift($fileParts)) !== null) { + if ($part != 'meta' && $part != 'thumb') { + if (isset($extension)) { + $name .= '.' . $extension; + } + $extension = $part; + } else { + $type = $part; + $extra = '.' . $part . '.' . implode('.', $fileParts); + break; + } + } + } + + return array($name, $extension, $type, $extra); + } +} diff --git a/system/src/Grav/Common/Page/Medium/AudioMedium.php b/system/src/Grav/Common/Page/Medium/AudioMedium.php new file mode 100644 index 0000000..aae3597 --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/AudioMedium.php @@ -0,0 +1,153 @@ +url($reset); + + return [ + 'name' => 'audio', + 'text' => 'Your browser does not support the audio tag.', + 'attributes' => $attributes + ]; + } + + /** + * Allows to set or remove the HTML5 default controls + * + * @param bool $display + * @return $this + */ + public function controls($display = true) + { + if($display) + { + $this->attributes['controls'] = true; + } + else + { + unset($this->attributes['controls']); + } + return $this; + } + + /** + * Allows to set the preload behaviour + * + * @param $preload + * @return $this + */ + public function preload($preload) + { + $validPreloadAttrs = array('auto','metadata','none'); + + if (in_array($preload, $validPreloadAttrs)) + { + $this->attributes['preload'] = $preload; + } + return $this; + } + + /** + * Allows to set the controlsList behaviour + * Separate multiple values with a hyphen + * + * @param $controlsList + * @return $this + */ + public function controlsList($controlsList) + { + $controlsList = str_replace('-', ' ', $controlsList); + $this->attributes['controlsList'] = $controlsList; + return $this; + } + + /** + * Allows to set the muted attribute + * + * @param bool $status + * @return $this + */ + public function muted($status = false) + { + if($status) + { + $this->attributes['muted'] = true; + } + else + { + unset($this->attributes['muted']); + } + return $this; + } + + /** + * Allows to set the loop attribute + * + * @param bool $status + * @return $this + */ + public function loop($status = false) + { + if($status) + { + $this->attributes['loop'] = true; + } + else + { + unset($this->attributes['loop']); + } + return $this; + } + + /** + * Allows to set the autoplay attribute + * + * @param bool $status + * @return $this + */ + public function autoplay($status = false) + { + if($status) + { + $this->attributes['autoplay'] = true; + } + else + { + unset($this->attributes['autoplay']); + } + return $this; + } + + + /** + * Reset medium. + * + * @return $this + */ + public function reset() + { + parent::reset(); + + $this->attributes['controls'] = true; + return $this; + } +} diff --git a/system/src/Grav/Common/Page/Medium/GlobalMedia.php b/system/src/Grav/Common/Page/Medium/GlobalMedia.php new file mode 100644 index 0000000..74adc08 --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/GlobalMedia.php @@ -0,0 +1,117 @@ +resolveStream($offset)); + } + + /** + * @param mixed $offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return parent::offsetGet($offset) ?: $this->addMedium($offset); + } + + /** + * @param string $filename + * @return string|null + */ + protected function resolveStream($filename) + { + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + + return $locator->isStream($filename) ? ($locator->findResource($filename) ?: null) : null; + } + + /** + * @param string $stream + * @return Medium|null + */ + protected function addMedium($stream) + { + $filename = $this->resolveStream($stream); + if (!$filename) { + return null; + } + + $path = dirname($filename); + list($basename, $ext,, $extra) = $this->getFileParts(basename($filename)); + $medium = MediumFactory::fromFile($filename); + + if (empty($medium)) { + return null; + } + + $medium->set('size', filesize($filename)); + $scale = (int) ($extra ?: 1); + + if ($scale !== 1) { + $altMedium = $medium; + + // Create scaled down regular sized image. + $medium = MediumFactory::scaledFromMedium($altMedium, $scale, 1)['file']; + + if (empty($medium)) { + return null; + } + + // Add original sized image as alternative. + $medium->addAlternative($scale, $altMedium['file']); + + // Locate or generate smaller retina images. + for ($i = $scale-1; $i > 1; $i--) { + $altFilename = "{$path}/{$basename}@{$i}x.{$ext}"; + + if (file_exists($altFilename)) { + $scaled = MediumFactory::fromFile($altFilename); + } else { + $scaled = MediumFactory::scaledFromMedium($altMedium, $scale, $i)['file']; + } + + if ($scaled) { + $medium->addAlternative($i, $scaled); + } + } + } + + $meta = "{$path}/{$basename}.{$ext}.yaml"; + if (file_exists($meta)) { + $medium->addMetaFile($meta); + } + $meta = "{$path}/{$basename}.{$ext}.meta.yaml"; + if (file_exists($meta)) { + $medium->addMetaFile($meta); + } + + $thumb = "{$path}/{$basename}.thumb.{$ext}"; + if (file_exists($thumb)) { + $medium->set('thumbnails.page', $thumb); + } + + $this->add($stream, $medium); + + return $medium; + } +} diff --git a/system/src/Grav/Common/Page/Medium/ImageFile.php b/system/src/Grav/Common/Page/Medium/ImageFile.php new file mode 100644 index 0000000..6834488 --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/ImageFile.php @@ -0,0 +1,101 @@ +operations = []; + } + + /** + * 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); + } + } +} diff --git a/system/src/Grav/Common/Page/Medium/ImageMedium.php b/system/src/Grav/Common/Page/Medium/ImageMedium.php new file mode 100644 index 0000000..05bc4c4 --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/ImageMedium.php @@ -0,0 +1,631 @@ + [0, 1], + 'forceResize' => [0, 1], + 'cropResize' => [0, 1], + 'crop' => [0, 1, 2, 3], + 'zoomCrop' => [0, 1] + ]; + + /** + * @var string + */ + protected $sizes = '100vw'; + + /** + * Construct. + * + * @param array $items + * @param Blueprint $blueprint + */ + public function __construct($items = [], Blueprint $blueprint = null) + { + parent::__construct($items, $blueprint); + + $config = Grav::instance()['config']; + + if (filesize($this->get('filepath')) === 0) { + return; + } + + $image_info = getimagesize($this->get('filepath')); + $this->def('width', $image_info[0]); + $this->def('height', $image_info[1]); + $this->def('mime', $image_info['mime']); + $this->def('debug', $config->get('system.images.debug')); + + $this->set('thumbnails.media', $this->get('filepath')); + + $this->default_quality = $config->get('system.images.default_image_quality', 85); + + $this->reset(); + + if ($config->get('system.images.cache_all', false)) { + $this->cache(); + } + } + + /** + * Add meta file for the medium. + * + * @param $filepath + * @return $this + */ + public function addMetaFile($filepath) + { + parent::addMetaFile($filepath); + + // Apply filters in meta file + $this->reset(); + + return $this; + } + + /** + * Clear out the alternatives + */ + public function clearAlternatives() + { + $this->alternatives = []; + } + + /** + * Return PATH to image. + * + * @param bool $reset + * @return string path to image + */ + public function path($reset = true) + { + $output = $this->saveImage(); + + if ($reset) { + $this->reset(); + } + + return $output; + } + + /** + * Return URL to image. + * + * @param bool $reset + * @return string + */ + public function url($reset = true) + { + $image_path = Grav::instance()['locator']->findResource('cache://images', true); + $image_dir = Grav::instance()['locator']->findResource('cache://images', false); + $saved_image_path = $this->saveImage(); + + $output = preg_replace('|^' . preg_quote(GRAV_ROOT) . '|', '', $saved_image_path); + + if (Utils::startsWith($output, $image_path)) { + $output = '/' . $image_dir . preg_replace('|^' . preg_quote($image_path) . '|', '', $output); + } + + if ($reset) { + $this->reset(); + } + + return trim(Grav::instance()['base_url'] . '/' . ltrim($output . $this->querystring() . $this->urlHash(), '/'), '\\'); + } + + /** + * Simply processes with no extra methods. Useful for triggering events. + * + * @return $this + */ + public function cache() + { + if (!$this->image) { + $this->image(); + } + + return $this; + } + + + /** + * Return srcset string for this Medium and its alternatives. + * + * @param bool $reset + * @return string + */ + public function srcset($reset = true) + { + if (empty($this->alternatives)) { + if ($reset) { + $this->reset(); + } + + return ''; + } + + $srcset = []; + foreach ($this->alternatives as $ratio => $medium) { + $srcset[] = $medium->url($reset) . ' ' . $medium->get('width') . 'w'; + } + $srcset[] = $this->url($reset) . ' ' . $this->get('width') . 'w'; + + return implode(', ', $srcset); + } + + /** + * Allows the ability to override the Inmage's Pretty name stored in cache + * + * @param $name + */ + public function setImagePrettyName($name) + { + $this->set('prettyname', $name); + if ($this->image) { + $this->image->setPrettyName($name); + } + } + + public function getImagePrettyName() + { + if ($this->get('prettyname')) { + return $this->get('prettyname'); + } else { + $basename = $this->get('basename'); + if (preg_match('/[a-z0-9]{40}-(.*)/', $basename, $matches)) { + $basename = $matches[1]; + } + return $basename; + } + } + + /** + * Generate alternative image widths, using either an array of integers, or + * a min width, a max width, and a step parameter to fill out the necessary + * widths. Existing image alternatives won't be overwritten. + * + * @param int|int[] $min_width + * @param int [$max_width=2500] + * @param int [$step=200] + * @return $this + */ + public function derivatives($min_width, $max_width = 2500, $step = 200) { + if (!empty($this->alternatives)) { + $max = max(array_keys($this->alternatives)); + $base = $this->alternatives[$max]; + } else { + $base = $this; + } + + $widths = []; + + if (func_num_args() === 1) { + foreach ((array) func_get_arg(0) as $width) { + if ($width < $base->get('width')) { + $widths[] = $width; + } + } + } else { + $max_width = min($max_width, $base->get('width')); + + for ($width = $min_width; $width < $max_width; $width = $width + $step) { + $widths[] = $width; + } + } + + foreach ($widths as $width) { + // Only generate image alternatives that don't already exist + if (array_key_exists((int) $width, $this->alternatives)) { + continue; + } + + $derivative = MediumFactory::fromFile($base->get('filepath')); + + // It's possible that MediumFactory::fromFile returns null if the + // original image file no longer exists and this class instance was + // retrieved from the page cache + if (isset($derivative)) { + $index = 2; + $alt_widths = array_keys($this->alternatives); + sort($alt_widths); + + foreach ($alt_widths as $i => $key) { + if ($width > $key) { + $index += max($i, 1); + } + } + + $basename = preg_replace('/(@\d+x){0,1}$/', "@{$width}w", $base->get('basename'), 1); + $derivative->setImagePrettyName($basename); + + $ratio = $base->get('width') / $width; + $height = $derivative->get('height') / $ratio; + + $derivative->resize($width, $height); + $derivative->set('width', $width); + $derivative->set('height', $height); + + $this->addAlternative($ratio, $derivative); + } + } + + return $this; + } + + /** + * Parsedown element for source display mode + * + * @param array $attributes + * @param boolean $reset + * @return array + */ + public function sourceParsedownElement(array $attributes, $reset = true) + { + empty($attributes['src']) && $attributes['src'] = $this->url(false); + + $srcset = $this->srcset($reset); + if ($srcset) { + empty($attributes['srcset']) && $attributes['srcset'] = $srcset; + $attributes['sizes'] = $this->sizes(); + } + + return [ 'name' => 'img', 'attributes' => $attributes ]; + } + + /** + * Reset image. + * + * @return $this + */ + public function reset() + { + parent::reset(); + + if ($this->image) { + $this->image(); + $this->image->clearOperations(); // Clear previously applied operations + $this->querystring(''); + $this->filter(); + $this->clearAlternatives(); + } + + $this->format = 'guess'; + $this->quality = $this->default_quality; + + $this->debug_watermarked = false; + + return $this; + } + + /** + * Turn the current Medium into a Link + * + * @param boolean $reset + * @param array $attributes + * @return Link + */ + public function link($reset = true, array $attributes = []) + { + $attributes['href'] = $this->url(false); + $srcset = $this->srcset(false); + if ($srcset) { + $attributes['data-srcset'] = $srcset; + } + + return parent::link($reset, $attributes); + } + + /** + * Turn the current Medium into a Link with lightbox enabled + * + * @param int $width + * @param int $height + * @param boolean $reset + * @return Link + */ + public function lightbox($width = null, $height = null, $reset = true) + { + if ($this->mode !== 'source') { + $this->display('source'); + } + + if ($width && $height) { + $this->cropResize($width, $height); + } + + return parent::lightbox($width, $height, $reset); + } + + /** + * Sets or gets the quality of the image + * + * @param int $quality 0-100 quality + * @return Medium + */ + public function quality($quality = null) + { + if ($quality) { + if (!$this->image) { + $this->image(); + } + + $this->quality = $quality; + return $this; + } + + return $this->quality; + } + + /** + * Sets image output format. + * + * @param string $format + * @return $this + */ + public function format($format) + { + if (!$this->image) { + $this->image(); + } + + $this->format = $format; + return $this; + } + + /** + * Set or get sizes parameter for srcset media action + * + * @param string $sizes + * @return $this + */ + public function sizes($sizes = null) + { + + if ($sizes) { + $this->sizes = $sizes; + return $this; + } + + return empty($this->sizes) ? '100vw' : $this->sizes; + } + + /** + * Allows to set the width attribute from Markdown or Twig + * Examples: ![Example](myimg.png?width=200&height=400) + * ![Example](myimg.png?resize=100,200&width=100&height=200) + * ![Example](myimg.png?width=auto&height=auto) + * ![Example](myimg.png?width&height) + * {{ page.media['myimg.png'].width().height().html }} + * {{ page.media['myimg.png'].resize(100,200).width(100).height(200).html }} + * + * @param mixed $value A value or 'auto' or empty to use the width of the image + * @return $this + */ + public function width($value = 'auto') + { + if (!$value || $value == 'auto') + $this->attributes['width'] = $this->get('width'); + else + $this->attributes['width'] = $value; + return $this; + } + + /** + * Allows to set the height attribute from Markdown or Twig + * Examples: ![Example](myimg.png?width=200&height=400) + * ![Example](myimg.png?resize=100,200&width=100&height=200) + * ![Example](myimg.png?width=auto&height=auto) + * ![Example](myimg.png?width&height) + * {{ page.media['myimg.png'].width().height().html }} + * {{ page.media['myimg.png'].resize(100,200).width(100).height(200).html }} + * + * @param mixed $value A value or 'auto' or empty to use the height of the image + * @return $this + */ + public function height($value = 'auto') + { + if (!$value || $value == 'auto') + $this->attributes['height'] = $this->get('height'); + else + $this->attributes['height'] = $value; + return $this; + } + + /** + * Forward the call to the image processing method. + * + * @param string $method + * @param mixed $args + * @return $this|mixed + */ + public function __call($method, $args) + { + if ($method == 'cropZoom') { + $method = 'zoomCrop'; + } + + if (!in_array($method, self::$magic_actions)) { + return parent::__call($method, $args); + } + + // Always initialize image. + if (!$this->image) { + $this->image(); + } + + try { + call_user_func_array([$this->image, $method], $args); + + foreach ($this->alternatives as $medium) { + if (!$medium->image) { + $medium->image(); + } + + $args_copy = $args; + + // regular image: resize 400x400 -> 200x200 + // --> @2x: resize 800x800->400x400 + if (isset(self::$magic_resize_actions[$method])) { + foreach (self::$magic_resize_actions[$method] as $param) { + if (isset($args_copy[$param])) { + $args_copy[$param] *= $medium->get('ratio'); + } + } + } + + call_user_func_array([$medium, $method], $args_copy); + } + } catch (\BadFunctionCallException $e) { + } + + return $this; + } + + /** + * Gets medium image, resets image manipulation operations. + * + * @return $this + */ + protected function image() + { + $locator = Grav::instance()['locator']; + + $file = $this->get('filepath'); + + // Use existing cache folder or if it doesn't exist, create it. + $cacheDir = $locator->findResource('cache://images', true) ?: $locator->findResource('cache://images', true, true); + + $this->image = ImageFile::open($file) + ->setCacheDir($cacheDir) + ->setActualCacheDir($cacheDir) + ->setPrettyName($this->getImagePrettyName()); + + return $this; + } + + /** + * Save the image with cache. + * + * @return mixed|string + */ + protected function saveImage() + { + if (!$this->image) { + return parent::path(false); + } + + $this->filter(); + + if (isset($this->result)) { + return $this->result; + } + + if ($this->get('debug') && !$this->debug_watermarked) { + $ratio = $this->get('ratio'); + if (!$ratio) { + $ratio = 1; + } + + $locator = Grav::instance()['locator']; + $overlay = $locator->findResource("system://assets/responsive-overlays/{$ratio}x.png") ?: $locator->findResource('system://assets/responsive-overlays/unknown.png'); + $this->image->merge(ImageFile::open($overlay)); + } + + return $this->image->cacheFile($this->format, $this->quality); + } + + /** + * Filter image by using user defined filter parameters. + * + * @param string $filter Filter to be used. + */ + public function filter($filter = 'image.filters.default') + { + $filters = (array) $this->get($filter, []); + foreach ($filters as $params) { + $params = (array) $params; + $method = array_shift($params); + $this->__call($method, $params); + } + } + + /** + * Return the image higher quality version + * + * @return ImageMedium the alternative version with higher quality + */ + public function higherQualityAlternative() + { + if ($this->alternatives) { + $max = reset($this->alternatives); + foreach($this->alternatives as $alternative) + { + if($alternative->quality() > $max->quality()) + { + $max = $alternative; + } + } + + return $max; + } else { + return $this; + } + } + +} diff --git a/system/src/Grav/Common/Page/Medium/Link.php b/system/src/Grav/Common/Page/Medium/Link.php new file mode 100644 index 0000000..15aac7b --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/Link.php @@ -0,0 +1,70 @@ +attributes = $attributes; + $this->source = $medium->reset()->thumbnail('auto')->display('thumbnail'); + $this->source->linked = true; + } + + /** + * Get an element (is array) that can be rendered by the Parsedown engine + * + * @param string $title + * @param string $alt + * @param string $class + * @param string $id + * @param boolean $reset + * @return array + */ + public function parsedownElement($title = null, $alt = null, $class = null, $id = null, $reset = true) + { + $innerElement = $this->source->parsedownElement($title, $alt, $class, $id, $reset); + + return [ + 'name' => 'a', + 'attributes' => $this->attributes, + 'handler' => is_string($innerElement) ? 'line' : 'element', + 'text' => $innerElement + ]; + } + + /** + * Forward the call to the source element + * + * @param string $method + * @param mixed $args + * @return mixed + */ + public function __call($method, $args) + { + $this->source = call_user_func_array(array($this->source, $method), $args); + + // Don't start nesting links, if user has multiple link calls in his + // actions, we will drop the previous links. + return $this->source instanceof Link ? $this->source : $this; + } +} diff --git a/system/src/Grav/Common/Page/Medium/Medium.php b/system/src/Grav/Common/Page/Medium/Medium.php new file mode 100644 index 0000000..6733680 --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/Medium.php @@ -0,0 +1,586 @@ +get('system.media.enable_media_timestamp', true)) { + $this->querystring('&' . Grav::instance()['cache']->getKey()); + } + + $this->def('mime', 'application/octet-stream'); + $this->reset(); + } + + /** + * Create a copy of this media object + * + * @return Medium + */ + public function copy() + { + return clone($this); + } + + /** + * Return just metadata from the Medium object + * + * @return Data + */ + public function meta() + { + return new Data($this->items); + } + + /** + * Check if this medium exists or not + * + * @return bool + */ + public function exists() + { + $path = $this->get('filepath'); + if (file_exists($path)) { + return true; + } + return false; + } + + /** + * Returns an array containing just the metadata + * + * @return array + */ + public function metadata() + { + return $this->metadata; + } + + /** + * Add meta file for the medium. + * + * @param $filepath + */ + public function addMetaFile($filepath) + { + $this->metadata = (array)CompiledYamlFile::instance($filepath)->content(); + $this->merge($this->metadata); + } + + /** + * Add alternative Medium to this Medium. + * + * @param $ratio + * @param Medium $alternative + */ + public function addAlternative($ratio, Medium $alternative) + { + if (!is_numeric($ratio) || $ratio === 0) { + return; + } + + $alternative->set('ratio', $ratio); + $width = $alternative->get('width'); + + $this->alternatives[$width] = $alternative; + } + + /** + * Return string representation of the object (html). + * + * @return string + */ + public function __toString() + { + return $this->html(); + } + + /** + * Return PATH to file. + * + * @param bool $reset + * @return string path to file + */ + public function path($reset = true) + { + if ($reset) { + $this->reset(); + } + + return $this->get('filepath'); + } + + /** + * Return the relative path to file + * + * @param bool $reset + * @return mixed + */ + public function relativePath($reset = true) + { + if ($reset) { + $this->reset(); + } + + return str_replace(GRAV_ROOT, '', $this->get('filepath')); + } + + /** + * Return URL to file. + * + * @param bool $reset + * @return string + */ + public function url($reset = true) + { + $output = preg_replace('|^' . preg_quote(GRAV_ROOT) . '|', '', $this->get('filepath')); + + if ($reset) { + $this->reset(); + } + + return trim(Grav::instance()['base_url'] . '/' . ltrim($output . $this->querystring() . $this->urlHash(), '/'), '\\'); + } + + /** + * Get/set querystring for the file's url + * + * @param string $querystring + * @param boolean $withQuestionmark + * @return string + */ + public function querystring($querystring = null, $withQuestionmark = true) + { + if (!is_null($querystring)) { + $this->set('querystring', ltrim($querystring, '?&')); + + foreach ($this->alternatives as $alt) { + $alt->querystring($querystring, $withQuestionmark); + } + } + + $querystring = $this->get('querystring', ''); + + if ($withQuestionmark && !empty($querystring)) { + return '?' . $querystring; + } else { + return $querystring; + } + } + + /** + * Get/set hash for the file's url + * + * @param string $hash + * @param boolean $withHash + * @return string + */ + public function urlHash($hash = null, $withHash = true) + { + if ($hash) { + $this->set('urlHash', ltrim($hash, '#')); + } + + $hash = $this->get('urlHash', ''); + + if ($withHash && !empty($hash)) { + return '#' . $hash; + } else { + return $hash; + } + } + + /** + * Get an element (is array) that can be rendered by the Parsedown engine + * + * @param string $title + * @param string $alt + * @param string $class + * @param string $id + * @param boolean $reset + * @return array + */ + public function parsedownElement($title = null, $alt = null, $class = null, $id = null, $reset = true) + { + $attributes = $this->attributes; + + $style = ''; + foreach ($this->styleAttributes as $key => $value) { + if (is_numeric($key)) // Special case for inline style attributes, refer to style() method + $style .= $value; + else + $style .= $key . ': ' . $value . ';'; + } + if ($style) { + $attributes['style'] = $style; + } + + if (empty($attributes['title'])) { + if (!empty($title)) { + $attributes['title'] = $title; + } elseif (!empty($this->items['title'])) { + $attributes['title'] = $this->items['title']; + } + } + + if (empty($attributes['alt'])) { + if (!empty($alt)) { + $attributes['alt'] = $alt; + } elseif (!empty($this->items['alt'])) { + $attributes['alt'] = $this->items['alt']; + } elseif (!empty($this->items['alt_text'])) { + $attributes['alt'] = $this->items['alt_text']; + } else { + $attributes['alt'] = ''; + } + } + + if (empty($attributes['class'])) { + if (!empty($class)) { + $attributes['class'] = $class; + } elseif (!empty($this->items['class'])) { + $attributes['class'] = $this->items['class']; + } + } + + if (empty($attributes['id'])) { + if (!empty($id)) { + $attributes['id'] = $id; + } elseif (!empty($this->items['id'])) { + $attributes['id'] = $this->items['id']; + } + } + + switch ($this->mode) { + case 'text': + $element = $this->textParsedownElement($attributes, false); + break; + case 'thumbnail': + $element = $this->getThumbnail()->sourceParsedownElement($attributes, false); + break; + case 'source': + $element = $this->sourceParsedownElement($attributes, false); + break; + } + + if ($reset) { + $this->reset(); + } + + $this->display('source'); + + return $element; + } + + /** + * Parsedown element for source display mode + * + * @param array $attributes + * @param boolean $reset + * @return array + */ + protected function sourceParsedownElement(array $attributes, $reset = true) + { + return $this->textParsedownElement($attributes, $reset); + } + + /** + * Parsedown element for text display mode + * + * @param array $attributes + * @param boolean $reset + * @return array + */ + protected function textParsedownElement(array $attributes, $reset = true) + { + $text = empty($attributes['title']) ? empty($attributes['alt']) ? $this->get('filename') : $attributes['alt'] : $attributes['title']; + + $element = [ + 'name' => 'p', + 'attributes' => $attributes, + 'text' => $text + ]; + + if ($reset) { + $this->reset(); + } + + return $element; + } + + /** + * Reset medium. + * + * @return $this + */ + public function reset() + { + $this->attributes = []; + return $this; + } + + /** + * Switch display mode. + * + * @param string $mode + * + * @return $this + */ + public function display($mode = 'source') + { + if ($this->mode === $mode) { + return $this; + } + + + $this->mode = $mode; + + return $mode === 'thumbnail' ? ($this->getThumbnail() ? $this->getThumbnail()->reset() : null) : $this->reset(); + } + + /** + * Helper method to determine if this media item has a thumbnail or not + * + * @param string $type; + * + * @return bool + */ + public function thumbnailExists($type = 'page') + { + $thumbs = $this->get('thumbnails'); + if (isset($thumbs[$type])) { + return true; + } + return false; + } + + /** + * Switch thumbnail. + * + * @param string $type + * + * @return $this + */ + public function thumbnail($type = 'auto') + { + if ($type !== 'auto' && !in_array($type, $this->thumbnailTypes)) { + return $this; + } + + if ($this->thumbnailType !== $type) { + $this->_thumbnail = null; + } + + $this->thumbnailType = $type; + + return $this; + } + + + /** + * Turn the current Medium into a Link + * + * @param boolean $reset + * @param array $attributes + * @return Link + */ + public function link($reset = true, array $attributes = []) + { + if ($this->mode !== 'source') { + $this->display('source'); + } + + foreach ($this->attributes as $key => $value) { + empty($attributes['data-' . $key]) && $attributes['data-' . $key] = $value; + } + + empty($attributes['href']) && $attributes['href'] = $this->url(); + + return new Link($attributes, $this); + } + + /** + * Turn the current Medium into a Link with lightbox enabled + * + * @param int $width + * @param int $height + * @param boolean $reset + * @return Link + */ + public function lightbox($width = null, $height = null, $reset = true) + { + $attributes = ['rel' => 'lightbox']; + + if ($width && $height) { + $attributes['data-width'] = $width; + $attributes['data-height'] = $height; + } + + return $this->link($reset, $attributes); + } + + /** + * Add a class to the element from Markdown or Twig + * Example: ![Example](myimg.png?classes=float-left) or ![Example](myimg.png?classes=myclass1,myclass2) + * + * @return $this + */ + public function classes() + { + $classes = func_get_args(); + if (!empty($classes)) { + $this->attributes['class'] = implode(',', (array)$classes); + } + + return $this; + } + + /** + * Add an id to the element from Markdown or Twig + * Example: ![Example](myimg.png?id=primary-img) + * + * @param $id + * @return $this + */ + public function id($id) + { + if (is_string($id)) { + $this->attributes['id'] = trim($id); + } + + return $this; + } + + /** + * Allows to add an inline style attribute from Markdown or Twig + * Example: ![Example](myimg.png?style=float:left) + * + * @param string $style + * @return $this + */ + public function style($style) + { + $this->styleAttributes[] = rtrim($style, ';') . ';'; + return $this; + } + + /** + * Allow any action to be called on this medium from twig or markdown + * + * @param string $method + * @param mixed $args + * @return $this + */ + public function __call($method, $args) + { + $qs = $method; + if (count($args) > 1 || (count($args) == 1 && !empty($args[0]))) { + $qs .= '=' . implode(',', array_map(function ($a) { + if (is_array($a)) { + $a = '[' . implode(',', $a) . ']'; + } + return rawurlencode($a); + }, $args)); + } + + if (!empty($qs)) { + $this->querystring($this->querystring(null, false) . '&' . $qs); + } + + return $this; + } + + /** + * Get the thumbnail Medium object + * + * @return ThumbnailImageMedium + */ + protected function getThumbnail() + { + if (!$this->_thumbnail) { + $types = $this->thumbnailTypes; + + if ($this->thumbnailType !== 'auto') { + array_unshift($types, $this->thumbnailType); + } + + foreach ($types as $type) { + $thumb = $this->get('thumbnails.' . $type, false); + + if ($thumb) { + $thumb = $thumb instanceof ThumbnailImageMedium ? $thumb : MediumFactory::fromFile($thumb, ['type' => 'thumbnail']); + $thumb->parent = $this; + } + + if ($thumb) { + $this->_thumbnail = $thumb; + break; + } + } + } + + return $this->_thumbnail; + } + +} diff --git a/system/src/Grav/Common/Page/Medium/MediumFactory.php b/system/src/Grav/Common/Page/Medium/MediumFactory.php new file mode 100644 index 0000000..b5b197e --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/MediumFactory.php @@ -0,0 +1,146 @@ +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); + } + + /** + * Create Medium from array of parameters + * + * @param array $items + * @param Blueprint|null $blueprint + * @return Medium + */ + public static function fromArray(array $items = [], Blueprint $blueprint = null) + { + $type = isset($items['type']) ? $items['type'] : null; + + switch ($type) { + case 'image': + return new ImageMedium($items, $blueprint); + break; + case 'thumbnail': + return new ThumbnailImageMedium($items, $blueprint); + break; + case 'animated': + case 'vector': + return new StaticImageMedium($items, $blueprint); + break; + case 'video': + return new VideoMedium($items, $blueprint); + break; + case 'audio': + return new AudioMedium($items, $blueprint); + break; + default: + return new Medium($items, $blueprint); + break; + } + } + + /** + * Create a new ImageMedium by scaling another ImageMedium object. + * + * @param ImageMedium $medium + * @param int $from + * @param int $to + * @return Medium|array + */ + public static function scaledFromMedium($medium, $from, $to) + { + if (! $medium instanceof ImageMedium) { + return $medium; + } + + if ($to > $from) { + return $medium; + } + + $ratio = $to / $from; + $width = $medium->get('width') * $ratio; + $height = $medium->get('height') * $ratio; + + $prev_basename = $medium->get('basename'); + $basename = str_replace('@'.$from.'x', '@'.$to.'x', $prev_basename); + + $debug = $medium->get('debug'); + $medium->set('debug', false); + $medium->setImagePrettyName($basename); + + $file = $medium->resize($width, $height)->path(); + + $medium->set('debug', $debug); + $medium->setImagePrettyName($prev_basename); + + $size = filesize($file); + + $medium = self::fromFile($file); + if ($medium) { + $medium->set('size', $size); + } + + return ['file' => $medium, 'size' => $size]; + } +} diff --git a/system/src/Grav/Common/Page/Medium/ParsedownHtmlTrait.php b/system/src/Grav/Common/Page/Medium/ParsedownHtmlTrait.php new file mode 100644 index 0000000..aaf6fde --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/ParsedownHtmlTrait.php @@ -0,0 +1,40 @@ +parsedownElement($title, $alt, $class, $id, $reset); + + if (!$this->parsedown) { + $this->parsedown = new Parsedown(null, null); + } + + return $this->parsedown->elementToHtml($element); + } +} diff --git a/system/src/Grav/Common/Page/Medium/RenderableInterface.php b/system/src/Grav/Common/Page/Medium/RenderableInterface.php new file mode 100644 index 0000000..35b0378 --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/RenderableInterface.php @@ -0,0 +1,35 @@ +url($reset); + + return [ 'name' => 'img', 'attributes' => $attributes ]; + } +} diff --git a/system/src/Grav/Common/Page/Medium/StaticResizeTrait.php b/system/src/Grav/Common/Page/Medium/StaticResizeTrait.php new file mode 100644 index 0000000..4e7d619 --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/StaticResizeTrait.php @@ -0,0 +1,27 @@ +styleAttributes['width'] = $width . 'px'; + $this->styleAttributes['height'] = $height . 'px'; + + return $this; + } +} diff --git a/system/src/Grav/Common/Page/Medium/ThumbnailImageMedium.php b/system/src/Grav/Common/Page/Medium/ThumbnailImageMedium.php new file mode 100644 index 0000000..6f88a2c --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/ThumbnailImageMedium.php @@ -0,0 +1,130 @@ +bubble('parsedownElement', [$title, $alt, $class, $id, $reset]); + } + + /** + * Return HTML markup from the medium. + * + * @param string $title + * @param string $alt + * @param string $class + * @param string $id + * @param bool $reset + * @return string + */ + public function html($title = null, $alt = null, $class = null, $id = null, $reset = true) + { + return $this->bubble('html', [$title, $alt, $class, $id, $reset]); + } + + /** + * Switch display mode. + * + * @param string $mode + * + * @return $this + */ + public function display($mode = 'source') + { + return $this->bubble('display', [$mode], false); + } + + /** + * Switch thumbnail. + * + * @param string $type + * + * @return $this + */ + public function thumbnail($type = 'auto') + { + $this->bubble('thumbnail', [$type], false); + return $this->bubble('getThumbnail', [], false); + } + + /** + * Turn the current Medium into a Link + * + * @param boolean $reset + * @param array $attributes + * @return Link + */ + public function link($reset = true, array $attributes = []) + { + return $this->bubble('link', [$reset, $attributes], false); + } + + /** + * Turn the current Medium into a Link with lightbox enabled + * + * @param int $width + * @param int $height + * @param boolean $reset + * @return Link + */ + public function lightbox($width = null, $height = null, $reset = true) + { + return $this->bubble('lightbox', [$width, $height, $reset], false); + } + + /** + * Bubble a function call up to either the superclass function or the parent Medium instance + * + * @param string $method + * @param array $arguments + * @param boolean $testLinked + * @return Medium + */ + protected function bubble($method, array $arguments = [], $testLinked = true) + { + if (!$testLinked || $this->linked) { + return $this->parent ? call_user_func_array(array($this->parent, $method), $arguments) : $this; + } + + return call_user_func_array(array($this, 'parent::' . $method), $arguments); + } +} diff --git a/system/src/Grav/Common/Page/Medium/VideoMedium.php b/system/src/Grav/Common/Page/Medium/VideoMedium.php new file mode 100644 index 0000000..b3c8eed --- /dev/null +++ b/system/src/Grav/Common/Page/Medium/VideoMedium.php @@ -0,0 +1,110 @@ +url($reset); + + return [ + 'name' => 'video', + 'text' => 'Your browser does not support the video tag.', + 'attributes' => $attributes + ]; + } + + /** + * Allows to set or remove the HTML5 default controls + * + * @param bool $display + * @return $this + */ + public function controls($display = true) + { + if($display) { + $this->attributes['controls'] = true; + } else { + unset($this->attributes['controls']); + } + + return $this; + } + + /** + * Allows to set the video's poster image + * + * @param $urlImage + * @return $this + */ + public function poster($urlImage) + { + $this->attributes['poster'] = $urlImage; + + return $this; + } + + /** + * Allows to set the loop attribute + * + * @param bool $status + * @return $this + */ + public function loop($status = false) + { + if($status) { + $this->attributes['loop'] = true; + } else { + unset($this->attributes['loop']); + } + + return $this; + } + + /** + * Allows to set the autoplay attribute + * + * @param bool $status + * @return $this + */ + public function autoplay($status = false) + { + if($status) { + $this->attributes['autoplay'] = true; + } else { + unset($this->attributes['autoplay']); + } + + return $this; + } + + /** + * Reset medium. + * + * @return $this + */ + public function reset() + { + parent::reset(); + + $this->attributes['controls'] = true; + + return $this; + } +} diff --git a/system/src/Grav/Common/Page/Page.php b/system/src/Grav/Common/Page/Page.php new file mode 100644 index 0000000..a4027a5 --- /dev/null +++ b/system/src/Grav/Common/Page/Page.php @@ -0,0 +1,2958 @@ +taxonomy = []; + $this->process = $config->get('system.pages.process'); + $this->published = true; + } + + /** + * Initializes the page instance variables based on a file + * + * @param \SplFileInfo $file The file information for the .md file that the page represents + * @param string $extension + * + * @return $this + */ + public function init(\SplFileInfo $file, $extension = null) + { + $config = Grav::instance()['config']; + + $this->hide_home_route = $config->get('system.home.hide_in_urls', false); + $this->home_route = $this->adjustRouteCase($config->get('system.home.alias')); + $this->filePath($file->getPathName()); + $this->modified($file->getMTime()); + $this->id($this->modified() . md5($this->filePath())); + $this->routable(true); + $this->header(); + $this->date(); + $this->metadata(); + $this->url(); + $this->visible(); + $this->modularTwig($this->slug[0] === '_'); + $this->setPublishState(); + $this->published(); + $this->urlExtension(); + + // some extension logic + if (empty($extension)) { + $this->extension('.' . $file->getExtension()); + } else { + $this->extension($extension); + } + + // extract page language from page extension + $language = trim(basename($this->extension(), 'md'), '.') ?: null; + $this->language($language); + + return $this; + } + + protected function processFrontmatter() + { + // Quick check for twig output tags in frontmatter if enabled + $process_fields = (array)$this->header(); + if (Utils::contains(json_encode(array_values($process_fields)), '{{')) { + $ignored_fields = []; + foreach ((array)Grav::instance()['config']->get('system.pages.frontmatter.ignore_fields') as $field) { + if (isset($process_fields[$field])) { + $ignored_fields[$field] = $process_fields[$field]; + unset($process_fields[$field]); + } + } + $text_header = Grav::instance()['twig']->processString(json_encode($process_fields), ['page' => $this]); + $this->header((object)(json_decode($text_header, true) + $ignored_fields)); + } + } + + /** + * Return an array with the routes of other translated languages + * + * @param bool $onlyPublished only return published translations + * + * @return array the page translated languages + */ + public function translatedLanguages($onlyPublished = false) + { + $filename = substr($this->name, 0, -(strlen($this->extension()))); + $config = Grav::instance()['config']; + $languages = $config->get('system.languages.supported', []); + $translatedLanguages = []; + + foreach ($languages as $language) { + $path = $this->path . DS . $this->folder . DS . $filename . '.' . $language . '.md'; + if (file_exists($path)) { + $aPage = new Page(); + $aPage->init(new \SplFileInfo($path), $language . '.md'); + + $route = isset($aPage->header()->routes['default']) ? $aPage->header()->routes['default'] : $aPage->rawRoute(); + if (!$route) { + $route = $aPage->slug(); + } + + if ($onlyPublished && !$aPage->published()) { + continue; + } + + $translatedLanguages[$language] = $route; + } + } + + return $translatedLanguages; + } + + /** + * Return an array listing untranslated languages available + * + * @param bool $includeUnpublished also list unpublished translations + * + * @return array the page untranslated languages + */ + public function untranslatedLanguages($includeUnpublished = false) + { + $filename = substr($this->name, 0, -(strlen($this->extension()))); + $config = Grav::instance()['config']; + $languages = $config->get('system.languages.supported', []); + $untranslatedLanguages = []; + + foreach ($languages as $language) { + $path = $this->path . DS . $this->folder . DS . $filename . '.' . $language . '.md'; + if (file_exists($path)) { + $aPage = new Page(); + $aPage->init(new \SplFileInfo($path), $language . '.md'); + if ($includeUnpublished && !$aPage->published()) { + $untranslatedLanguages[] = $language; + } + } else { + $untranslatedLanguages[] = $language; + } + } + + return $untranslatedLanguages; + } + + /** + * Gets and Sets the raw data + * + * @param string $var Raw content string + * + * @return string Raw content string + */ + public function raw($var = null) + { + $file = $this->file(); + + if ($var) { + // First update file object. + if ($file) { + $file->raw($var); + } + + // Reset header and content. + $this->modified = time(); + $this->id($this->modified() . md5($this->filePath())); + $this->header = null; + $this->content = null; + $this->summary = null; + } + + return $file ? $file->raw() : ''; + } + + /** + * Gets and Sets the page frontmatter + * + * @param string|null $var + * + * @return string + */ + public function frontmatter($var = null) + { + + if ($var) { + $this->frontmatter = (string)$var; + + // Update also file object. + $file = $this->file(); + if ($file) { + $file->frontmatter((string)$var); + } + + // Force content re-processing. + $this->id(time() . md5($this->filePath())); + } + if (!$this->frontmatter) { + $this->header(); + } + + return $this->frontmatter; + } + + /** + * Gets and Sets the header based on the YAML configuration at the top of the .md file + * + * @param object|array $var a YAML object representing the configuration for the file + * + * @return object the current YAML configuration + */ + public function header($var = null) + { + if ($var) { + $this->header = (object)$var; + + // Update also file object. + $file = $this->file(); + if ($file) { + $file->header((array)$var); + } + + // Force content re-processing. + $this->id(time() . md5($this->filePath())); + } + if (!$this->header) { + $file = $this->file(); + if ($file) { + // Set some options + $file->settings(['native' => true, 'compat' => true]); + try { + $this->raw_content = $file->markdown(); + $this->frontmatter = $file->frontmatter(); + $this->header = (object)$file->header(); + + if (!Utils::isAdminPlugin()) { + // If there's a `frontmatter.yaml` file merge that in with the page header + // note page's own frontmatter has precedence and will overwrite any defaults + $frontmatter_file = $this->path . '/' . $this->folder . '/frontmatter.yaml'; + if (file_exists($frontmatter_file)) { + $frontmatter_data = (array)Yaml::parse(file_get_contents($frontmatter_file)); + $this->header = (object)array_replace_recursive($frontmatter_data, + (array)$this->header); + } + // Process frontmatter with Twig if enabled + if (Grav::instance()['config']->get('system.pages.frontmatter.process_twig') === true) { + $this->processFrontmatter(); + } + } + } catch (ParseException $e) { + $file->raw(Grav::instance()['language']->translate([ + 'FRONTMATTER_ERROR_PAGE', + $this->slug(), + $file->filename(), + $e->getMessage(), + $file->raw() + ])); + $this->raw_content = $file->markdown(); + $this->frontmatter = $file->frontmatter(); + $this->header = (object)$file->header(); + } + $var = true; + } + + + } + + if ($var) { + if (isset($this->header->slug)) { + $this->slug(($this->header->slug)); + } + if (isset($this->header->routes)) { + $this->routes = (array)($this->header->routes); + } + if (isset($this->header->title)) { + $this->title = trim($this->header->title); + } + if (isset($this->header->language)) { + $this->language = trim($this->header->language); + } + if (isset($this->header->template)) { + $this->template = trim($this->header->template); + } + if (isset($this->header->menu)) { + $this->menu = trim($this->header->menu); + } + if (isset($this->header->routable)) { + $this->routable = (bool)$this->header->routable; + } + if (isset($this->header->visible)) { + $this->visible = (bool)$this->header->visible; + } + if (isset($this->header->redirect)) { + $this->redirect = trim($this->header->redirect); + } + if (isset($this->header->external_url)) { + $this->external_url = trim($this->header->external_url); + } + if (isset($this->header->order_dir)) { + $this->order_dir = trim($this->header->order_dir); + } + if (isset($this->header->order_by)) { + $this->order_by = trim($this->header->order_by); + } + if (isset($this->header->order_manual)) { + $this->order_manual = (array)$this->header->order_manual; + } + if (isset($this->header->dateformat)) { + $this->dateformat($this->header->dateformat); + } + if (isset($this->header->date)) { + $this->date($this->header->date); + } + if (isset($this->header->markdown_extra)) { + $this->markdown_extra = (bool)$this->header->markdown_extra; + } + if (isset($this->header->taxonomy)) { + foreach ((array)$this->header->taxonomy as $taxonomy => $taxitems) { + $this->taxonomy[$taxonomy] = (array)$taxitems; + } + } + if (isset($this->header->max_count)) { + $this->max_count = intval($this->header->max_count); + } + if (isset($this->header->process)) { + foreach ((array)$this->header->process as $process => $status) { + $this->process[$process] = (bool)$status; + } + } + if (isset($this->header->published)) { + $this->published = (bool)$this->header->published; + } + if (isset($this->header->publish_date)) { + $this->publishDate($this->header->publish_date); + } + if (isset($this->header->unpublish_date)) { + $this->unpublishDate($this->header->unpublish_date); + } + if (isset($this->header->expires)) { + $this->expires = intval($this->header->expires); + } + if (isset($this->header->cache_control)) { + $this->cache_control = $this->header->cache_control; + } + if (isset($this->header->etag)) { + $this->etag = (bool)$this->header->etag; + } + if (isset($this->header->last_modified)) { + $this->last_modified = (bool)$this->header->last_modified; + } + if (isset($this->header->ssl)) { + $this->ssl = (bool)$this->header->ssl; + } + if (isset($this->header->template_format)) { + $this->template_format = $this->header->template_format; + } + if (isset($this->header->debugger)) { + $this->debugger = (bool)$this->header->debugger; + } + } + + return $this->header; + } + + /** + * Get page language + * + * @param $var + * + * @return mixed + */ + public function language($var = null) + { + if ($var !== null) { + $this->language = $var; + } + + return $this->language; + } + + /** + * Modify a header value directly + * + * @param $key + * @param $value + */ + public function modifyHeader($key, $value) + { + $this->header->{$key} = $value; + } + + /** + * Get the summary. + * + * @param int $size Max summary size. + * + * @param boolean $textOnly Only count text size. + * + * @return string + */ + public function summary($size = null, $textOnly = false) + { + $config = (array)Grav::instance()['config']->get('site.summary'); + if (isset($this->header->summary)) { + $config = array_merge($config, $this->header->summary); + } + + // Return summary based on settings in site config file + if (!$config['enabled']) { + return $this->content(); + } + + // Set up variables to process summary from page or from custom summary + if ($this->summary === null) { + $content = $textOnly ? strip_tags($this->content()) : $this->content(); + $summary_size = $this->summary_size; + } else { + $content = strip_tags($this->summary); + // Use mb_strwidth to deal with the 2 character widths characters + $summary_size = mb_strwidth($content, 'utf-8'); + } + + // Return calculated summary based on summary divider's position + $format = $config['format']; + // Return entire page content on wrong/ unknown format + if (!in_array($format, ['short', 'long'])) { + return $content; + } + if (($format === 'short') && isset($summary_size)) { + // Use mb_strimwidth to slice the string + if (mb_strwidth($content, 'utf8') > $summary_size) { + return mb_substr($content, 0, $summary_size); + } + + return $content; + } + + // Get summary size from site config's file + if ($size === null) { + $size = $config['size']; + } + + // If the size is zero, return the entire page content + if ($size === 0) { + return $content; + // Return calculated summary based on defaults + } + if (!is_numeric($size) || ($size < 0)) { + $size = 300; + } + + // Only return string but not html, wrap whatever html tag you want when using + if ($textOnly) { + if (mb_strwidth($content, 'utf-8') <= $size) { + return $content; + } + + return mb_strimwidth($content, 0, $size, '...', 'utf-8'); + } + + $summary = Utils::truncateHTML($content, $size); + + return html_entity_decode($summary); + } + + /** + * Sets the summary of the page + * + * @param string $summary Summary + */ + public function setSummary($summary) + { + $this->summary = $summary; + } + + /** + * Gets and Sets the content based on content portion of the .md file + * + * @param string $var Content + * + * @return string Content + */ + public function content($var = null) + { + if ($var !== null) { + $this->raw_content = $var; + + // Update file object. + $file = $this->file(); + if ($file) { + $file->markdown($var); + } + + // Force re-processing. + $this->id(time() . md5($this->filePath())); + $this->content = null; + } + // If no content, process it + if ($this->content === null) { + // Get media + $this->media(); + + /** @var Config $config */ + $config = Grav::instance()['config']; + + // Load cached content + /** @var Cache $cache */ + $cache = Grav::instance()['cache']; + $cache_id = md5('page' . $this->id()); + $content_obj = $cache->fetch($cache_id); + + if (is_array($content_obj)) { + $this->content = $content_obj['content']; + $this->content_meta = $content_obj['content_meta']; + } else { + $this->content = $content_obj; + } + + + $process_markdown = $this->shouldProcess('markdown'); + $process_twig = $this->shouldProcess('twig') || $this->modularTwig(); + + $cache_enable = isset($this->header->cache_enable) ? $this->header->cache_enable : $config->get('system.cache.enabled', + true); + $twig_first = isset($this->header->twig_first) ? $this->header->twig_first : $config->get('system.pages.twig_first', + true); + + // never cache twig means it's always run after content + $never_cache_twig = isset($this->header->never_cache_twig) ? $this->header->never_cache_twig : $config->get('system.pages.never_cache_twig', + false); + + // if no cached-content run everything + if ($never_cache_twig) { + if ($this->content === false || $cache_enable === false) { + $this->content = $this->raw_content; + Grav::instance()->fireEvent('onPageContentRaw', new Event(['page' => $this])); + + if ($process_markdown) { + $this->processMarkdown(); + } + + // Content Processed but not cached yet + Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this])); + + if ($cache_enable) { + $this->cachePageContent(); + } + } + + if ($process_twig) { + $this->processTwig(); + } + + } else { + if ($this->content === false || $cache_enable === false) { + $this->content = $this->raw_content; + Grav::instance()->fireEvent('onPageContentRaw', new Event(['page' => $this])); + + if ($twig_first) { + if ($process_twig) { + $this->processTwig(); + } + if ($process_markdown) { + $this->processMarkdown(); + } + + // Content Processed but not cached yet + Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this])); + + } else { + if ($process_markdown) { + $this->processMarkdown(); + } + + // Content Processed but not cached yet + Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this])); + + if ($process_twig) { + $this->processTwig(); + } + } + + if ($cache_enable) { + $this->cachePageContent(); + } + } + } + + // Handle summary divider + $delimiter = $config->get('site.summary.delimiter', '==='); + $divider_pos = mb_strpos($this->content, "

{$delimiter}

"); + if ($divider_pos !== false) { + $this->summary_size = $divider_pos; + $this->content = str_replace("

{$delimiter}

", '', $this->content); + } + + } + + return $this->content; + } + + /** + * Get the contentMeta array and initialize content first if it's not already + * + * @return mixed + */ + public function contentMeta() + { + if ($this->content === null) { + $this->content(); + } + + return $this->getContentMeta(); + } + + /** + * Add an entry to the page's contentMeta array + * + * @param $name + * @param $value + */ + public function addContentMeta($name, $value) + { + $this->content_meta[$name] = $value; + } + + /** + * Return the whole contentMeta array as it currently stands + * + * @param null $name + * + * @return mixed + */ + public function getContentMeta($name = null) + { + if ($name) { + if (isset($this->content_meta[$name])) { + return $this->content_meta[$name]; + } + + return null; + } + + return $this->content_meta; + } + + /** + * Sets the whole content meta array in one shot + * + * @param $content_meta + * + * @return mixed + */ + public function setContentMeta($content_meta) + { + return $this->content_meta = $content_meta; + } + + /** + * Process the Markdown content. Uses Parsedown or Parsedown Extra depending on configuration + */ + protected function processMarkdown() + { + /** @var Config $config */ + $config = Grav::instance()['config']; + + $defaults = (array)$config->get('system.pages.markdown'); + if (isset($this->header()->markdown)) { + $defaults = array_merge($defaults, $this->header()->markdown); + } + + // pages.markdown_extra is deprecated, but still check it... + if (!isset($defaults['extra']) && (isset($this->markdown_extra) || $config->get('system.pages.markdown_extra') !== null)) { + $defaults['extra'] = $this->markdown_extra ?: $config->get('system.pages.markdown_extra'); + } + + // Initialize the preferred variant of Parsedown + if ($defaults['extra']) { + $parsedown = new ParsedownExtra($this, $defaults); + } else { + $parsedown = new Parsedown($this, $defaults); + } + + $this->content = $parsedown->text($this->content); + } + + + /** + * Process the Twig page content. + */ + private function processTwig() + { + $twig = Grav::instance()['twig']; + $this->content = $twig->processPage($this, $this->content); + } + + /** + * Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page + */ + public function cachePageContent() + { + $cache = Grav::instance()['cache']; + $cache_id = md5('page' . $this->id()); + $cache->save($cache_id, ['content' => $this->content, 'content_meta' => $this->content_meta]); + } + + /** + * Needed by the onPageContentProcessed event to get the raw page content + * + * @return string the current page content + */ + public function getRawContent() + { + return $this->content; + } + + /** + * Needed by the onPageContentProcessed event to set the raw page content + * + * @param $content + */ + public function setRawContent($content) + { + $this->content = $content; + } + + /** + * Get value from a page variable (used mostly for creating edit forms). + * + * @param string $name Variable name. + * @param mixed $default + * + * @return mixed + */ + public function value($name, $default = null) + { + if ($name === 'content') { + return $this->raw_content; + } + if ($name === 'route') { + return $this->parent()->rawRoute(); + } + if ($name === 'order') { + $order = $this->order(); + + return $order ? (int)$this->order() : ''; + } + if ($name === 'ordering') { + return (bool)$this->order(); + } + if ($name === 'folder') { + return preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder); + } + if ($name === 'slug') { + return $this->slug(); + } + if ($name === 'name') { + $language = $this->language() ? '.' . $this->language() : ''; + $name_val = str_replace($language . '.md', '', $this->name()); + if ($this->modular()) { + return 'modular/' . $name_val; + } + + return $name_val; + } + if ($name === 'media') { + return $this->media()->all(); + } + if ($name === 'media.file') { + return $this->media()->files(); + } + if ($name === 'media.video') { + return $this->media()->videos(); + } + if ($name === 'media.image') { + return $this->media()->images(); + } + if ($name === 'media.audio') { + return $this->media()->audios(); + } + + $path = explode('.', $name); + $scope = array_shift($path); + + if ($name === 'frontmatter') { + return $this->frontmatter; + } + + if ($scope === 'header') { + $current = $this->header(); + foreach ($path as $field) { + if (is_object($current) && isset($current->{$field})) { + $current = $current->{$field}; + } elseif (is_array($current) && isset($current[$field])) { + $current = $current[$field]; + } else { + return $default; + } + } + + return $current; + } + + return $default; + } + + /** + * Gets and Sets the Page raw content + * + * @param null $var + * + * @return null + */ + public function rawMarkdown($var = null) + { + if ($var !== null) { + $this->raw_content = $var; + } + + return $this->raw_content; + } + + /** + * Get file object to the page. + * + * @return MarkdownFile|null + */ + public function file() + { + if ($this->name) { + return MarkdownFile::instance($this->filePath()); + } + + return null; + } + + /** + * Save page if there's a file assigned to it. + * + * @param bool|mixed $reorder Internal use. + */ + public function save($reorder = true) + { + // Perform move, copy [or reordering] if needed. + $this->doRelocation(); + + $file = $this->file(); + if ($file) { + $file->filename($this->filePath()); + $file->header((array)$this->header()); + $file->markdown($this->raw_content); + $file->save(); + } + + // Perform reorder if required + if ($reorder && is_array($reorder)) { + $this->doReorder($reorder); + } + + $this->_original = null; + } + + /** + * Prepare move page to new location. Moves also everything that's under the current page. + * + * You need to call $this->save() in order to perform the move. + * + * @param Page $parent New parent page. + * + * @return $this + */ + public function move(Page $parent) + { + if (!$this->_original) { + $clone = clone $this; + $this->_original = $clone; + } + + $this->_action = 'move'; + + if ($this->route() === $parent->route()) { + throw new Exception('Failed: Cannot set page parent to self'); + } + if (Utils::startsWith($parent->rawRoute(), $this->rawRoute())) { + throw new Exception('Failed: Cannot set page parent to a child of current page'); + } + + $this->parent($parent); + $this->id(time() . md5($this->filePath())); + + if ($parent->path()) { + $this->path($parent->path() . '/' . $this->folder()); + } + + if ($parent->route()) { + $this->route($parent->route() . '/' . $this->slug()); + } else { + $this->route(Grav::instance()['pages']->root()->route() . '/' . $this->slug()); + } + + $this->raw_route = null; + + return $this; + } + + /** + * Prepare a copy from the page. Copies also everything that's under the current page. + * + * Returns a new Page object for the copy. + * You need to call $this->save() in order to perform the move. + * + * @param Page $parent New parent page. + * + * @return $this + */ + public function copy($parent) + { + $this->move($parent); + $this->_action = 'copy'; + + return $this; + } + + /** + * Get blueprints for the page. + * + * @return Blueprint + */ + public function blueprints() + { + $grav = Grav::instance(); + + /** @var Pages $pages */ + $pages = $grav['pages']; + + $blueprint = $pages->blueprints($this->blueprintName()); + $fields = $blueprint->fields(); + $edit_mode = isset($grav['admin']) ? $grav['config']->get('plugins.admin.edit_mode') : null; + + // override if you only want 'normal' mode + if (empty($fields) && ($edit_mode === 'auto' || $edit_mode === 'normal')) { + $blueprint = $pages->blueprints('default'); + } + + // override if you only want 'expert' mode + if (!empty($fields) && $edit_mode === 'expert') { + $blueprint = $pages->blueprints(''); + } + + return $blueprint; + } + + /** + * Get the blueprint name for this page. Use the blueprint form field if set + * + * @return string + */ + public function blueprintName() + { + $blueprint_name = filter_input(INPUT_POST, 'blueprint', FILTER_SANITIZE_STRING) ?: $this->template(); + + return $blueprint_name; + } + + /** + * Validate page header. + * + * @throws Exception + */ + public function validate() + { + $blueprints = $this->blueprints(); + $blueprints->validate($this->toArray()); + } + + /** + * Filter page header from illegal contents. + */ + public function filter() + { + $blueprints = $this->blueprints(); + $values = $blueprints->filter($this->toArray()); + if ($values && isset($values['header'])) { + $this->header($values['header']); + } + } + + /** + * Get unknown header variables. + * + * @return array + */ + public function extra() + { + $blueprints = $this->blueprints(); + + return $blueprints->extra($this->toArray()['header'], 'header.'); + } + + /** + * Convert page to an array. + * + * @return array + */ + public function toArray() + { + return [ + 'header' => (array)$this->header(), + 'content' => (string)$this->value('content') + ]; + } + + /** + * Convert page to YAML encoded string. + * + * @return string + */ + public function toYaml() + { + return Yaml::dump($this->toArray(), 20); + } + + /** + * Convert page to JSON encoded string. + * + * @return string + */ + public function toJson() + { + return json_encode($this->toArray()); + } + + /** + * Gets and sets the associated media as found in the page folder. + * + * @param Media $var Representation of associated media. + * + * @return Media Representation of associated media. + */ + public function media($var = null) + { + /** @var Cache $cache */ + $cache = Grav::instance()['cache']; + + if ($var) { + $this->media = $var; + } + if ($this->media === null) { + // Use cached media if possible. + $media_cache_id = md5('media' . $this->id()); + if (!$media = $cache->fetch($media_cache_id)) { + $media = new Media($this->path()); + $cache->save($media_cache_id, $media); + } + $this->media = $media; + } + + return $this->media; + } + + /** + * Gets and sets the name field. If no name field is set, it will return 'default.md'. + * + * @param string $var The name of this page. + * + * @return string The name of this page. + */ + public function name($var = null) + { + if ($var !== null) { + $this->name = $var; + } + + return empty($this->name) ? 'default.md' : $this->name; + } + + /** + * Returns child page type. + * + * @return string + */ + public function childType() + { + return isset($this->header->child_type) ? (string)$this->header->child_type : ''; + } + + /** + * Gets and sets the template field. This is used to find the correct Twig template file to render. + * If no field is set, it will return the name without the .md extension + * + * @param string $var the template name + * + * @return string the template name + */ + public function template($var = null) + { + if ($var !== null) { + $this->template = $var; + } + if (empty($this->template)) { + $this->template = ($this->modular() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name()); + } + + return $this->template; + } + + /** + * Allows a page to override the output render format, usually the extension provided + * in the URL. (e.g. `html`, `json`, `xml`, etc). + * + * @param null $var + * + * @return null + */ + public function templateFormat($var = null) + { + if ($var !== null) { + $this->template_format = $var; + } + + if (empty($this->template_format)) { + $this->template_format = Grav::instance()['uri']->extension('html'); + } + + return $this->template_format; + } + + /** + * Gets and sets the extension field. + * + * @param null $var + * + * @return null|string + */ + public function extension($var = null) + { + if ($var !== null) { + $this->extension = $var; + } + if (empty($this->extension)) { + $this->extension = '.' . pathinfo($this->name(), PATHINFO_EXTENSION); + } + + return $this->extension; + } + + /** + * Returns the page extension, got from the page `url_extension` config and falls back to the + * system config `system.pages.append_url_extension`. + * + * @return string The extension of this page. For example `.html` + */ + public function urlExtension() + { + if ($this->home()) { + return ''; + } + + // if not set in the page get the value from system config + if (empty($this->url_extension)) { + $this->url_extension = trim(isset($this->header->append_url_extension) ? $this->header->append_url_extension : Grav::instance()['config']->get('system.pages.append_url_extension', + false)); + } + + return $this->url_extension; + } + + /** + * Gets and sets the expires field. If not set will return the default + * + * @param int $var The new expires value. + * + * @return int The expires value + */ + public function expires($var = null) + { + if ($var !== null) { + $this->expires = $var; + } + + return !isset($this->expires) ? Grav::instance()['config']->get('system.pages.expires') : $this->expires; + } + + /** + * Gets and sets the cache-control property. If not set it will return the default value (null) + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control for more details on valid options + * + * @param null $var + * @return null + */ + public function cacheControl($var = null) + { + if ($var !== null) { + $this->cache_control = $var; + } + + return !isset($this->cache_control) ? Grav::instance()['config']->get('system.pages.cache_control') : $this->cache_control; + } + + /** + * Gets and sets the title for this Page. If no title is set, it will use the slug() to get a name + * + * @param string $var the title of the Page + * + * @return string the title of the Page + */ + public function title($var = null) + { + if ($var !== null) { + $this->title = $var; + } + if (empty($this->title)) { + $this->title = ucfirst($this->slug()); + } + + return $this->title; + } + + /** + * Gets and sets the menu name for this Page. This is the text that can be used specifically for navigation. + * If no menu field is set, it will use the title() + * + * @param string $var the menu field for the page + * + * @return string the menu field for the page + */ + public function menu($var = null) + { + if ($var !== null) { + $this->menu = $var; + } + if (empty($this->menu)) { + $this->menu = $this->title(); + } + + return $this->menu; + } + + /** + * Gets and Sets whether or not this Page is visible for navigation + * + * @param bool $var true if the page is visible + * + * @return bool true if the page is visible + */ + public function visible($var = null) + { + if ($var !== null) { + $this->visible = (bool)$var; + } + + if ($this->visible === null) { + // Set item visibility in menu if folder is different from slug + // eg folder = 01.Home and slug = Home + if (preg_match(PAGE_ORDER_PREFIX_REGEX, $this->folder)) { + $this->visible = true; + } else { + $this->visible = false; + } + } + + return $this->visible; + } + + /** + * Gets and Sets whether or not this Page is considered published + * + * @param bool $var true if the page is published + * + * @return bool true if the page is published + */ + public function published($var = null) + { + if ($var !== null) { + $this->published = (bool)$var; + } + + // If not published, should not be visible in menus either + if ($this->published === false) { + $this->visible = false; + } + + return $this->published; + } + + /** + * Gets and Sets the Page publish date + * + * @param string $var string representation of a date + * + * @return int unix timestamp representation of the date + */ + public function publishDate($var = null) + { + if ($var !== null) { + $this->publish_date = Utils::date2timestamp($var, $this->dateformat); + } + + return $this->publish_date; + } + + /** + * Gets and Sets the Page unpublish date + * + * @param string $var string representation of a date + * + * @return int|null unix timestamp representation of the date + */ + public function unpublishDate($var = null) + { + if ($var !== null) { + $this->unpublish_date = Utils::date2timestamp($var, $this->dateformat); + } + + return $this->unpublish_date; + } + + /** + * Gets and Sets whether or not this Page is routable, ie you can reach it + * via a URL. + * The page must be *routable* and *published* + * + * @param bool $var true if the page is routable + * + * @return bool true if the page is routable + */ + public function routable($var = null) + { + if ($var !== null) { + $this->routable = (bool)$var; + } + + return $this->routable && $this->published(); + } + + public function ssl($var = null) + { + if ($var !== null) { + $this->ssl = (bool)$var; + } + + return $this->ssl; + } + + /** + * Gets and Sets the process setup for this Page. This is multi-dimensional array that consists of + * a simple array of arrays with the form array("markdown"=>true) for example + * + * @param array $var an Array of name value pairs where the name is the process and value is true or false + * + * @return array an Array of name value pairs where the name is the process and value is true or false + */ + public function process($var = null) + { + if ($var !== null) { + $this->process = (array)$var; + } + + return $this->process; + } + + /** + * Returns the state of the debugger override etting for this page + * + * @return mixed + */ + public function debugger() + { + if (isset($this->debugger) && $this->debugger === false) { + return false; + } + + return true; + } + + /** + * Function to merge page metadata tags and build an array of Metadata objects + * that can then be rendered in the page. + * + * @param array $var an Array of metadata values to set + * + * @return array an Array of metadata values for the page + */ + public function metadata($var = null) + { + if ($var !== null) { + $this->metadata = (array)$var; + } + + // if not metadata yet, process it. + if (null === $this->metadata) { + $header_tag_http_equivs = ['content-type', 'default-style', 'refresh', 'x-ua-compatible']; + + $this->metadata = []; + + $metadata = []; + // Set the Generator tag + $metadata['generator'] = 'GravCMS'; + + // Get initial metadata for the page + $metadata = array_merge($metadata, Grav::instance()['config']->get('site.metadata')); + + if (isset($this->header->metadata)) { + // Merge any site.metadata settings in with page metadata + $metadata = array_merge($metadata, $this->header->metadata); + } + + // Build an array of meta objects.. + foreach ((array)$metadata as $key => $value) { + // Lowercase the key + $key = strtolower($key); + // If this is a property type metadata: "og", "twitter", "facebook" etc + // Backward compatibility for nested arrays in metas + if (is_array($value)) { + foreach ($value as $property => $prop_value) { + $prop_key = $key . ':' . $property; + $this->metadata[$prop_key] = [ + 'name' => $prop_key, + 'property' => $prop_key, + 'content' => htmlspecialchars($prop_value, ENT_QUOTES, 'UTF-8') + ]; + } + } else { + // If it this is a standard meta data type + if ($value) { + if (in_array($key, $header_tag_http_equivs)) { + $this->metadata[$key] = [ + 'http_equiv' => $key, + 'content' => htmlspecialchars($value, ENT_QUOTES, 'UTF-8') + ]; + } elseif ($key === 'charset') { + $this->metadata[$key] = ['charset' => htmlspecialchars($value, ENT_QUOTES, 'UTF-8')]; + } else { + // if it's a social metadata with separator, render as property + $separator = strpos($key, ':'); + $hasSeparator = $separator && $separator < strlen($key) - 1; + $entry = [ + 'content' => htmlspecialchars($value, ENT_QUOTES, 'UTF-8') + ]; + + if ($hasSeparator && !Utils::startsWith($key, 'twitter')) { + $entry['property'] = $key; + } else { + $entry['name'] = $key; + } + + $this->metadata[$key] = $entry; + } + } + } + } + } + + return $this->metadata; + } + + /** + * Gets and Sets the slug for the Page. The slug is used in the URL routing. If not set it uses + * the parent folder from the path + * + * @param string $var the slug, e.g. 'my-blog' + * + * @return string the slug + */ + public function slug($var = null) + { + if ($var !== null && $var !== '') { + $this->slug = $var; + } + + if (empty($this->slug)) { + $this->slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder)); + } + + + return $this->slug; + } + + /** + * Get/set order number of this page. + * + * @param int $var + * + * @return int|bool + */ + public function order($var = null) + { + if ($var !== null) { + $order = !empty($var) ? sprintf('%02d.', (int)$var) : ''; + $this->folder($order . preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder)); + + return $order; + } + + preg_match(PAGE_ORDER_PREFIX_REGEX, $this->folder, $order); + + return isset($order[0]) ? $order[0] : false; + } + + /** + * Gets the URL for a page - alias of url(). + * + * @param bool $include_host + * + * @return string the permalink + */ + public function link($include_host = false) + { + return $this->url($include_host); + } + + /** + * Gets the URL with host information, aka Permalink. + * @return string The permalink. + */ + public function permalink() + { + return $this->url(true, false, true, true); + } + + /** + * Returns the canonical URL for a page + * + * @param bool $include_lang + * + * @return string + */ + public function canonical($include_lang = true) + { + return $this->url(true, true, $include_lang); + } + + /** + * Gets the url for the Page. + * + * @param bool $include_host Defaults false, but true would include http://yourhost.com + * @param bool $canonical true to return the canonical URL + * @param bool $include_lang + * @param bool $raw_route + * + * @return string The url. + */ + public function url($include_host = false, $canonical = false, $include_lang = true, $raw_route = false) + { + $grav = Grav::instance(); + + /** @var Pages $pages */ + $pages = $grav['pages']; + + /** @var Config $config */ + $config = $grav['config']; + + /** @var Language $language */ + $language = $grav['language']; + + /** @var Uri $uri */ + $uri = $grav['uri']; + + // Override any URL when external_url is set + if (isset($this->external_url)) { + return $this->external_url; + } + + // get pre-route + if ($include_lang && $language->enabled()) { + $pre_route = $language->getLanguageURLPrefix(); + } else { + $pre_route = ''; + } + + // add full route if configured to do so + if ($config->get('system.absolute_urls', false)) { + $include_host = true; + } + + // get canonical route if requested + if ($canonical) { + $route = $pre_route . $this->routeCanonical(); + } elseif ($raw_route) { + $route = $pre_route . $this->rawRoute(); + } else { + $route = $pre_route . $this->route(); + } + + $rootUrl = $uri->rootUrl($include_host) . $pages->base(); + + $url = $rootUrl . '/' . trim($route, '/') . $this->urlExtension(); + + // trim trailing / if not root + if ($url !== '/') { + $url = rtrim($url, '/'); + } + + return Uri::filterPath($url); + } + + /** + * Gets the route for the page based on the route headers if available, else from + * the parents route and the current Page's slug. + * + * @param string $var Set new default route. + * + * @return string The route for the Page. + */ + public function route($var = null) + { + if ($var !== null) { + $this->route = $var; + } + + if (empty($this->route)) { + $baseRoute = null; + + // calculate route based on parent slugs + $parent = $this->parent(); + if (isset($parent)) { + if ($this->hide_home_route && $parent->route() === $this->home_route) { + $baseRoute = ''; + } else { + $baseRoute = (string)$parent->route(); + } + } + + $this->route = isset($baseRoute) ? $baseRoute . '/' . $this->slug() : null; + + if (!empty($this->routes) && isset($this->routes['default'])) { + $this->routes['aliases'][] = $this->route; + $this->route = $this->routes['default']; + + return $this->route; + } + } + + return $this->route; + } + + /** + * Helper method to clear the route out so it regenerates next time you use it + */ + public function unsetRouteSlug() + { + unset($this->route); + unset($this->slug); + } + + /** + * Gets and Sets the page raw route + * + * @param null $var + * + * @return null|string + */ + public function rawRoute($var = null) + { + if ($var !== null) { + $this->raw_route = $var; + } + + if (empty($this->raw_route)) { + $baseRoute = $this->parent ? (string)$this->parent()->rawRoute() : null; + + $slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder)); + + $this->raw_route = isset($baseRoute) ? $baseRoute . '/' . $slug : null; + } + + return $this->raw_route; + } + + /** + * Gets the route aliases for the page based on page headers. + * + * @param array $var list of route aliases + * + * @return array The route aliases for the Page. + */ + public function routeAliases($var = null) + { + if ($var !== null) { + $this->routes['aliases'] = (array)$var; + } + + if (!empty($this->routes) && isset($this->routes['aliases'])) { + return $this->routes['aliases']; + } + + return []; + } + + /** + * Gets the canonical route for this page if its set. If provided it will use + * that value, else if it's `true` it will use the default route. + * + * @param null $var + * + * @return bool|string + */ + public function routeCanonical($var = null) + { + if ($var !== null) { + $this->routes['canonical'] = (array)$var; + } + + if (!empty($this->routes) && isset($this->routes['canonical'])) { + return $this->routes['canonical']; + } + + return $this->route(); + } + + /** + * Gets and sets the identifier for this Page object. + * + * @param string $var the identifier + * + * @return string the identifier + */ + public function id($var = null) + { + if ($var !== null) { + // store unique per language + $active_lang = Grav::instance()['language']->getLanguage() ?: ''; + $id = $active_lang . $var; + $this->id = $id; + } + + return $this->id; + } + + /** + * Gets and sets the modified timestamp. + * + * @param int $var modified unix timestamp + * + * @return int modified unix timestamp + */ + public function modified($var = null) + { + if ($var !== null) { + $this->modified = $var; + } + + return $this->modified; + } + + /** + * Gets the redirect set in the header. + * + * @param string $var redirect url + * + * @return string + */ + public function redirect($var = null) + { + if ($var !== null) { + $this->redirect = $var; + } + + return $this->redirect; + } + + /** + * Gets and sets the option to show the etag header for the page. + * + * @param boolean $var show etag header + * + * @return boolean show etag header + */ + public function eTag($var = null) + { + if ($var !== null) { + $this->etag = $var; + } + if (!isset($this->etag)) { + $this->etag = (bool)Grav::instance()['config']->get('system.pages.etag'); + } + + return $this->etag; + } + + /** + * Gets and sets the option to show the last_modified header for the page. + * + * @param boolean $var show last_modified header + * + * @return boolean show last_modified header + */ + public function lastModified($var = null) + { + if ($var !== null) { + $this->last_modified = $var; + } + if (!isset($this->last_modified)) { + $this->last_modified = (bool)Grav::instance()['config']->get('system.pages.last_modified'); + } + + return $this->last_modified; + } + + /** + * Gets and sets the path to the .md file for this Page object. + * + * @param string $var the file path + * + * @return string|null the file path + */ + public function filePath($var = null) + { + if ($var !== null) { + // Filename of the page. + $this->name = basename($var); + // Folder of the page. + $this->folder = basename(dirname($var)); + // Path to the page. + $this->path = dirname(dirname($var)); + } + + return $this->path . '/' . $this->folder . '/' . ($this->name ?: ''); + } + + /** + * Gets the relative path to the .md file + * + * @return string The relative file path + */ + public function filePathClean() + { + $path = str_replace(ROOT_DIR, '', $this->filePath()); + + return $path; + } + + /** + * Returns the clean path to the page file + */ + public function relativePagePath() + { + $path = str_replace('/' . $this->name(), '', $this->filePathClean()); + + return $path; + } + + /** + * Gets and sets the path to the folder where the .md for this Page object resides. + * This is equivalent to the filePath but without the filename. + * + * @param string $var the path + * + * @return string|null the path + */ + public function path($var = null) + { + if ($var !== null) { + // Folder of the page. + $this->folder = basename($var); + // Path to the page. + $this->path = dirname($var); + } + + return $this->path ? $this->path . '/' . $this->folder : null; + } + + /** + * Get/set the folder. + * + * @param string $var Optional path + * + * @return string|null + */ + public function folder($var = null) + { + if ($var !== null) { + $this->folder = $var; + } + + return $this->folder; + } + + /** + * Gets and sets the date for this Page object. This is typically passed in via the page headers + * + * @param string $var string representation of a date + * + * @return int unix timestamp representation of the date + */ + public function date($var = null) + { + if ($var !== null) { + $this->date = Utils::date2timestamp($var, $this->dateformat); + } + + if (!$this->date) { + $this->date = $this->modified; + } + + return $this->date; + } + + /** + * Gets and sets the date format for this Page object. This is typically passed in via the page headers + * using typical PHP date string structure - http://php.net/manual/en/function.date.php + * + * @param string $var string representation of a date format + * + * @return string string representation of a date format + */ + public function dateformat($var = null) + { + if ($var !== null) { + $this->dateformat = $var; + } + + return $this->dateformat; + } + + /** + * Gets and sets the order by which any sub-pages should be sorted. + * + * @param string $var the order, either "asc" or "desc" + * + * @return string the order, either "asc" or "desc" + */ + public function orderDir($var = null) + { + if ($var !== null) { + $this->order_dir = $var; + } + if (empty($this->order_dir)) { + $this->order_dir = 'asc'; + } + + return $this->order_dir; + } + + /** + * Gets and sets the order by which the sub-pages should be sorted. + * + * default - is the order based on the file system, ie 01.Home before 02.Advark + * title - is the order based on the title set in the pages + * date - is the order based on the date set in the pages + * folder - is the order based on the name of the folder with any numerics omitted + * + * @param string $var supported options include "default", "title", "date", and "folder" + * + * @return string supported options include "default", "title", "date", and "folder" + */ + public function orderBy($var = null) + { + if ($var !== null) { + $this->order_by = $var; + } + + return $this->order_by; + } + + /** + * Gets the manual order set in the header. + * + * @param string $var supported options include "default", "title", "date", and "folder" + * + * @return array + */ + public function orderManual($var = null) + { + if ($var !== null) { + $this->order_manual = $var; + } + + return (array)$this->order_manual; + } + + /** + * Gets and sets the maxCount field which describes how many sub-pages should be displayed if the + * sub_pages header property is set for this page object. + * + * @param int $var the maximum number of sub-pages + * + * @return int the maximum number of sub-pages + */ + public function maxCount($var = null) + { + if ($var !== null) { + $this->max_count = (int)$var; + } + if (empty($this->max_count)) { + /** @var Config $config */ + $config = Grav::instance()['config']; + $this->max_count = (int)$config->get('system.pages.list.count'); + } + + return $this->max_count; + } + + /** + * Gets and sets the taxonomy array which defines which taxonomies this page identifies itself with. + * + * @param array $var an array of taxonomies + * + * @return array an array of taxonomies + */ + public function taxonomy($var = null) + { + if ($var !== null) { + $this->taxonomy = $var; + } + + return $this->taxonomy; + } + + /** + * Gets and sets the modular var that helps identify this page is a modular child + * + * @param bool $var true if modular_twig + * + * @return bool true if modular_twig + */ + public function modular($var = null) + { + return $this->modularTwig($var); + } + + /** + * Gets and sets the modular_twig var that helps identify this page as a modular child page that will need + * twig processing handled differently from a regular page. + * + * @param bool $var true if modular_twig + * + * @return bool true if modular_twig + */ + public function modularTwig($var = null) + { + if ($var !== null) { + $this->modular_twig = (bool)$var; + if ($var) { + $this->visible(false); + // some routable logic + if (empty($this->header->routable)) { + $this->routable = false; + } + } + } + + return $this->modular_twig; + } + + /** + * Gets the configured state of the processing method. + * + * @param string $process the process, eg "twig" or "markdown" + * + * @return bool whether or not the processing method is enabled for this Page + */ + public function shouldProcess($process) + { + return isset($this->process[$process]) ? (bool)$this->process[$process] : false; + } + + /** + * Gets and Sets the parent object for this page + * + * @param Page $var the parent page object + * + * @return Page|null the parent page object if it exists. + */ + public function parent(Page $var = null) + { + if ($var) { + $this->parent = $var->path(); + + return $var; + } + + /** @var Pages $pages */ + $pages = Grav::instance()['pages']; + + return $pages->get($this->parent); + } + + /** + * Gets the top parent object for this page + * + * @return Page|null the top parent page object if it exists. + */ + public function topParent() + { + $topParent = $this->parent(); + + if (!$topParent) { + return null; + } + + while (true) { + $theParent = $topParent->parent(); + if ($theParent !== null && $theParent->parent() !== null) { + $topParent = $theParent; + } else { + break; + } + } + + return $topParent; + } + + /** + * Returns children of this page. + * + * @return \Grav\Common\Page\Collection + */ + public function children() + { + /** @var Pages $pages */ + $pages = Grav::instance()['pages']; + + return $pages->children($this->path()); + } + + + /** + * Check to see if this item is the first in an array of sub-pages. + * + * @return boolean True if item is first. + */ + public function isFirst() + { + $collection = $this->parent()->collection('content', false); + if ($collection instanceof Collection) { + return $collection->isFirst($this->path()); + } + + return true; + } + + /** + * Check to see if this item is the last in an array of sub-pages. + * + * @return boolean True if item is last + */ + public function isLast() + { + $collection = $this->parent()->collection('content', false); + if ($collection instanceof Collection) { + return $collection->isLast($this->path()); + } + + return true; + } + + /** + * Gets the previous sibling based on current position. + * + * @return Page the previous Page item + */ + public function prevSibling() + { + return $this->adjacentSibling(-1); + } + + /** + * Gets the next sibling based on current position. + * + * @return Page the next Page item + */ + public function nextSibling() + { + return $this->adjacentSibling(1); + } + + /** + * Returns the adjacent sibling based on a direction. + * + * @param integer $direction either -1 or +1 + * + * @return Page|bool the sibling page + */ + public function adjacentSibling($direction = 1) + { + $collection = $this->parent()->collection('content', false); + if ($collection instanceof Collection) { + return $collection->adjacentSibling($this->path(), $direction); + } + + return false; + } + + /** + * Returns the item in the current position. + * + * @param string $path the path the item + * + * @return Integer the index of the current page. + */ + public function currentPosition() + { + $collection = $this->parent()->collection('content', false); + if ($collection instanceof Collection) { + return $collection->currentPosition($this->path()); + } + + return true; + } + + /** + * Returns whether or not this page is the currently active page requested via the URL. + * + * @return bool True if it is active + */ + public function active() + { + $uri_path = rtrim(urldecode(Grav::instance()['uri']->path()), '/') ?: '/'; + $routes = Grav::instance()['pages']->routes(); + + if (isset($routes[$uri_path])) { + if ($routes[$uri_path] === $this->path()) { + return true; + } + + } + + return false; + } + + /** + * Returns whether or not this URI's URL contains the URL of the active page. + * Or in other words, is this page's URL in the current URL + * + * @return bool True if active child exists + */ + public function activeChild() + { + $uri = Grav::instance()['uri']; + $pages = Grav::instance()['pages']; + $uri_path = rtrim(urldecode($uri->path()), '/'); + $routes = Grav::instance()['pages']->routes(); + + if (isset($routes[$uri_path])) { + /** @var Page $child_page */ + $child_page = $pages->dispatch($uri->route())->parent(); + if ($child_page) { + while (!$child_page->root()) { + if ($this->path() === $child_page->path()) { + return true; + } + $child_page = $child_page->parent(); + } + } + } + + return false; + } + + /** + * Returns whether or not this page is the currently configured home page. + * + * @return bool True if it is the homepage + */ + public function home() + { + $home = Grav::instance()['config']->get('system.home.alias'); + $is_home = ($this->route() === $home || $this->rawRoute() === $home); + + return $is_home; + } + + /** + * Returns whether or not this page is the root node of the pages tree. + * + * @return bool True if it is the root + */ + public function root() + { + if (!$this->parent && !$this->name && !$this->visible) { + return true; + } + + return false; + } + + /** + * Helper method to return an ancestor page. + * + * @param string $url The url of the page + * @param bool $lookup Name of the parent folder + * + * @return \Grav\Common\Page\Page page you were looking for if it exists + */ + public function ancestor($lookup = null) + { + /** @var Pages $pages */ + $pages = Grav::instance()['pages']; + + return $pages->ancestor($this->route, $lookup); + } + + /** + * Helper method to return an ancestor page to inherit from. The current + * page object is returned. + * + * @param string $field Name of the parent folder + * + * @return Page + */ + public function inherited($field) + { + list($inherited, $currentParams) = $this->getInheritedParams($field); + + $this->modifyHeader($field, $currentParams); + + return $inherited; + } + + /** + * Helper method to return an ancestor field only to inherit from. The + * first occurrence of an ancestor field will be returned if at all. + * + * @param string $field Name of the parent folder + * + * @return array + */ + public function inheritedField($field) + { + list($inherited, $currentParams) = $this->getInheritedParams($field); + + return $currentParams; + } + + /** + * Method that contains shared logic for inherited() and inheritedField() + * + * @param string $field Name of the parent folder + * + * @return array + */ + protected function getInheritedParams($field) + { + $pages = Grav::instance()['pages']; + + /** @var Pages $pages */ + $inherited = $pages->inherited($this->route, $field); + $inheritedParams = (array)$inherited->value('header.' . $field); + $currentParams = (array)$this->value('header.' . $field); + if ($inheritedParams && is_array($inheritedParams)) { + $currentParams = array_replace_recursive($inheritedParams, $currentParams); + } + + return [$inherited, $currentParams]; + } + + /** + * Helper method to return a page. + * + * @param string $url the url of the page + * @param bool $all + * + * @return \Grav\Common\Page\Page page you were looking for if it exists + */ + public function find($url, $all = false) + { + /** @var Pages $pages */ + $pages = Grav::instance()['pages']; + + return $pages->find($url, $all); + } + + /** + * Get a collection of pages in the current context. + * + * @param string|array $params + * @param boolean $pagination + * + * @return Collection + * @throws \InvalidArgumentException + */ + public function collection($params = 'content', $pagination = true) + { + if (is_string($params)) { + $params = (array)$this->value('header.' . $params); + } elseif (!is_array($params)) { + throw new \InvalidArgumentException('Argument should be either header variable name or array of parameters'); + } + + if (!isset($params['items'])) { + return new Collection(); + } + + // See if require published filter is set and use that, if assume published=true + $only_published = true; + if (isset($params['filter']['published']) && $params['filter']['published']) { + $only_published = false; + } elseif (isset($params['filter']['non-published']) && $params['filter']['non-published']) { + $only_published = false; + } + + $collection = $this->evaluate($params['items'], $only_published); + if (!$collection instanceof Collection) { + $collection = new Collection(); + } + $collection->setParams($params); + + /** @var Uri $uri */ + $uri = Grav::instance()['uri']; + /** @var Config $config */ + $config = Grav::instance()['config']; + + $process_taxonomy = isset($params['url_taxonomy_filters']) ? $params['url_taxonomy_filters'] : $config->get('system.pages.url_taxonomy_filters'); + + if ($process_taxonomy) { + foreach ((array)$config->get('site.taxonomies') as $taxonomy) { + if ($uri->param(rawurlencode($taxonomy))) { + $items = explode(',', $uri->param($taxonomy)); + $collection->setParams(['taxonomies' => [$taxonomy => $items]]); + + foreach ($collection as $page) { + // Don't filter modular pages + if ($page->modular()) { + continue; + } + foreach ($items as $item) { + $item = rawurldecode($item); + if (empty($page->taxonomy[$taxonomy]) || !in_array(htmlspecialchars_decode($item, + ENT_QUOTES), $page->taxonomy[$taxonomy]) + ) { + $collection->remove($page->path()); + } + } + } + } + } + } + + // If a filter or filters are set, filter the collection... + if (isset($params['filter'])) { + + // remove any inclusive sets from filer: + $sets = ['published', 'visible', 'modular', 'routable']; + foreach ($sets as $type) { + if (isset($params['filter'][$type]) && isset($params['filter']['non-'.$type])) { + if ($params['filter'][$type] && $params['filter']['non-'.$type]) { + unset ($params['filter'][$type]); + unset ($params['filter']['non-'.$type]); + } + + } + } + + foreach ((array)$params['filter'] as $type => $filter) { + switch ($type) { + case 'published': + if ((bool) $filter) { + $collection->published(); + } + break; + case 'non-published': + if ((bool) $filter) { + $collection->nonPublished(); + } + break; + case 'visible': + if ((bool) $filter) { + $collection->visible(); + } + break; + case 'non-visible': + if ((bool) $filter) { + $collection->nonVisible(); + } + break; + case 'modular': + if ((bool) $filter) { + $collection->modular(); + } + break; + case 'non-modular': + if ((bool) $filter) { + $collection->nonModular(); + } + break; + case 'routable': + if ((bool) $filter) { + $collection->routable(); + } + break; + case 'non-routable': + if ((bool) $filter) { + $collection->nonRoutable(); + } + break; + case 'type': + $collection->ofType($filter); + break; + case 'types': + $collection->ofOneOfTheseTypes($filter); + break; + case 'access': + $collection->ofOneOfTheseAccessLevels($filter); + break; + } + } + } + + if (isset($params['dateRange'])) { + $start = isset($params['dateRange']['start']) ? $params['dateRange']['start'] : 0; + $end = isset($params['dateRange']['end']) ? $params['dateRange']['end'] : false; + $field = isset($params['dateRange']['field']) ? $params['dateRange']['field'] : false; + $collection->dateRange($start, $end, $field); + } + + if (isset($params['order'])) { + $by = isset($params['order']['by']) ? $params['order']['by'] : 'default'; + $dir = isset($params['order']['dir']) ? $params['order']['dir'] : 'asc'; + $custom = isset($params['order']['custom']) ? $params['order']['custom'] : null; + $sort_flags = isset($params['order']['sort_flags']) ? $params['order']['sort_flags'] : null; + + if (is_array($sort_flags)) { + $sort_flags = array_map('constant', $sort_flags); //transform strings to constant value + $sort_flags = array_reduce($sort_flags, function ($a, $b) { + return $a | $b; + }, 0); //merge constant values using bit or + } + + $collection->order($by, $dir, $custom, $sort_flags); + } + + /** @var Grav $grav */ + $grav = Grav::instance()['grav']; + + // New Custom event to handle things like pagination. + $grav->fireEvent('onCollectionProcessed', new Event(['collection' => $collection])); + + // Slice and dice the collection if pagination is required + if ($pagination) { + $params = $collection->params(); + + $limit = isset($params['limit']) ? $params['limit'] : 0; + $start = !empty($params['pagination']) ? ($uri->currentPage() - 1) * $limit : 0; + + if ($limit && $collection->count() > $limit) { + $collection->slice($start, $limit); + } + } + + return $collection; + } + + /** + * @param string|array $value + * @param bool $only_published + * @return mixed + * @internal + */ + public function evaluate($value, $only_published = true) + { + // Parse command. + if (is_string($value)) { + // Format: @command.param + $cmd = $value; + $params = []; + } elseif (is_array($value) && count($value) == 1 && !is_int(key($value))) { + // Format: @command.param: { attr1: value1, attr2: value2 } + $cmd = (string)key($value); + $params = (array)current($value); + } else { + $result = []; + foreach ((array)$value as $key => $val) { + if (is_int($key)) { + $result = $result + $this->evaluate($val)->toArray(); + } else { + $result = $result + $this->evaluate([$key => $val])->toArray(); + } + + } + + return new Collection($result); + } + + /** @var Pages $pages */ + $pages = Grav::instance()['pages']; + + $parts = explode('.', $cmd); + $current = array_shift($parts); + + /** @var Collection $results */ + $results = new Collection(); + + switch ($current) { + case 'self@': + case '@self': + if (!empty($parts)) { + switch ($parts[0]) { + case 'modular': + // @self.modular: false (alternative to @self.children) + if (!empty($params) && $params[0] === false) { + $results = $this->children()->nonModular(); + break; + } + $results = $this->children()->modular(); + break; + case 'children': + $results = $this->children()->nonModular(); + break; + case 'all': + $results = $this->children(); + break; + case 'parent': + $collection = new Collection(); + $results = $collection->addPage($this->parent()); + break; + case 'siblings': + if (!$this->parent()) { + return new Collection(); + } + $results = $this->parent()->children()->remove($this->path()); + break; + case 'descendants': + $results = $pages->all($this)->remove($this->path())->nonModular(); + break; + } + } + + + break; + + case 'page@': + case '@page': + $page = null; + + if (!empty($params)) { + $page = $this->find($params[0]); + } + + // safety check in case page is not found + if (!isset($page)) { + return $results; + } + + // Handle a @page.descendants + if (!empty($parts)) { + switch ($parts[0]) { + case 'modular': + $results = new Collection(); + foreach ($page->children() as $child) { + $results = $results->addPage($child); + } + $results->modular(); + break; + case 'page': + case 'self': + $results = new Collection(); + $results = $results->addPage($page)->nonModular(); + break; + + case 'descendants': + $results = $pages->all($page)->remove($page->path())->nonModular(); + break; + + case 'children': + $results = $page->children()->nonModular(); + break; + } + } else { + $results = $page->children()->nonModular(); + } + + break; + + case 'root@': + case '@root': + if (!empty($parts) && $parts[0] === 'descendants') { + $results = $pages->all($pages->root())->nonModular(); + } else { + $results = $pages->root()->children()->nonModular(); + } + break; + + case 'taxonomy@': + case '@taxonomy': + // Gets a collection of pages by using one of the following formats: + // @taxonomy.category: blog + // @taxonomy.category: [ blog, featured ] + // @taxonomy: { category: [ blog, featured ], level: 1 } + + /** @var Taxonomy $taxonomy_map */ + $taxonomy_map = Grav::instance()['taxonomy']; + + if (!empty($parts)) { + $params = [implode('.', $parts) => $params]; + } + $results = $taxonomy_map->findTaxonomy($params); + break; + } + + if ($only_published) { + $results = $results->published(); + } + + return $results; + } + + /** + * Returns whether or not this Page object has a .md file associated with it or if its just a directory. + * + * @return bool True if its a page with a .md file associated + */ + public function isPage() + { + if ($this->name) { + return true; + } + + return false; + } + + /** + * Returns whether or not this Page object is a directory or a page. + * + * @return bool True if its a directory + */ + public function isDir() + { + return !$this->isPage(); + } + + /** + * Returns whether the page exists in the filesystem. + * + * @return bool + */ + public function exists() + { + $file = $this->file(); + + return $file && $file->exists(); + } + + /** + * Returns whether or not the current folder exists + * + * @return bool + */ + public function folderExists() + { + return file_exists($this->path()); + } + + /** + * Cleans the path. + * + * @param string $path the path + * + * @return string the path + */ + protected function cleanPath($path) + { + $lastchunk = strrchr($path, DS); + if (strpos($lastchunk, ':') !== false) { + $path = str_replace($lastchunk, '', $path); + } + + return $path; + } + + /** + * Reorders all siblings according to a defined order + * + * @param $new_order + */ + protected function doReorder($new_order) + { + if (!$this->_original) { + return; + } + + $pages = Grav::instance()['pages']; + $pages->init(); + + $this->_original->path($this->path()); + + $siblings = $this->parent()->children(); + $siblings->order('slug', 'asc', $new_order); + + $counter = 0; + + // Reorder all moved pages. + foreach ($siblings as $slug => $page) { + $order = (int)trim($page->order(), '.'); + $counter++; + + if ($order) { + if ($page->path() === $this->path() && $this->folderExists()) { + // Handle current page; we do want to change ordering number, but nothing else. + $this->order($counter); + $this->save(false); + } else { + // Handle all the other pages. + $page = $pages->get($page->path()); + if ($page && $page->folderExists() && !$page->_action) { + $page = $page->move($this->parent()); + $page->order($counter); + $page->save(false); + } + } + } + } + } + + /** + * Moves or copies the page in filesystem. + * + * @internal + * + * @throws Exception + */ + protected function doRelocation() + { + if (!$this->_original) { + return; + } + + if (is_dir($this->_original->path())) { + if ($this->_action === 'move') { + Folder::move($this->_original->path(), $this->path()); + } elseif ($this->_action === 'copy') { + Folder::copy($this->_original->path(), $this->path()); + } + } + + if ($this->name() !== $this->_original->name()) { + $path = $this->path(); + if (is_file($path . '/' . $this->_original->name())) { + rename($path . '/' . $this->_original->name(), $path . '/' . $this->name()); + } + } + + } + + protected function setPublishState() + { + // Handle publishing dates if no explicit published option set + if (Grav::instance()['config']->get('system.pages.publish_dates') && !isset($this->header->published)) { + // unpublish if required, if not clear cache right before page should be unpublished + if ($this->unpublishDate()) { + if ($this->unpublishDate() < time()) { + $this->published(false); + } else { + $this->published(); + Grav::instance()['cache']->setLifeTime($this->unpublishDate()); + } + } + // publish if required, if not clear cache right before page is published + if ($this->publishDate() && $this->publishDate() > time()) { + $this->published(false); + Grav::instance()['cache']->setLifeTime($this->publishDate()); + } + } + } + + protected function adjustRouteCase($route) + { + $case_insensitive = Grav::instance()['config']->get('system.force_lowercase_urls'); + + if ($case_insensitive) { + return mb_strtolower($route); + } else { + return $route; + } + } +} diff --git a/system/src/Grav/Common/Page/Pages.php b/system/src/Grav/Common/Page/Pages.php new file mode 100644 index 0000000..2ff049d --- /dev/null +++ b/system/src/Grav/Common/Page/Pages.php @@ -0,0 +1,1342 @@ +grav = $c; + } + + /** + * Get or set base path for the pages. + * + * @param string $path + * + * @return string + */ + public function base($path = null) + { + if ($path !== null) { + $path = trim($path, '/'); + $this->base = $path ? '/' . $path : null; + $this->baseUrl = []; + } + + return $this->base; + } + + /** + * + * Get base URL for Grav pages. + * + * @param string $lang Optional language code for multilingual links. + * @param bool $absolute If true, return absolute url, if false, return relative url. Otherwise return default. + * + * @return string + */ + public function baseUrl($lang = null, $absolute = null) + { + $lang = (string) $lang; + $type = $absolute === null ? 'base_url' : ($absolute ? 'base_url_absolute' : 'base_url_relative'); + $key = "{$lang} {$type}"; + + if (!isset($this->baseUrl[$key])) { + /** @var Config $config */ + $config = $this->grav['config']; + + /** @var Language $language */ + $language = $this->grav['language']; + + if (!$lang) { + $lang = $language->getActive(); + } + + $path_append = rtrim($this->grav['pages']->base(), '/'); + if ($language->getDefault() !== $lang || $config->get('system.languages.include_default_lang') === true) { + $path_append .= $lang ? '/' . $lang : ''; + } + + $this->baseUrl[$key] = $this->grav[$type] . $path_append; + } + + return $this->baseUrl[$key]; + } + + /** + * + * Get home URL for Grav site. + * + * @param string $lang Optional language code for multilingual links. + * @param bool $absolute If true, return absolute url, if false, return relative url. Otherwise return default. + * + * @return string + */ + public function homeUrl($lang = null, $absolute = null) + { + return $this->baseUrl($lang, $absolute) ?: '/'; + } + + /** + * + * Get home URL for Grav site. + * + * @param string $route Optional route to the page. + * @param string $lang Optional language code for multilingual links. + * @param bool $absolute If true, return absolute url, if false, return relative url. Otherwise return default. + * + * @return string + */ + public function url($route = '/', $lang = null, $absolute = null) + { + if ($route === '/') { + return $this->homeUrl($lang, $absolute); + } + + return $this->baseUrl($lang, $absolute) . Uri::filterPath($route); + } + + /** + * Class initialization. Must be called before using this class. + */ + public function init() + { + $config = $this->grav['config']; + $this->ignore_files = $config->get('system.pages.ignore_files'); + $this->ignore_folders = $config->get('system.pages.ignore_folders'); + $this->ignore_hidden = $config->get('system.pages.ignore_hidden'); + + $this->instances = []; + $this->children = []; + $this->routes = []; + + $this->buildPages(); + } + + /** + * Get or set last modification time. + * + * @param int $modified + * + * @return int|null + */ + public function lastModified($modified = null) + { + if ($modified && $modified > $this->last_modified) { + $this->last_modified = $modified; + } + + return $this->last_modified; + } + + /** + * Returns a list of all pages. + * + * @return array|Page[] + */ + public function instances() + { + return $this->instances; + } + + /** + * Returns a list of all routes. + * + * @return array + */ + public function routes() + { + return $this->routes; + } + + /** + * Adds a page and assigns a route to it. + * + * @param Page $page Page to be added. + * @param string $route Optional route (uses route from the object if not set). + */ + public function addPage(Page $page, $route = null) + { + if (!isset($this->instances[$page->path()])) { + $this->instances[$page->path()] = $page; + } + $route = $page->route($route); + if ($page->parent()) { + $this->children[$page->parent()->path()][$page->path()] = ['slug' => $page->slug()]; + } + $this->routes[$route] = $page->path(); + + $this->grav->fireEvent('onPageProcessed', new Event(['page' => $page])); + } + + /** + * Sort sub-pages in a page. + * + * @param Page $page + * @param string $order_by + * @param string $order_dir + * + * @return array + */ + public function sort(Page $page, $order_by = null, $order_dir = null, $sort_flags = null) + { + if ($order_by === null) { + $order_by = $page->orderBy(); + } + if ($order_dir === null) { + $order_dir = $page->orderDir(); + } + + $path = $page->path(); + $children = isset($this->children[$path]) ? $this->children[$path] : []; + + if (!$children) { + return $children; + } + + if (!isset($this->sort[$path][$order_by])) { + $this->buildSort($path, $children, $order_by, $page->orderManual(), $sort_flags); + } + + $sort = $this->sort[$path][$order_by]; + + if ($order_dir !== 'asc') { + $sort = array_reverse($sort); + } + + return $sort; + } + + /** + * @param Collection $collection + * @param $orderBy + * @param string $orderDir + * @param null $orderManual + * + * @return array + * @internal + */ + public function sortCollection(Collection $collection, $orderBy, $orderDir = 'asc', $orderManual = null, $sort_flags = null) + { + $items = $collection->toArray(); + if (!$items) { + return []; + } + + $lookup = md5(json_encode($items) . json_encode($orderManual) . $orderBy . $orderDir); + if (!isset($this->sort[$lookup][$orderBy])) { + $this->buildSort($lookup, $items, $orderBy, $orderManual, $sort_flags); + } + + $sort = $this->sort[$lookup][$orderBy]; + + if ($orderDir !== 'asc') { + $sort = array_reverse($sort); + } + + return $sort; + + } + + /** + * Get a page instance. + * + * @param string $path The filesystem full path of the page + * + * @return Page + * @throws \Exception + */ + public function get($path) + { + return isset($this->instances[(string)$path]) ? $this->instances[(string)$path] : null; + } + + /** + * Get children of the path. + * + * @param string $path + * + * @return Collection + */ + public function children($path) + { + $children = isset($this->children[(string)$path]) ? $this->children[(string)$path] : []; + + return new Collection($children, [], $this); + } + + /** + * Get a page ancestor. + * + * @param string $route The relative URL of the page + * @param string $path The relative path of the ancestor folder + * + * @return Page|null + */ + public function ancestor($route, $path = null) + { + if ($path !== null) { + $page = $this->dispatch($route, true); + + if ($page && $page->path() === $path) { + return $page; + } + if ($page && !$page->parent()->root()) { + return $this->ancestor($page->parent()->route(), $path); + } + } + + return null; + } + + /** + * Get a page ancestor trait. + * + * @param string $route The relative route of the page + * @param string $field The field name of the ancestor to query for + * + * @return Page|null + */ + public function inherited($route, $field = null) + { + if ($field !== null) { + + $page = $this->dispatch($route, true); + + if ($page && $page->parent()->value('header.' . $field) !== null) { + return $page->parent(); + } + if ($page && !$page->parent()->root()) { + return $this->inherited($page->parent()->route(), $field); + } + } + + return null; + } + + /** + * alias method to return find a page. + * + * @param string $route The relative URL of the page + * @param bool $all + * + * @return Page|null + */ + public function find($route, $all = false) + { + return $this->dispatch($route, $all, false); + } + + /** + * Dispatch URI to a page. + * + * @param string $route The relative URL of the page + * @param bool $all + * + * @param bool $redirect + * @return Page|null + * @throws \Exception + */ + public function dispatch($route, $all = false, $redirect = true) + { + $route = urldecode($route); + + // Fetch page if there's a defined route to it. + $page = isset($this->routes[$route]) ? $this->get($this->routes[$route]) : null; + // Try without trailing slash + if (!$page && Utils::endsWith($route, '/')) { + $page = isset($this->routes[rtrim($route, '/')]) ? $this->get($this->routes[rtrim($route, '/')]) : null; + } + + // Are we in the admin? this is important! + $not_admin = !isset($this->grav['admin']); + + // If the page cannot be reached, look into site wide redirects, routes + wildcards + if (!$all && $not_admin) { + + // If the page is a simple redirect, just do it. + if ($redirect && $page && $page->redirect()) { + $this->grav->redirectLangSafe($page->redirect()); + } + + // fall back and check site based redirects + if (!$page || ($page && !$page->routable())) { + /** @var Config $config */ + $config = $this->grav['config']; + + // See if route matches one in the site configuration + $site_route = $config->get("site.routes.{$route}"); + if ($site_route) { + $page = $this->dispatch($site_route, $all); + } else { + + /** @var Uri $uri */ + $uri = $this->grav['uri']; + /** @var \Grav\Framework\Uri\Uri $source_url */ + $source_url = $uri->uri(false); + + // Try Regex style redirects + $site_redirects = $config->get("site.redirects"); + if (is_array($site_redirects)) { + foreach ((array)$site_redirects as $pattern => $replace) { + $pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#'; + try { + $found = preg_replace($pattern, $replace, $source_url); + if ($found != $source_url) { + $this->grav->redirectLangSafe($found); + } + } catch (ErrorException $e) { + $this->grav['log']->error('site.redirects: ' . $pattern . '-> ' . $e->getMessage()); + } + } + } + + // Try Regex style routes + $site_routes = $config->get("site.routes"); + if (is_array($site_routes)) { + foreach ((array)$site_routes as $pattern => $replace) { + $pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#'; + try { + $found = preg_replace($pattern, $replace, $source_url); + if ($found !== $source_url) { + $page = $this->dispatch($found, $all); + } + } catch (ErrorException $e) { + $this->grav['log']->error('site.routes: ' . $pattern . '-> ' . $e->getMessage()); + } + } + } + } + } + } + + return $page; + } + + /** + * Get root page. + * + * @return Page + */ + public function root() + { + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + return $this->instances[rtrim($locator->findResource('page://'), DS)]; + } + + /** + * Get a blueprint for a page type. + * + * @param string $type + * + * @return Blueprint + */ + public function blueprints($type) + { + if ($this->blueprints === null) { + $this->blueprints = new Blueprints(self::getTypes()); + } + + try { + $blueprint = $this->blueprints->get($type); + } catch (\RuntimeException $e) { + $blueprint = $this->blueprints->get('default'); + } + + if (empty($blueprint->initialized)) { + $this->grav->fireEvent('onBlueprintCreated', new Event(['blueprint' => $blueprint, 'type' => $type])); + $blueprint->initialized = true; + } + + return $blueprint; + } + + /** + * Get all pages + * + * @param \Grav\Common\Page\Page $current + * + * @return \Grav\Common\Page\Collection + */ + public function all(Page $current = null) + { + $all = new Collection(); + + /** @var Page $current */ + $current = $current ?: $this->root(); + + if (!$current->root()) { + $all[$current->path()] = ['slug' => $current->slug()]; + } + + foreach ($current->children() as $next) { + $all->append($this->all($next)); + } + + return $all; + } + + /** + * Get available parents raw routes. + * + * @return array + */ + public static function parentsRawRoutes() + { + $rawRoutes = true; + + return self::getParents($rawRoutes); + } + + /** + * Get available parents routes + * + * @param bool $rawRoutes get the raw route or the normal route + * + * @return array + */ + private static function getParents($rawRoutes) + { + $grav = Grav::instance(); + + /** @var Pages $pages */ + $pages = $grav['pages']; + + $parents = $pages->getList(null, 0, $rawRoutes); + + if (isset($grav['admin'])) { + // Remove current route from parents + + /** @var Admin $admin */ + $admin = $grav['admin']; + + $page = $admin->getPage($admin->route); + $page_route = $page->route(); + if (isset($parents[$page_route])) { + unset($parents[$page_route]); + } + + } + + return $parents; + } + + /** + * Get list of route/title of all pages. + * + * @param Page $current + * @param int $level + * @param bool $rawRoutes + * + * @param bool $showAll + * @param bool $showFullpath + * @param bool $showSlug + * @param bool $showModular + * @param bool $limitLevels + * @return array + */ + public function getList(Page $current = null, $level = 0, $rawRoutes = false, $showAll = true, $showFullpath = false, $showSlug = false, $showModular = false, $limitLevels = false) + { + if (!$current) { + if ($level) { + throw new \RuntimeException('Internal error'); + } + + $current = $this->root(); + } + + $list = []; + + if (!$current->root()) { + if ($rawRoutes) { + $route = $current->rawRoute(); + } else { + $route = $current->route(); + } + + if ($showFullpath) { + $option = $current->route(); + } else { + $extra = $showSlug ? '(' . $current->slug() . ') ' : ''; + $option = str_repeat('—-', $level). '▸ ' . $extra . $current->title(); + + + } + + $list[$route] = $option; + + + } + + if ($limitLevels === false || ($level+1 < $limitLevels)) { + foreach ($current->children() as $next) { + if ($showAll || $next->routable() || ($next->modular() && $showModular)) { + $list = array_merge($list, $this->getList($next, $level + 1, $rawRoutes, $showAll, $showFullpath, $showSlug, $showModular, $limitLevels)); + } + } + } + + return $list; + } + + /** + * Get available page types. + * + * @return Types + */ + public static function getTypes() + { + if (!self::$types) { + + $grav = Grav::instance(); + + $scanBlueprintsAndTemplates = function () use ($grav) { + // Scan blueprints + $event = new Event(); + $event->types = self::$types; + $grav->fireEvent('onGetPageBlueprints', $event); + + self::$types->scanBlueprints('theme://blueprints/'); + + // Scan templates + $event = new Event(); + $event->types = self::$types; + $grav->fireEvent('onGetPageTemplates', $event); + + self::$types->scanTemplates('theme://templates/'); + }; + + if ($grav['config']->get('system.cache.enabled')) { + /** @var Cache $cache */ + $cache = $grav['cache']; + + // Use cached types if possible. + $types_cache_id = md5('types'); + self::$types = $cache->fetch($types_cache_id); + + if (!self::$types) { + self::$types = new Types(); + $scanBlueprintsAndTemplates(); + $cache->save($types_cache_id, self::$types); + } + + } else { + self::$types = new Types(); + $scanBlueprintsAndTemplates(); + } + + } + + return self::$types; + } + + /** + * Get available page types. + * + * @return array + */ + public static function types() + { + $types = self::getTypes(); + + return $types->pageSelect(); + } + + /** + * Get available page types. + * + * @return array + */ + public static function modularTypes() + { + $types = self::getTypes(); + + return $types->modularSelect(); + } + + /** + * Get template types based on page type (standard or modular) + * + * @return array + */ + public static function pageTypes() + { + if (isset(Grav::instance()['admin'])) { + /** @var Admin $admin */ + $admin = Grav::instance()['admin']; + + /** @var Page $page */ + $page = $admin->getPage($admin->route); + + if ($page && $page->modular()) { + return static::modularTypes(); + } + + return static::types(); + } + + return []; + } + + /** + * Get access levels of the site pages + * + * @return array + */ + public function accessLevels() + { + $accessLevels = []; + foreach ($this->all() as $page) { + if (isset($page->header()->access)) { + if (is_array($page->header()->access)) { + foreach ($page->header()->access as $index => $accessLevel) { + if (is_array($accessLevel)) { + foreach ($accessLevel as $innerIndex => $innerAccessLevel) { + array_push($accessLevels, $innerIndex); + } + } else { + array_push($accessLevels, $index); + } + } + } else { + + array_push($accessLevels, $page->header()->access); + } + } + } + + return array_unique($accessLevels); + } + + /** + * Get available parents routes + * + * @return array + */ + public static function parents() + { + $rawRoutes = false; + + return self::getParents($rawRoutes); + } + + + + /** + * Gets the home route + * + * @return string + */ + public static function getHomeRoute() + { + if (empty(self::$home_route)) { + $grav = Grav::instance(); + + /** @var Config $config */ + $config = $grav['config']; + + /** @var Language $language */ + $language = $grav['language']; + + $home = $config->get('system.home.alias'); + + if ($language->enabled()) { + $home_aliases = $config->get('system.home.aliases'); + if ($home_aliases) { + $active = $language->getActive(); + $default = $language->getDefault(); + + try { + if ($active) { + $home = $home_aliases[$active]; + } else { + $home = $home_aliases[$default]; + } + } catch (ErrorException $e) { + $home = $home_aliases[$default]; + } + + } + } + + self::$home_route = trim($home, '/'); + } + + return self::$home_route; + } + + /** + * Needed for testing where we change the home route via config + */ + public static function resetHomeRoute() + { + self::$home_route = null; + return self::getHomeRoute(); + } + + /** + * Builds pages. + * + * @internal + */ + protected function buildPages() + { + $this->sort = []; + + /** @var Config $config */ + $config = $this->grav['config']; + + /** @var Language $language */ + $language = $this->grav['language']; + + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + + $pages_dir = $locator->findResource('page://'); + + if ($config->get('system.cache.enabled')) { + /** @var Cache $cache */ + $cache = $this->grav['cache']; + /** @var Taxonomy $taxonomy */ + $taxonomy = $this->grav['taxonomy']; + + // how should we check for last modified? Default is by file + switch (strtolower($config->get('system.cache.check.method', 'file'))) { + case 'none': + case 'off': + $hash = 0; + break; + case 'folder': + $hash = Folder::lastModifiedFolder($pages_dir); + break; + case 'hash': + $hash = Folder::hashAllFiles($pages_dir); + break; + default: + $hash = Folder::lastModifiedFile($pages_dir); + } + + $this->pages_cache_id = md5($pages_dir . $hash . $language->getActive() . $config->checksum()); + + list($this->instances, $this->routes, $this->children, $taxonomy_map, $this->sort) = $cache->fetch($this->pages_cache_id); + if (!$this->instances) { + $this->grav['debugger']->addMessage('Page cache missed, rebuilding pages..'); + + // recurse pages and cache result + $this->resetPages($pages_dir, $this->pages_cache_id); + + } else { + // If pages was found in cache, set the taxonomy + $this->grav['debugger']->addMessage('Page cache hit.'); + $taxonomy->taxonomy($taxonomy_map); + } + } else { + $this->recurse($pages_dir); + $this->buildRoutes(); + } + } + + /** + * Accessible method to manually reset the pages cache + * + * @param $pages_dir + */ + public function resetPages($pages_dir) + { + $this->recurse($pages_dir); + $this->buildRoutes(); + + // cache if needed + if ($this->grav['config']->get('system.cache.enabled')) { + /** @var Cache $cache */ + $cache = $this->grav['cache']; + /** @var Taxonomy $taxonomy */ + $taxonomy = $this->grav['taxonomy']; + + // save pages, routes, taxonomy, and sort to cache + $cache->save($this->pages_cache_id, [$this->instances, $this->routes, $this->children, $taxonomy->taxonomy(), $this->sort]); + } + } + + /** + * Recursive function to load & build page relationships. + * + * @param string $directory + * @param Page|null $parent + * + * @return Page + * @throws \RuntimeException + * @internal + */ + protected function recurse($directory, Page $parent = null) + { + $directory = rtrim($directory, DS); + $page = new Page; + + /** @var Config $config */ + $config = $this->grav['config']; + + /** @var Language $language */ + $language = $this->grav['language']; + + // stuff to do at root page + if ($parent === null) { + + // Fire event for memory and time consuming plugins... + if ($config->get('system.pages.events.page')) { + $this->grav->fireEvent('onBuildPagesInitialized'); + } + } + + $page->path($directory); + if ($parent) { + $page->parent($parent); + } + + $page->orderDir($config->get('system.pages.order.dir')); + $page->orderBy($config->get('system.pages.order.by')); + + // Add into instances + if (!isset($this->instances[$page->path()])) { + $this->instances[$page->path()] = $page; + if ($parent && $page->path()) { + $this->children[$parent->path()][$page->path()] = ['slug' => $page->slug()]; + } + } else { + throw new \RuntimeException('Fatal error when creating page instances.'); + } + + $content_exists = false; + $pages_found = new \GlobIterator($directory . '/*' . CONTENT_EXT); + $page_found = null; + + $page_extension = ''; + + if ($pages_found && count($pages_found) > 0) { + + $page_extensions = $language->getFallbackPageExtensions(); + + foreach ($page_extensions as $extension) { + foreach ($pages_found as $found) { + if ($found->isDir()) { + continue; + } + $regex = '/^[^\.]*' . preg_quote($extension, '/') . '$/'; + if (preg_match($regex, $found->getFilename())) { + $page_found = $found; + $page_extension = $extension; + break 2; + } + } + } + } + + if ($parent && !empty($page_found)) { + $page->init($page_found, $page_extension); + + $content_exists = true; + + if ($config->get('system.pages.events.page')) { + $this->grav->fireEvent('onPageProcessed', new Event(['page' => $page])); + } + } + + // set current modified of page + $last_modified = $page->modified(); + + $iterator = new \FilesystemIterator($directory); + + /** @var \DirectoryIterator $file */ + foreach ($iterator as $file) { + $name = $file->getFilename(); + + // Ignore all hidden files if set. + if ($this->ignore_hidden && $name && $name[0] === '.') { + continue; + } + + if ($file->isFile()) { + // Update the last modified if it's newer than already found + if (!in_array($file->getBasename(), $this->ignore_files) && ($modified = $file->getMTime()) > $last_modified) { + $last_modified = $modified; + } + } elseif ($file->isDir() && !in_array($file->getFilename(), $this->ignore_folders)) { + + // if folder contains separator, continue + if (Utils::contains($file->getFilename(), $config->get('system.param_sep', ':'))) { + continue; + } + + if (!$page->path()) { + $page->path($file->getPath()); + } + + $path = $directory . DS . $name; + $child = $this->recurse($path, $page); + + if (Utils::startsWith($name, '_')) { + $child->routable(false); + } + + $this->children[$page->path()][$child->path()] = ['slug' => $child->slug()]; + + if ($config->get('system.pages.events.page')) { + $this->grav->fireEvent('onFolderProcessed', new Event(['page' => $page])); + } + } + } + + // Set routability to false if no page found + if (!$content_exists) { + $page->routable(false); + } + + // Override the modified time if modular + if ($page->template() === 'modular') { + foreach ($page->collection() as $child) { + $modified = $child->modified(); + + if ($modified > $last_modified) { + $last_modified = $modified; + } + } + } + + // Override the modified and ID so that it takes the latest change into account + $page->modified($last_modified); + $page->id($last_modified . md5($page->filePath())); + + // Sort based on Defaults or Page Overridden sort order + $this->children[$page->path()] = $this->sort($page); + + return $page; + } + + /** + * @internal + */ + protected function buildRoutes() + { + /** @var $taxonomy Taxonomy */ + $taxonomy = $this->grav['taxonomy']; + + // Get the home route + $home = self::resetHomeRoute(); + + // Build routes and taxonomy map. + /** @var $page Page */ + foreach ($this->instances as $page) { + if (!$page->root()) { + // process taxonomy + $taxonomy->addTaxonomy($page); + + $route = $page->route(); + $raw_route = $page->rawRoute(); + $page_path = $page->path(); + + // add regular route + $this->routes[$route] = $page_path; + + // add raw route + if ($raw_route != $route) { + $this->routes[$raw_route] = $page_path; + } + + // add canonical route + $route_canonical = $page->routeCanonical(); + if ($route_canonical && ($route !== $route_canonical)) { + $this->routes[$route_canonical] = $page_path; + } + + // add aliases to routes list if they are provided + $route_aliases = $page->routeAliases(); + if ($route_aliases) { + foreach ($route_aliases as $alias) { + $this->routes[$alias] = $page_path; + } + } + } + } + + // Alias and set default route to home page. + if ($home && isset($this->routes['/' . $home])) { + $this->routes['/'] = $this->routes['/' . $home]; + $this->get($this->routes['/' . $home])->route('/'); + } + } + + /** + * @param string $path + * @param array $pages + * @param string $order_by + * @param array $manual + * @param int $sort_flags + * + * @throws \RuntimeException + * @internal + */ + protected function buildSort($path, array $pages, $order_by = 'default', $manual = null, $sort_flags = null) + { + $list = []; + $header_default = null; + $header_query = null; + + // do this header query work only once + if (strpos($order_by, 'header.') === 0) { + $header_query = explode('|', str_replace('header.', '', $order_by)); + if (isset($header_query[1])) { + $header_default = $header_query[1]; + } + } + + foreach ($pages as $key => $info) { + $child = isset($this->instances[$key]) ? $this->instances[$key] : null; + if (!$child) { + throw new \RuntimeException("Page does not exist: {$key}"); + } + + switch ($order_by) { + case 'title': + $list[$key] = $child->title(); + break; + case 'date': + $list[$key] = $child->date(); + $sort_flags = SORT_REGULAR; + break; + case 'modified': + $list[$key] = $child->modified(); + $sort_flags = SORT_REGULAR; + break; + case 'publish_date': + $list[$key] = $child->publishDate(); + $sort_flags = SORT_REGULAR; + break; + case 'unpublish_date': + $list[$key] = $child->unpublishDate(); + $sort_flags = SORT_REGULAR; + break; + case 'slug': + $list[$key] = $child->slug(); + break; + case 'basename': + $list[$key] = basename($key); + break; + case 'folder': + $list[$key] = $child->folder(); + break; + case (is_string($header_query[0])): + $child_header = new Header((array)$child->header()); + $header_value = $child_header->get($header_query[0]); + if (is_array($header_value)) { + $list[$key] = implode(',',$header_value); + } elseif ($header_value) { + $list[$key] = $header_value; + } else { + $list[$key] = $header_default ?: $key; + } + $sort_flags = $sort_flags ?: SORT_REGULAR; + break; + case 'manual': + case 'default': + default: + $list[$key] = $key; + $sort_flags = $sort_flags ?: SORT_REGULAR; + } + } + + if (!$sort_flags) { + $sort_flags = SORT_NATURAL | SORT_FLAG_CASE; + } + + // handle special case when order_by is random + if ($order_by === 'random') { + $list = $this->arrayShuffle($list); + } else { + // else just sort the list according to specified key + if (extension_loaded('intl') && $this->grav['config']->get('system.intl_enabled')) { + $locale = setlocale(LC_COLLATE, 0); //`setlocale` with a 0 param returns the current locale set + $col = Collator::create($locale); + if ($col) { + if (($sort_flags & SORT_NATURAL) === SORT_NATURAL) { + $list = preg_replace_callback('~([0-9]+)\.~', function($number) { + return sprintf('%032d.', $number[0]); + }, $list); + + $list_vals = array_values($list); + if (is_numeric(array_shift($list_vals))) { + $sort_flags = Collator::SORT_REGULAR; + } else { + $sort_flags = Collator::SORT_STRING; + } + } + + $col->asort($list, $sort_flags); + } else { + asort($list, $sort_flags); + } + } else { + asort($list, $sort_flags); + } + } + + + // Move manually ordered items into the beginning of the list. Order of the unlisted items does not change. + if (is_array($manual) && !empty($manual)) { + $new_list = []; + $i = count($manual); + + foreach ($list as $key => $dummy) { + $info = $pages[$key]; + $order = array_search($info['slug'], $manual); + if ($order === false) { + $order = $i++; + } + $new_list[$key] = (int)$order; + } + + $list = $new_list; + + // Apply manual ordering to the list. + asort($list); + } + + foreach ($list as $key => $sort) { + $info = $pages[$key]; + $this->sort[$path][$order_by][$key] = $info; + } + } + + /** + * Shuffles an associative array + * + * @param array $list + * + * @return array + */ + protected function arrayShuffle($list) + { + $keys = array_keys($list); + shuffle($keys); + + $new = []; + foreach ($keys as $key) { + $new[$key] = $list[$key]; + } + + return $new; + } + + /** + * Get the Pages cache ID + * + * this is particularly useful to know if pages have changed and you want + * to sync another cache with pages cache - works best in `onPagesInitialized()` + * + * @return mixed + */ + public function getPagesCacheId() + { + return $this->pages_cache_id; + } +} diff --git a/system/src/Grav/Common/Page/Types.php b/system/src/Grav/Common/Page/Types.php new file mode 100644 index 0000000..436d4f8 --- /dev/null +++ b/system/src/Grav/Common/Page/Types.php @@ -0,0 +1,140 @@ +items[$type])) { + $this->items[$type] = []; + } elseif (!$blueprint) { + return; + } + + if (!$blueprint && $this->systemBlueprints) { + $blueprint = isset($this->systemBlueprints[$type]) ? $this->systemBlueprints[$type] : $this->systemBlueprints['default']; + } + + if ($blueprint) { + array_unshift($this->items[$type], $blueprint); + } + } + + public function scanBlueprints($uri) + { + if (!is_string($uri)) { + throw new \InvalidArgumentException('First parameter must be URI'); + } + + if (!$this->systemBlueprints) { + $this->systemBlueprints = $this->findBlueprints('blueprints://pages'); + + // Register default by default. + $this->register('default'); + + $this->register('external'); + } + + foreach ($this->findBlueprints($uri) as $type => $blueprint) { + $this->register($type, $blueprint); + } + } + + public function scanTemplates($uri) + { + if (!is_string($uri)) { + throw new \InvalidArgumentException('First parameter must be URI'); + } + + $options = [ + 'compare' => 'Filename', + 'pattern' => '|\.html\.twig$|', + 'filters' => [ + 'value' => '|\.html\.twig$|' + ], + 'value' => 'Filename', + 'recursive' => false + ]; + + foreach (Folder::all($uri, $options) as $type) { + $this->register($type); + } + + $modular_uri = rtrim($uri, '/') . '/modular'; + if (is_dir($modular_uri)) { + foreach (Folder::all($modular_uri, $options) as $type) { + $this->register('modular/' . $type); + } + } + } + + public function pageSelect() + { + $list = []; + foreach ($this->items as $name => $file) { + if (strpos($name, '/')) { + continue; + } + $list[$name] = ucfirst(strtr($name, '_', ' ')); + } + ksort($list); + return $list; + } + + public function modularSelect() + { + $list = []; + foreach ($this->items as $name => $file) { + if (strpos($name, 'modular/') !== 0) { + continue; + } + $list[$name] = trim(ucfirst(strtr(basename($name), '_', ' '))); + } + ksort($list); + return $list; + } + + private function findBlueprints($uri) + { + $options = [ + 'compare' => 'Filename', + 'pattern' => '|\.yaml$|', + 'filters' => [ + 'key' => '|\.yaml$|' + ], + 'key' => 'SubPathName', + 'value' => 'PathName', + ]; + + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + if ($locator->isStream($uri)) { + $options['value'] = 'Url'; + } + + $list = Folder::all($uri, $options); + + return $list; + } +} diff --git a/system/src/Grav/Common/Plugin.php b/system/src/Grav/Common/Plugin.php new file mode 100644 index 0000000..ec5b346 --- /dev/null +++ b/system/src/Grav/Common/Plugin.php @@ -0,0 +1,362 @@ +name = $name; + $this->grav = $grav; + if ($config) { + $this->setConfig($config); + } + } + + /** + * @param Config $config + * @return $this + */ + public function setConfig(Config $config) + { + $this->config = $config; + + return $this; + } + + /** + * Get configuration of the plugin. + * + * @return array + */ + public function config() + { + return $this->config["plugins.{$this->name}"]; + } + + /** + * Determine if this is running under the admin + * + * @return bool + */ + public function isAdmin() + { + return Utils::isAdminPlugin(); + } + + /** + * Determine if this route is in Admin and active for the plugin + * + * @param $plugin_route + * @return bool + */ + protected function isPluginActiveAdmin($plugin_route) + { + $should_run = false; + + $uri = $this->grav['uri']; + + if (strpos($uri->path(), $this->config->get('plugins.admin.route') . '/' . $plugin_route) === false) { + $should_run = false; + } elseif (isset($uri->paths()[1]) && $uri->paths()[1] === $plugin_route) { + $should_run = true; + } + + return $should_run; + } + + /** + * @param array $events + */ + protected function enable(array $events) + { + /** @var EventDispatcher $dispatcher */ + $dispatcher = $this->grav['events']; + + foreach ($events as $eventName => $params) { + if (is_string($params)) { + $dispatcher->addListener($eventName, [$this, $params]); + } elseif (is_string($params[0])) { + $dispatcher->addListener($eventName, [$this, $params[0]], isset($params[1]) ? $params[1] : 0); + } else { + foreach ($params as $listener) { + $dispatcher->addListener($eventName, [$this, $listener[0]], isset($listener[1]) ? $listener[1] : 0); + } + } + } + } + + /** + * @param array $events + */ + protected function disable(array $events) + { + /** @var EventDispatcher $dispatcher */ + $dispatcher = $this->grav['events']; + + foreach ($events as $eventName => $params) { + if (is_string($params)) { + $dispatcher->removeListener($eventName, [$this, $params]); + } elseif (is_string($params[0])) { + $dispatcher->removeListener($eventName, [$this, $params[0]]); + } else { + foreach ($params as $listener) { + $dispatcher->removeListener($eventName, [$this, $listener[0]]); + } + } + } + } + + /** + * Whether or not an offset exists. + * + * @param mixed $offset An offset to check for. + * @return bool Returns TRUE on success or FALSE on failure. + */ + public function offsetExists($offset) + { + $this->loadBlueprint(); + + if ($offset === 'title') { + $offset = 'name'; + } + return isset($this->blueprint[$offset]); + } + + /** + * Returns the value at specified offset. + * + * @param mixed $offset The offset to retrieve. + * @return mixed Can return all value types. + */ + public function offsetGet($offset) + { + $this->loadBlueprint(); + + if ($offset === 'title') { + $offset = 'name'; + } + return isset($this->blueprint[$offset]) ? $this->blueprint[$offset] : null; + } + + /** + * Assigns a value to the specified offset. + * + * @param mixed $offset The offset to assign the value to. + * @param mixed $value The value to set. + * @throws LogicException + */ + public function offsetSet($offset, $value) + { + throw new LogicException(__CLASS__ . ' blueprints cannot be modified.'); + } + + /** + * Unsets an offset. + * + * @param mixed $offset The offset to unset. + * @throws LogicException + */ + public function offsetUnset($offset) + { + throw new LogicException(__CLASS__ . ' blueprints cannot be modified.'); + } + + /** + * This function will search a string for markdown links in a specific format. The link value can be + * optionally compared against via the $internal_regex and operated on by the callback $function + * provided. + * + * format: [plugin:myplugin_name](function_data) + * + * @param string $content The string to perform operations upon + * @param callable $function The anonymous callback function + * @param string $internal_regex Optional internal regex to extra data from + * + * @return string + */ + protected function parseLinks($content, $function, $internal_regex = '(.*)') + { + $regex = '/\[plugin:(?:' . $this->name . ')\]\(' . $internal_regex . '\)/i'; + + return preg_replace_callback($regex, $function, $content); + } + + /** + * Merge global and page configurations. + * + * @param Page $page The page to merge the configurations with the + * plugin settings. + * @param mixed $deep false = shallow|true = recursive|merge = recursive+unique + * @param array $params Array of additional configuration options to + * merge with the plugin settings. + * @param string $type Is this 'plugins' or 'themes' + * + * @return Data + */ + protected function mergeConfig(Page $page, $deep = false, $params = [], $type = 'plugins') + { + $class_name = $this->name; + $class_name_merged = $class_name . '.merged'; + $defaults = $this->config->get($type . '.' . $class_name, []); + $page_header = $page->header(); + $header = []; + + if (!isset($page_header->$class_name_merged) && isset($page_header->$class_name)) { + // Get default plugin configurations and retrieve page header configuration + $config = $page_header->$class_name; + if (is_bool($config)) { + // Overwrite enabled option with boolean value in page header + $config = ['enabled' => $config]; + } + // Merge page header settings using deep or shallow merging technique + $header = $this->mergeArrays($deep, $defaults, $config); + + // Create new config object and set it on the page object so it's cached for next time + $page->modifyHeader($class_name_merged, new Data($header)); + } else if (isset($page_header->$class_name_merged)) { + $merged = $page_header->$class_name_merged; + $header = $merged->toArray(); + } + if (empty($header)) { + $header = $defaults; + } + // Merge additional parameter with configuration options + $header = $this->mergeArrays($deep, $header, $params); + + // Return configurations as a new data config class + return new Data($header); + } + + /** + * Merge arrays based on deepness + * + * @param bool $deep + * @param $array1 + * @param $array2 + * @return array|mixed + */ + private function mergeArrays($deep = false, $array1, $array2) + { + if ($deep === 'merge') { + return Utils::arrayMergeRecursiveUnique($array1, $array2); + } + if ($deep === true) { + return array_replace_recursive($array1, $array2); + } + + return array_merge($array1, $array2); + } + + /** + * Persists to disk the plugin parameters currently stored in the Grav Config object + * + * @param string $plugin_name The name of the plugin whose config it should store. + * + * @return true + */ + public static function saveConfig($plugin_name) + { + if (!$plugin_name) { + return false; + } + + $grav = Grav::instance(); + $locator = $grav['locator']; + $filename = 'config://plugins/' . $plugin_name . '.yaml'; + $file = YamlFile::instance($locator->findResource($filename, true, true)); + $content = $grav['config']->get('plugins.' . $plugin_name); + $file->save($content); + $file->free(); + + return true; + } + + /** + * Simpler getter for the plugin blueprint + * + * @return mixed + */ + public function getBlueprint() + { + if (!$this->blueprint) { + $this->loadBlueprint(); + } + return $this->blueprint; + } + + /** + * Load blueprints. + */ + protected function loadBlueprint() + { + if (!$this->blueprint) { + $grav = Grav::instance(); + $plugins = $grav['plugins']; + $this->blueprint = $plugins->get($this->name)->blueprints(); + } + } +} diff --git a/system/src/Grav/Common/Plugins.php b/system/src/Grav/Common/Plugins.php new file mode 100644 index 0000000..5e407a9 --- /dev/null +++ b/system/src/Grav/Common/Plugins.php @@ -0,0 +1,207 @@ +getIterator('plugins://'); + + $plugins = []; + foreach($iterator as $directory) { + if (!$directory->isDir()) { + continue; + } + $plugins[] = $directory->getBasename(); + } + + natsort($plugins); + + foreach ($plugins as $plugin) { + $this->add($this->loadPlugin($plugin)); + } + } + + /** + * @return $this + */ + public function setup() + { + $blueprints = []; + $formFields = []; + + /** @var Plugin $plugin */ + foreach ($this->items as $plugin) { + if (isset($plugin->features['blueprints'])) { + $blueprints["plugin://{$plugin->name}/blueprints"] = $plugin->features['blueprints']; + } + if (method_exists($plugin, 'getFormFieldTypes')) { + $formFields[get_class($plugin)] = isset($plugin->features['formfields']) ? $plugin->features['formfields'] : 0; + } + } + + if ($blueprints) { + // Order by priority. + arsort($blueprints); + + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + $locator->addPath('blueprints', '', array_keys($blueprints), 'system/blueprints'); + } + + if ($formFields) { + // Order by priority. + arsort($formFields); + + $list = []; + foreach ($formFields as $className => $priority) { + $plugin = $this->items[$className]; + $list += $plugin->getFormFieldTypes(); + } + + $this->formFieldTypes = $list; + } + + return $this; + } + + /** + * Registers all plugins. + * + * @return array|Plugin[] array of Plugin objects + * @throws \RuntimeException + */ + public function init() + { + $grav = Grav::instance(); + + /** @var Config $config */ + $config = $grav['config']; + + /** @var EventDispatcher $events */ + $events = $grav['events']; + + foreach ($this->items as $instance) { + // Register only enabled plugins. + if ($config["plugins.{$instance->name}.enabled"] && $instance instanceof Plugin) { + $instance->setConfig($config); + $events->addSubscriber($instance); + } + } + + return $this->items; + } + + /** + * Add a plugin + * + * @param $plugin + */ + public function add($plugin) + { + if (is_object($plugin)) { + $this->items[get_class($plugin)] = $plugin; + } + } + + /** + * Return list of all plugin data with their blueprints. + * + * @return array + */ + public static function all() + { + $plugins = Grav::instance()['plugins']; + $list = []; + + foreach ($plugins as $instance) { + $name = $instance->name; + $result = self::get($name); + + if ($result) { + $list[$name] = $result; + } + } + + return $list; + } + + /** + * Get a plugin by name + * + * @param string $name + * + * @return Data|null + */ + public static function get($name) + { + $blueprints = new Blueprints('plugins://'); + $blueprint = $blueprints->get("{$name}/blueprints"); + + // Load default configuration. + $file = CompiledYamlFile::instance("plugins://{$name}/{$name}" . YAML_EXT); + + // ensure this is a valid plugin + if (!$file->exists()) { + return null; + } + + $obj = new Data($file->content(), $blueprint); + + // Override with user configuration. + $obj->merge(Grav::instance()['config']->get('plugins.' . $name) ?: []); + + // Save configuration always to user/config. + $file = CompiledYamlFile::instance("config://plugins/{$name}.yaml"); + $obj->file($file); + + return $obj; + } + + protected function loadPlugin($name) + { + $grav = Grav::instance(); + $locator = $grav['locator']; + + $filePath = $locator->findResource('plugins://' . $name . DS . $name . PLUGIN_EXT); + if (!is_file($filePath)) { + $grav['log']->addWarning( + sprintf("Plugin '%s' enabled but not found! Try clearing cache with `bin/grav clear-cache`", $name) + ); + return null; + } + + require_once $filePath; + + $pluginClassName = 'Grav\\Plugin\\' . ucfirst($name) . 'Plugin'; + if (!class_exists($pluginClassName)) { + $pluginClassName = 'Grav\\Plugin\\' . $grav['inflector']->camelize($name) . 'Plugin'; + if (!class_exists($pluginClassName)) { + throw new \RuntimeException(sprintf("Plugin '%s' class not found! Try reinstalling this plugin.", $name)); + } + } + return new $pluginClassName($name, $grav); + } + +} diff --git a/system/src/Grav/Common/Processors/AssetsProcessor.php b/system/src/Grav/Common/Processors/AssetsProcessor.php new file mode 100644 index 0000000..6ca952d --- /dev/null +++ b/system/src/Grav/Common/Processors/AssetsProcessor.php @@ -0,0 +1,21 @@ +container['assets']->init(); + $this->container->fireEvent('onAssetsInitialized'); + } +} diff --git a/system/src/Grav/Common/Processors/ConfigurationProcessor.php b/system/src/Grav/Common/Processors/ConfigurationProcessor.php new file mode 100644 index 0000000..0347853 --- /dev/null +++ b/system/src/Grav/Common/Processors/ConfigurationProcessor.php @@ -0,0 +1,21 @@ +container['config']->init(); + $this->container['plugins']->setup(); + } +} diff --git a/system/src/Grav/Common/Processors/DebuggerAssetsProcessor.php b/system/src/Grav/Common/Processors/DebuggerAssetsProcessor.php new file mode 100644 index 0000000..643e8d1 --- /dev/null +++ b/system/src/Grav/Common/Processors/DebuggerAssetsProcessor.php @@ -0,0 +1,20 @@ +container['debugger']->addAssets(); + } +} diff --git a/system/src/Grav/Common/Processors/DebuggerInitProcessor.php b/system/src/Grav/Common/Processors/DebuggerInitProcessor.php new file mode 100644 index 0000000..e3b4e1d --- /dev/null +++ b/system/src/Grav/Common/Processors/DebuggerInitProcessor.php @@ -0,0 +1,20 @@ +container['debugger']->init(); + } +} diff --git a/system/src/Grav/Common/Processors/ErrorsProcessor.php b/system/src/Grav/Common/Processors/ErrorsProcessor.php new file mode 100644 index 0000000..7c7685d --- /dev/null +++ b/system/src/Grav/Common/Processors/ErrorsProcessor.php @@ -0,0 +1,20 @@ +container['errors']->resetHandlers(); + } +} diff --git a/system/src/Grav/Common/Processors/InitializeProcessor.php b/system/src/Grav/Common/Processors/InitializeProcessor.php new file mode 100644 index 0000000..e3f2569 --- /dev/null +++ b/system/src/Grav/Common/Processors/InitializeProcessor.php @@ -0,0 +1,44 @@ +container['config']->debug(); + + // Use output buffering to prevent headers from being sent too early. + ob_start(); + if ($this->container['config']->get('system.cache.gzip')) { + // Enable zip/deflate with a fallback in case of if browser does not support compressing. + if (!@ob_start("ob_gzhandler")) { + ob_start(); + } + } + + // Initialize the timezone. + if ($this->container['config']->get('system.timezone')) { + date_default_timezone_set($this->container['config']->get('system.timezone')); + } + + // FIXME: Initialize session should happen later after plugins have been loaded. This is a workaround to fix session issues in AWS. + if ($this->container['config']->get('system.session.initialize', 1) && isset($this->container['session'])) { + $this->container['session']->init(); + } + + // Initialize uri. + $this->container['uri']->init(); + + $this->container->setLocale(); + } +} diff --git a/system/src/Grav/Common/Processors/PagesProcessor.php b/system/src/Grav/Common/Processors/PagesProcessor.php new file mode 100644 index 0000000..b2828f7 --- /dev/null +++ b/system/src/Grav/Common/Processors/PagesProcessor.php @@ -0,0 +1,44 @@ +container['debugger']->addMessage($this->container['cache']->getCacheStatus()); + + $this->container['pages']->init(); + $this->container->fireEvent('onPagesInitialized', new Event(['pages' => $this->container['pages']])); + $this->container->fireEvent('onPageInitialized', new Event(['page' => $this->container['page']])); + + /** @var Page $page */ + $page = $this->container['page']; + + if (!$page->routable()) { + // If no page found, fire event + $event = $this->container->fireEvent('onPageNotFound', new Event(['page' => $page])); + + if (isset($event->page)) { + unset ($this->container['page']); + $this->container['page'] = $event->page; + } else { + throw new \RuntimeException('Page Not Found', 404); + } + } + + } +} diff --git a/system/src/Grav/Common/Processors/PluginsProcessor.php b/system/src/Grav/Common/Processors/PluginsProcessor.php new file mode 100644 index 0000000..ee56393 --- /dev/null +++ b/system/src/Grav/Common/Processors/PluginsProcessor.php @@ -0,0 +1,21 @@ +container['plugins']->init(); + $this->container->fireEvent('onPluginsInitialized'); + } +} diff --git a/system/src/Grav/Common/Processors/ProcessorBase.php b/system/src/Grav/Common/Processors/ProcessorBase.php new file mode 100644 index 0000000..056c86d --- /dev/null +++ b/system/src/Grav/Common/Processors/ProcessorBase.php @@ -0,0 +1,25 @@ +container = $container; + } + +} diff --git a/system/src/Grav/Common/Processors/ProcessorInterface.php b/system/src/Grav/Common/Processors/ProcessorInterface.php new file mode 100644 index 0000000..0e4b169 --- /dev/null +++ b/system/src/Grav/Common/Processors/ProcessorInterface.php @@ -0,0 +1,14 @@ +container; + $output = $container['output']; + + if ($output instanceof \Psr\Http\Message\ResponseInterface) { + // Support for custom output providers like Slim Framework. + } else { + // Use internal Grav output. + $container->output = $output; + $container->fireEvent('onOutputGenerated'); + + // Set the header type + $container->header(); + + echo $container->output; + + // remove any output + $container->output = ''; + + $this->container->fireEvent('onOutputRendered'); + } + } +} diff --git a/system/src/Grav/Common/Processors/SiteSetupProcessor.php b/system/src/Grav/Common/Processors/SiteSetupProcessor.php new file mode 100644 index 0000000..1f3f8af --- /dev/null +++ b/system/src/Grav/Common/Processors/SiteSetupProcessor.php @@ -0,0 +1,21 @@ +container['setup']->init(); + $this->container['streams']; + } +} diff --git a/system/src/Grav/Common/Processors/TasksProcessor.php b/system/src/Grav/Common/Processors/TasksProcessor.php new file mode 100644 index 0000000..d1e7a2f --- /dev/null +++ b/system/src/Grav/Common/Processors/TasksProcessor.php @@ -0,0 +1,23 @@ +container['task']; + if ($task) { + $this->container->fireEvent('onTask.' . $task); + } + } +} diff --git a/system/src/Grav/Common/Processors/ThemesProcessor.php b/system/src/Grav/Common/Processors/ThemesProcessor.php new file mode 100644 index 0000000..c9ea013 --- /dev/null +++ b/system/src/Grav/Common/Processors/ThemesProcessor.php @@ -0,0 +1,20 @@ +container['themes']->init(); + } +} diff --git a/system/src/Grav/Common/Processors/TwigProcessor.php b/system/src/Grav/Common/Processors/TwigProcessor.php new file mode 100644 index 0000000..392824f --- /dev/null +++ b/system/src/Grav/Common/Processors/TwigProcessor.php @@ -0,0 +1,21 @@ +container['twig']->init(); + } + +} diff --git a/system/src/Grav/Common/Service/AssetsServiceProvider.php b/system/src/Grav/Common/Service/AssetsServiceProvider.php new file mode 100644 index 0000000..9618013 --- /dev/null +++ b/system/src/Grav/Common/Service/AssetsServiceProvider.php @@ -0,0 +1,21 @@ +findResource('cache://compiled/blueprints', true, true); + + $files = []; + $paths = $locator->findResources('blueprints://config'); + $files += (new ConfigFileFinder)->locateFiles($paths); + $paths = $locator->findResources('plugins://'); + $files += (new ConfigFileFinder)->setBase('plugins')->locateInFolders($paths, 'blueprints'); + + $blueprints = new CompiledBlueprints($cache, $files, GRAV_ROOT); + + return $blueprints->name("master-{$setup->environment}")->load(); + } + + public static function load(Container $container) + { + /** Setup $setup */ + $setup = $container['setup']; + + /** @var UniformResourceLocator $locator */ + $locator = $container['locator']; + + $cache = $locator->findResource('cache://compiled/config', true, true); + + $files = []; + $paths = $locator->findResources('config://'); + $files += (new ConfigFileFinder)->locateFiles($paths); + $paths = $locator->findResources('plugins://'); + $files += (new ConfigFileFinder)->setBase('plugins')->locateInFolders($paths); + + $config = new CompiledConfig($cache, $files, GRAV_ROOT); + $config->setBlueprints(function() use ($container) { + return $container['blueprints']; + }); + + return $config->name("master-{$setup->environment}")->load(); + } + + public static function languages(Container $container) + { + /** @var Setup $setup */ + $setup = $container['setup']; + + /** @var Config $config */ + $config = $container['config']; + + /** @var UniformResourceLocator $locator */ + $locator = $container['locator']; + + $cache = $locator->findResource('cache://compiled/languages', true, true); + $files = []; + + // Process languages only if enabled in configuration. + if ($config->get('system.languages.translations', true)) { + $paths = $locator->findResources('languages://'); + $files += (new ConfigFileFinder)->locateFiles($paths); + $paths = $locator->findResources('plugins://'); + $files += (new ConfigFileFinder)->setBase('plugins')->locateInFolders($paths, 'languages'); + $paths = static::pluginFolderPaths($paths, 'languages'); + $files += (new ConfigFileFinder)->locateFiles($paths); + } + + $languages = new CompiledLanguages($cache, $files, GRAV_ROOT); + + return $languages->name("master-{$setup->environment}")->load(); + } + + /** + * Find specific paths in plugins + * + * @param $plugins + * @param $folder_path + * @return array + */ + private static function pluginFolderPaths($plugins, $folder_path) + { + $paths = []; + + foreach ($plugins as $path) { + $iterator = new \DirectoryIterator($path); + + /** @var \DirectoryIterator $directory */ + foreach ($iterator as $directory) { + if (!$directory->isDir() || $directory->isDot()) { + continue; + } + + // Path to the languages folder + $lang_path = $directory->getPathName() . '/' . $folder_path; + + // If this folder exists, add it to the list of paths + if (file_exists($lang_path)) { + $paths []= $lang_path; + } + } + } + return $paths; + } + +} diff --git a/system/src/Grav/Common/Service/ErrorServiceProvider.php b/system/src/Grav/Common/Service/ErrorServiceProvider.php new file mode 100644 index 0000000..139de54 --- /dev/null +++ b/system/src/Grav/Common/Service/ErrorServiceProvider.php @@ -0,0 +1,22 @@ +findResource('log://grav.log', true, true); + + $log->pushHandler(new StreamHandler($log_file, Logger::DEBUG)); + + return $log; + }; + } +} diff --git a/system/src/Grav/Common/Service/OutputServiceProvider.php b/system/src/Grav/Common/Service/OutputServiceProvider.php new file mode 100644 index 0000000..89322ee --- /dev/null +++ b/system/src/Grav/Common/Service/OutputServiceProvider.php @@ -0,0 +1,30 @@ +processSite($page->templateFormat()); + }; + } +} diff --git a/system/src/Grav/Common/Service/PageServiceProvider.php b/system/src/Grav/Common/Service/PageServiceProvider.php new file mode 100644 index 0000000..bf55f79 --- /dev/null +++ b/system/src/Grav/Common/Service/PageServiceProvider.php @@ -0,0 +1,102 @@ +path(); // Don't trim to support trailing slash default routes + $path = $path ?: '/'; + + $page = $pages->dispatch($path); + + // Redirection tests + if ($page) { + /** @var Language $language */ + $language = $c['language']; + + // some debugger override logic + if ($page->debugger() === false) { + $c['debugger']->enabled(false); + } + + if ($c['config']->get('system.force_ssl')) { + if (!isset($_SERVER['HTTPS']) || $_SERVER["HTTPS"] != "on") { + $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; + $c->redirect($url); + } + } + + $url = $page->route(); + + if ($uri->params()) { + if ($url == '/') { //Avoid double slash + $url = $uri->params(); + } else { + $url .= $uri->params(); + } + } + if ($uri->query()) { + $url .= '?' . $uri->query(); + } + if ($uri->fragment()) { + $url .= '#' . $uri->fragment(); + } + + // Language-specific redirection scenarios + if ($language->enabled()) { + if ($language->isLanguageInUrl() && !$language->isIncludeDefaultLanguage()) { + $c->redirect($url); + } + if (!$language->isLanguageInUrl() && $language->isIncludeDefaultLanguage()) { + $c->redirectLangSafe($url); + } + } + // Default route test and redirect + if ($c['config']->get('system.pages.redirect_default_route') && $page->route() != $path) { + $c->redirectLangSafe($url); + } + } + + // if page is not found, try some fallback stuff + if (!$page || !$page->routable()) { + + // Try fallback URL stuff... + $page = $c->fallbackUrl($path); + + if (!$page) { + $path = $c['locator']->findResource('system://pages/notfound.md'); + $page = new Page(); + $page->init(new \SplFileInfo($path)); + $page->routable(false); + } + } + + return $page; + }; + } +} diff --git a/system/src/Grav/Common/Service/SessionServiceProvider.php b/system/src/Grav/Common/Service/SessionServiceProvider.php new file mode 100644 index 0000000..52e107b --- /dev/null +++ b/system/src/Grav/Common/Service/SessionServiceProvider.php @@ -0,0 +1,105 @@ +get('system.session.timeout', 1800); + $session_path = $config->get('system.session.path'); + if (null === $session_path) { + $session_path = '/' . ltrim(Uri::filterPath($uri->rootUrl(false)), '/'); + } + $domain = $uri->host(); + if ($domain === 'localhost') { + $domain = ''; + } + + // Get session options. + $secure = (bool)$config->get('system.session.secure', false); + $httponly = (bool)$config->get('system.session.httponly', true); + $enabled = (bool)$config->get('system.session.enabled', false); + + // Activate admin if we're inside the admin path. + $is_admin = false; + if ($config->get('plugins.admin.enabled')) { + $base = '/' . trim($config->get('plugins.admin.route'), '/'); + + // Uri::route() is not processed yet, let's quickly get what we need. + $current_route = str_replace(Uri::filterPath($uri->rootUrl(false)), '', parse_url($uri->url(true), PHP_URL_PATH)); + + // Check no language, simple language prefix (en) and region specific language prefix (en-US). + $pos = strpos($current_route, $base); + if ($pos === 0 || $pos === 3 || $pos === 6) { + $session_timeout = $config->get('plugins.admin.session.timeout', 1800); + $enabled = $is_admin = true; + } + } + + // Fix for HUGE session timeouts. + if ($session_timeout > 99999999999) { + $session_timeout = 9999999999; + } + + $inflector = new Inflector(); + $session_name = $inflector->hyphenize($config->get('system.session.name', 'grav_site')) . '-' . substr(md5(GRAV_ROOT), 0, 7); + if ($is_admin && $config->get('system.session.split', true)) { + $session_name .= '-admin'; + } + + // Define session service. + $session = new Session($session_timeout, $session_path, $domain); + $session->setName($session_name); + $session->setSecure($secure); + $session->setHttpOnly($httponly); + $session->setAutoStart($enabled); + + return $session; + }; + + // Define session message service. + $container['messages'] = function ($c) { + if (!isset($c['session']) || !$c['session']->started()) { + /** @var Debugger $debugger */ + $debugger = $c['debugger']; + $debugger->addMessage('Inactive session: session messages may disappear', 'warming'); + + return new Message; + } + + /** @var Session $session */ + $session = $c['session']; + + if (!isset($session->messages)) { + $session->messages = new Message; + } + + return $session->messages; + }; + } +} diff --git a/system/src/Grav/Common/Service/StreamsServiceProvider.php b/system/src/Grav/Common/Service/StreamsServiceProvider.php new file mode 100644 index 0000000..a2ebcc6 --- /dev/null +++ b/system/src/Grav/Common/Service/StreamsServiceProvider.php @@ -0,0 +1,47 @@ +initializeLocator($locator); + + return $locator; + }; + + $container['streams'] = function($c) { + /** @var Setup $setup */ + $setup = $c['setup']; + + /** @var UniformResourceLocator $locator */ + $locator = $c['locator']; + + // Set locator to both streams. + Stream::setLocator($locator); + ReadOnlyStream::setLocator($locator); + + return new StreamBuilder($setup->getStreams()); + }; + } +} diff --git a/system/src/Grav/Common/Service/TaskServiceProvider.php b/system/src/Grav/Common/Service/TaskServiceProvider.php new file mode 100644 index 0000000..40b9696 --- /dev/null +++ b/system/src/Grav/Common/Service/TaskServiceProvider.php @@ -0,0 +1,24 @@ +param('task'); + }; + } +} diff --git a/system/src/Grav/Common/Session.php b/system/src/Grav/Common/Session.php new file mode 100644 index 0000000..7573f08 --- /dev/null +++ b/system/src/Grav/Common/Session.php @@ -0,0 +1,153 @@ +lifetime = $lifetime; + $this->path = $path; + $this->domain = $domain; + + if (php_sapi_name() !== 'cli') { + parent::__construct($lifetime, $path, $domain); + } + } + + /** + * Initialize session. + * + * Code in this function has been moved into SessionServiceProvider class. + */ + public function init() + { + if ($this->autoStart) { + $this->start(); + + // TODO: This setcookie shouldn't be here, session should by itself be able to update its cookie. + setcookie(session_name(), session_id(), $this->lifetime ? time() + $this->lifetime : 0, $this->path, $this->domain, $this->secure, $this->httpOnly); + + $this->autoStart = false; + } + } + + /** + * @param bool $auto + * @return $this + */ + public function setAutoStart($auto) + { + $this->autoStart = (bool)$auto; + + return $this; + } + + /** + * @param bool $secure + * @return $this + */ + public function setSecure($secure) + { + $this->secure = $secure; + ini_set('session.cookie_secure', (bool)$secure); + + return $this; + } + + /** + * @param bool $httpOnly + * @return $this + */ + public function setHttpOnly($httpOnly) + { + $this->httpOnly = $httpOnly; + ini_set('session.cookie_httponly', (bool)$httpOnly); + + return $this; + } + + /** + * Store something in session temporarily. + * + * @param string $name + * @param mixed $object + * @return $this + */ + public function setFlashObject($name, $object) + { + $this->{$name} = serialize($object); + + return $this; + } + + /** + * Return object and remove it from session. + * + * @param string $name + * @return mixed + */ + public function getFlashObject($name) + { + $object = unserialize($this->{$name}); + + $this->{$name} = null; + + return $object; + } + + /** + * Store something in cookie temporarily. + * + * @param string $name + * @param mixed $object + * @param int $time + * @return $this + */ + public function setFlashCookieObject($name, $object, $time = 60) + { + setcookie($name, json_encode($object), time() + $time, '/'); + + return $this; + } + + /** + * Return object and remove it from the cookie. + * + * @param string $name + * @return mixed|null + */ + public function getFlashCookieObject($name) + { + if (isset($_COOKIE[$name])) { + $object = json_decode($_COOKIE[$name]); + setcookie($name, '', time() - 3600, '/'); + return $object; + } + + return null; + } +} diff --git a/system/src/Grav/Common/Taxonomy.php b/system/src/Grav/Common/Taxonomy.php new file mode 100644 index 0000000..dda2844 --- /dev/null +++ b/system/src/Grav/Common/Taxonomy.php @@ -0,0 +1,149 @@ +taxonomy_map = []; + $this->grav = $grav; + } + + /** + * Takes an individual page and processes the taxonomies configured in its header. It + * then adds those taxonomies to the map + * + * @param Page $page the page to process + * @param array $page_taxonomy + */ + public function addTaxonomy(Page $page, $page_taxonomy = null) + { + if (!$page_taxonomy) { + $page_taxonomy = $page->taxonomy(); + } + + if (!$page->published() || empty($page_taxonomy)) { + return; + } + + /** @var Config $config */ + $config = $this->grav['config']; + if ($config->get('site.taxonomies')) { + foreach ((array)$config->get('site.taxonomies') as $taxonomy) { + if (isset($page_taxonomy[$taxonomy])) { + foreach ((array)$page_taxonomy[$taxonomy] as $item) { + $this->taxonomy_map[$taxonomy][(string)$item][$page->path()] = ['slug' => $page->slug()]; + } + } + } + } + } + + /** + * Returns a new Page object with the sub-pages containing all the values set for a + * particular taxonomy. + * + * @param array $taxonomies taxonomies to search, eg ['tag'=>['animal','cat']] + * @param string $operator can be 'or' or 'and' (defaults to 'and') + * + * @return Collection Collection object set to contain matches found in the taxonomy map + */ + public function findTaxonomy($taxonomies, $operator = 'and') + { + $matches = []; + $results = []; + + foreach ((array)$taxonomies as $taxonomy => $items) { + foreach ((array)$items as $item) { + if (isset($this->taxonomy_map[$taxonomy][$item])) { + $matches[] = $this->taxonomy_map[$taxonomy][$item]; + } else { + $matches[] = []; + } + } + } + + if (strtolower($operator) == 'or') { + foreach ($matches as $match) { + $results = array_merge($results, $match); + } + } else { + $results = $matches ? array_pop($matches) : []; + foreach ($matches as $match) { + $results = array_intersect_key($results, $match); + } + } + + return new Collection($results, ['taxonomies' => $taxonomies]); + } + + /** + * Gets and Sets the taxonomy map + * + * @param array $var the taxonomy map + * + * @return array the taxonomy map + */ + public function taxonomy($var = null) + { + if ($var) { + $this->taxonomy_map = $var; + } + + return $this->taxonomy_map; + } + + /** + * Gets item keys per taxonomy + * + * @param string $taxonomy taxonomy name + * + * @return array keys of this taxonomy + */ + public function getTaxonomyItemKeys($taxonomy) { + if (isset($this->taxonomy_map[$taxonomy])) { + + $results = array_keys($this->taxonomy_map[$taxonomy]); + + return $results; + } + + return []; + } +} diff --git a/system/src/Grav/Common/Theme.php b/system/src/Grav/Common/Theme.php new file mode 100644 index 0000000..537df11 --- /dev/null +++ b/system/src/Grav/Common/Theme.php @@ -0,0 +1,94 @@ +config["themes.{$this->name}"]; + } + + /** + * 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; + } + + $grav = Grav::instance(); + $locator = $grav['locator']; + $filename = 'config://themes/' . $theme_name . '.yaml'; + $file = YamlFile::instance($locator->findResource($filename, true, true)); + $content = $grav['config']->get('themes.' . $theme_name); + $file->save($content); + $file->free(); + + return true; + } + + /** + * Override the mergeConfig method to work for themes + */ + protected function mergeConfig(Page $page, $deep = 'merge', $params = [], $type = 'themes') { + return parent::mergeConfig($page, $deep, $params, $type); + } + + /** + * Simpler getter for the theme blueprint + * + * @return mixed + */ + public function getBlueprint() + { + if (!$this->blueprint) { + $this->loadBlueprint(); + } + return $this->blueprint; + } + + /** + * Load blueprints. + */ + protected function loadBlueprint() + { + if (!$this->blueprint) { + $grav = Grav::instance(); + $themes = $grav['themes']; + $this->blueprint = $themes->get($this->name)->blueprints(); + } + } +} diff --git a/system/src/Grav/Common/Themes.php b/system/src/Grav/Common/Themes.php new file mode 100644 index 0000000..8f29037 --- /dev/null +++ b/system/src/Grav/Common/Themes.php @@ -0,0 +1,359 @@ +grav = $grav; + $this->config = $grav['config']; + + // Register instance as autoloader for theme inheritance + spl_autoload_register([$this, 'autoloadTheme']); + } + + public function init() + { + /** @var Themes $themes */ + $themes = $this->grav['themes']; + $themes->configure(); + + $this->initTheme(); + } + + public function initTheme() + { + if ($this->inited === false) { + /** @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'); + + $this->inited = true; + } + } + + /** + * Return list of all theme data with their blueprints. + * + * @return array + */ + public function all() + { + $list = []; + + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + + $iterator = $locator->getIterator('themes://'); + + /** @var \DirectoryIterator $directory */ + foreach ($iterator as $directory) { + if (!$directory->isDir() || $directory->isDot()) { + continue; + } + + $theme = $directory->getBasename(); + $result = self::get($theme); + + if ($result) { + $list[$theme] = $result; + } + } + ksort($list); + + return $list; + } + + /** + * Get theme configuration or throw exception if it cannot be found. + * + * @param string $name + * + * @return Data + * @throws \RuntimeException + */ + public function get($name) + { + if (!$name) { + throw new \RuntimeException('Theme name not provided.'); + } + + $blueprints = new Blueprints('themes://'); + $blueprint = $blueprints->get("{$name}/blueprints"); + + // Load default configuration. + $file = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT); + + // ensure this is a valid theme + if (!$file->exists()) { + return null; + } + + // Find thumbnail. + $thumb = "themes://{$name}/thumbnail.jpg"; + $path = $this->grav['locator']->findResource($thumb, false); + + if ($path) { + $blueprint->set('thumbnail', $this->grav['base_url'] . '/' . $path); + } + + $obj = new Data($file->content(), $blueprint); + + // Override with user configuration. + $obj->merge($this->config->get('themes.' . $name) ?: []); + + // Save configuration always to user/config. + $file = CompiledYamlFile::instance("config://themes/{$name}" . YAML_EXT); + $obj->file($file); + + return $obj; + } + + /** + * Return name of the current theme. + * + * @return string + */ + public function current() + { + return (string)$this->config->get('system.pages.theme'); + } + + /** + * Load current theme. + * + * @return Theme + */ + public function load() + { + // NOTE: ALL THE LOCAL VARIABLES ARE USED INSIDE INCLUDED FILE, DO NOT REMOVE THEM! + $grav = $this->grav; + $config = $this->config; + $name = $this->current(); + + /** @var UniformResourceLocator $locator */ + $locator = $grav['locator']; + $file = $locator('theme://theme.php') ?: $locator("theme://{$name}.php"); + + $inflector = $grav['inflector']; + + if ($file) { + // Local variables available in the file: $grav, $config, $name, $file + $class = include $file; + + if (!is_object($class)) { + $themeClassFormat = [ + 'Grav\\Theme\\' . ucfirst($name), + 'Grav\\Theme\\' . $inflector->camelize($name) + ]; + + foreach ($themeClassFormat as $themeClass) { + if (class_exists($themeClass)) { + $themeClassName = $themeClass; + $class = new $themeClassName($grav, $config, $name); + break; + } + } + } + } elseif (!$locator('theme://') && !defined('GRAV_CLI')) { + exit("Theme '$name' does not exist, unable to display page."); + } + + $this->config->set('theme', $config->get('themes.' . $name)); + + if (empty($class)) { + $class = new Theme($grav, $config, $name); + } + + return $class; + } + + /** + * Configure and prepare streams for current template. + * + * @throws \InvalidArgumentException + */ + public function configure() + { + $name = $this->current(); + $config = $this->config; + + $this->loadConfiguration($name, $config); + + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + + $registered = stream_get_wrappers(); + + $schemes = $config->get("themes.{$name}.streams.schemes", []); + $schemes += [ + 'theme' => [ + 'type' => 'ReadOnlyStream', + 'paths' => $locator->findResources("themes://{$name}", false) + ] + ]; + + foreach ($schemes as $scheme => $config) { + if (isset($config['paths'])) { + $locator->addPath($scheme, '', $config['paths']); + } + if (isset($config['prefixes'])) { + foreach ($config['prefixes'] as $prefix => $paths) { + $locator->addPath($scheme, $prefix, $paths); + } + } + + if (in_array($scheme, $registered)) { + stream_wrapper_unregister($scheme); + } + $type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream'; + if ($type[0] !== '\\') { + $type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type; + } + + if (!stream_wrapper_register($scheme, $type)) { + throw new \InvalidArgumentException("Stream '{$type}' could not be initialized."); + } + } + + // Load languages after streams has been properly initialized + $this->loadLanguages($this->config); + } + + /** + * Load theme configuration. + * + * @param string $name Theme name + * @param Config $config Configuration class + */ + protected function loadConfiguration($name, Config $config) + { + $themeConfig = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT)->content(); + $config->joinDefaults("themes.{$name}", $themeConfig); + } + + /** + * Load theme languages. + * + * @param Config $config Configuration class + */ + protected function loadLanguages(Config $config) + { + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + + if ($config->get('system.languages.translations', true)) { + $language_file = $locator->findResource("theme://languages" . YAML_EXT); + if ($language_file) { + $language = CompiledYamlFile::instance($language_file)->content(); + $this->grav['languages']->mergeRecursive($language); + } + $languages_folder = $locator->findResource("theme://languages/"); + if (file_exists($languages_folder)) { + $languages = []; + $iterator = new \DirectoryIterator($languages_folder); + + /** @var \DirectoryIterator $directory */ + foreach ($iterator as $file) { + if ($file->getExtension() !== 'yaml') { + continue; + } + $languages[$file->getBasename('.yaml')] = CompiledYamlFile::instance($file->getPathname())->content(); + } + $this->grav['languages']->mergeRecursive($languages); + } + } + } + + /** + * Autoload theme classes for inheritance + * + * @param string $class Class name + * + * @return mixed false FALSE if unable to load $class; Class name if + * $class is successfully loaded + */ + protected function autoloadTheme($class) + { + $prefix = 'Grav\\Theme\\'; + if (false !== strpos($class, $prefix)) { + // Remove prefix from class + $class = substr($class, strlen($prefix)); + $locator = $this->grav['locator']; + + // First try lowercase version of the classname. + $path = strtolower($class); + $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php"); + + if ($file) { + return include_once $file; + } + + // Replace namespace tokens to directory separators + $path = $this->grav['inflector']->hyphenize($class); + $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php"); + + // Load class + if ($file) { + return include_once $file; + } + + // Try Old style theme classes + $path = strtolower(preg_replace('#\\\|_(?!.+\\\)#', '/', $class)); + $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php"); + + // Load class + if ($file) { + return include_once $file; + } + } + + return false; + } +} diff --git a/system/src/Grav/Common/Twig/Node/TwigNodeMarkdown.php b/system/src/Grav/Common/Twig/Node/TwigNodeMarkdown.php new file mode 100644 index 0000000..5943c95 --- /dev/null +++ b/system/src/Grav/Common/Twig/Node/TwigNodeMarkdown.php @@ -0,0 +1,35 @@ + $body), array(), $lineno, $tag); + } + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler A Twig_Compiler instance + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write('ob_start();' . PHP_EOL) + ->subcompile($this->getNode('body')) + ->write('$content = ob_get_clean();' . PHP_EOL) + ->write('preg_match("/^\s*/", $content, $matches);' . PHP_EOL) + ->write('$lines = explode("\n", $content);' . PHP_EOL) + ->write('$content = preg_replace(\'/^\' . $matches[0]. \'/\', "", $lines);' . PHP_EOL) + ->write('$content = join("\n", $content);' . PHP_EOL) + ->write('echo $this->env->getExtension(\'Grav\Common\Twig\TwigExtension\')->markdownFunction($content);' . PHP_EOL); + } +} diff --git a/system/src/Grav/Common/Twig/Node/TwigNodeScript.php b/system/src/Grav/Common/Twig/Node/TwigNodeScript.php new file mode 100644 index 0000000..35ca20f --- /dev/null +++ b/system/src/Grav/Common/Twig/Node/TwigNodeScript.php @@ -0,0 +1,102 @@ + $body, 'file' => $file, 'group' => $group, 'priority' => $priority, 'attributes' => $attributes], [], $lineno, $tag); + } + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler $compiler A Twig_Compiler instance + * @throws \LogicException + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + if ($this->getNode('attributes') !== null) { + $compiler + ->write('$attributes = ') + ->subcompile($this->getNode('attributes')) + ->raw(";\n") + ->write("if (\$attributes !== null && !is_array(\$attributes)) {\n") + ->indent() + ->write("throw new UnexpectedValueException('{% {$this->tagName} with x %}: x is not an array');\n") + ->outdent() + ->write("}\n"); + } else { + $compiler->write('$attributes = [];' . "\n"); + } + + if ($this->getNode('group') !== null) { + $compiler + ->write('$group = ') + ->subcompile($this->getNode('group')) + ->raw(";\n") + ->write("if (\$group !== null && !is_string(\$group)) {\n") + ->indent() + ->write("throw new UnexpectedValueException('{% {$this->tagName} in x %}: x is not a string');\n") + ->outdent() + ->write("}\n"); + } else { + $compiler->write('$group = null;' . "\n"); + } + + if ($this->getNode('priority') !== null) { + $compiler + ->write('$priority = (int)(') + ->subcompile($this->getNode('priority')) + ->raw(");\n"); + } else { + $compiler->write('$priority = null;' . "\n"); + } + + $compiler->write("\$assets = \\Grav\\Common\\Grav::instance()['assets'];\n"); + + if ($this->getNode('file') !== null) { + $compiler + ->write('$file = ') + ->subcompile($this->getNode('file')) + ->write(";\n") + ->write("\$pipeline = !empty(\$attributes['pipeline']);\n") + ->write("\$loading = !empty(\$attributes['defer']) ? 'defer' : (!empty(\$attributes['async']) ? 'async' : null);\n") + ->write("\$assets->addJs(\$file, \$priority, \$pipeline, \$loading, \$group);\n"); + } else { + $compiler + ->write("ob_start();\n") + ->subcompile($this->getNode('body')) + ->write("\$content = ob_get_clean();") + ->write("\$assets->addInlineJs(\$content, \$priority, \$group, \$attributes);\n"); + } + } +} diff --git a/system/src/Grav/Common/Twig/Node/TwigNodeStyle.php b/system/src/Grav/Common/Twig/Node/TwigNodeStyle.php new file mode 100644 index 0000000..8c0b3b8 --- /dev/null +++ b/system/src/Grav/Common/Twig/Node/TwigNodeStyle.php @@ -0,0 +1,98 @@ + $body, 'file' => $file, 'group' => $group, 'priority' => $priority, 'attributes' => $attributes], [], $lineno, $tag); + } + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler $compiler A Twig_Compiler instance + * @throws \LogicException + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + if ($this->getNode('attributes') !== null) { + $compiler + ->write('$attributes = ') + ->subcompile($this->getNode('attributes')) + ->raw(";\n") + ->write("if (\$attributes !== null && !is_array(\$attributes)) {\n") + ->indent() + ->write("throw new UnexpectedValueException('{% {$this->tagName} with x %}: x is not an array');\n") + ->outdent() + ->write("}\n"); + } else { + $compiler->write('$attributes = [];' . "\n"); + } + + if ($this->getNode('group') !== null) { + $compiler + ->write('$group = ') + ->subcompile($this->getNode('group')) + ->raw(";\n") + ->write("if (\$group !== null && !is_string(\$group)) {\n") + ->indent() + ->write("throw new UnexpectedValueException('{% {$this->tagName} in x %}: x is not a string');\n") + ->outdent() + ->write("}\n"); + } else { + $compiler->write('$group = null;' . "\n"); + } + + if ($this->getNode('priority') !== null) { + $compiler + ->write('$priority = (int)(') + ->subcompile($this->getNode('priority')) + ->raw(");\n"); + } else { + $compiler->write('$priority = null;' . "\n"); + } + + $compiler->write("\$assets = \\Grav\\Common\\Grav::instance()['assets'];\n"); + + if ($this->getNode('file') !== null) { + $compiler + ->write('$file = ') + ->subcompile($this->getNode('file')) + ->write(";\n") + ->write("\$pipeline = !empty(\$attributes['pipeline']);\n") + ->write("\$assets->addCss(\$file, \$priority, \$pipeline, \$group);\n"); + } else { + $compiler + ->write("ob_start();\n") + ->subcompile($this->getNode('body')) + ->write("\$content = ob_get_clean();") + ->write("\$assets->addInlineCss(\$content, \$priority, \$group);\n"); + } + } +} diff --git a/system/src/Grav/Common/Twig/Node/TwigNodeSwitch.php b/system/src/Grav/Common/Twig/Node/TwigNodeSwitch.php new file mode 100644 index 0000000..e0e8127 --- /dev/null +++ b/system/src/Grav/Common/Twig/Node/TwigNodeSwitch.php @@ -0,0 +1,71 @@ + $value, 'cases' => $cases, 'default' => $default), array(), $lineno, $tag); + } + + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler A Twig_Compiler instance + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write("switch (") + ->subcompile($this->getNode('value')) + ->raw(") {\n") + ->indent(); + + foreach ($this->getNode('cases') as $case) + { + if (!$case->hasNode('body')) + { + continue; + } + + foreach ($case->getNode('values') as $value) + { + $compiler + ->write('case ') + ->subcompile($value) + ->raw(":\n"); + } + + $compiler + ->write("{\n") + ->indent() + ->subcompile($case->getNode('body')) + ->write("break;\n") + ->outdent() + ->write("}\n"); + } + + if ($this->hasNode('default') && $this->getNode('default') !== null) + { + $compiler + ->write("default:\n") + ->write("{\n") + ->indent() + ->subcompile($this->getNode('default')) + ->outdent() + ->write("}\n"); + } + + $compiler + ->outdent() + ->write("}\n"); + } +} diff --git a/system/src/Grav/Common/Twig/Node/TwigNodeTryCatch.php b/system/src/Grav/Common/Twig/Node/TwigNodeTryCatch.php new file mode 100644 index 0000000..e37c319 --- /dev/null +++ b/system/src/Grav/Common/Twig/Node/TwigNodeTryCatch.php @@ -0,0 +1,52 @@ + $try, 'catch' => $catch), array(), $lineno, $tag); + } + + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler $compiler A Twig_Compiler instance + * @throws \LogicException + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + $compiler + ->write('try {') + ; + + $compiler + ->indent() + ->subcompile($this->getNode('try')) + ; + + if ($this->hasNode('catch') && null !== $this->getNode('catch')) { + $compiler + ->outdent() + ->write('} catch (\Exception $e) {' . "\n") + ->indent() + ->write('if (isset($context[\'grav\'][\'debugger\'])) $context[\'grav\'][\'debugger\']->addException($e);' . "\n") + ->write('$context[\'e\'] = $e;' . "\n") + ->subcompile($this->getNode('catch')) + ; + } + + $compiler + ->outdent() + ->write("}\n"); + } +} diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php new file mode 100644 index 0000000..a1d4135 --- /dev/null +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php @@ -0,0 +1,53 @@ +getLine(); + $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(array($this, 'decideMarkdownEnd'), true); + $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); + return new TwigNodeMarkdown($body, $lineno, $this->getTag()); + } + /** + * Decide if current token marks end of Markdown block. + * + * @param \Twig_Token $token + * @return bool + */ + public function decideMarkdownEnd(\Twig_Token $token) + { + return $token->test('endmarkdown'); + } + /** + * {@inheritdoc} + */ + public function getTag() + { + return 'markdown'; + } +} diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php new file mode 100644 index 0000000..98c72e2 --- /dev/null +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php @@ -0,0 +1,100 @@ +getLine(); + $stream = $this->parser->getStream(); + + list($file, $group, $priority, $attributes) = $this->parseArguments($token); + + $content = null; + if ($file === null) { + $content = $this->parser->subparse([$this, 'decideBlockEnd'], true); + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + } + + return new TwigNodeScript($content, $file, $group, $priority, $attributes, $lineno, $this->getTag()); + } + + /** + * @param \Twig_Token $token + * @return array + */ + protected function parseArguments(\Twig_Token $token) + { + $stream = $this->parser->getStream(); + + $file = null; + if (!$stream->test(\Twig_Token::NAME_TYPE) && !$stream->test(\Twig_Token::OPERATOR_TYPE) && !$stream->test(\Twig_Token::BLOCK_END_TYPE)) { + $file = $this->parser->getExpressionParser()->parseExpression(); + } + + $group = null; + if ($stream->nextIf(\Twig_Token::OPERATOR_TYPE, 'in')) { + $group = $this->parser->getExpressionParser()->parseExpression(); + } + + $priority = null; + if ($stream->nextIf(\Twig_Token::NAME_TYPE, 'priority')) { + $stream->expect(\Twig_Token::PUNCTUATION_TYPE, ':'); + $priority = $this->parser->getExpressionParser()->parseExpression(); + } + + $attributes = null; + if ($stream->nextIf(\Twig_Token::NAME_TYPE, 'with')) { + $attributes = $this->parser->getExpressionParser()->parseExpression(); + } + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + return [$file, $group, $priority, $attributes]; + } + + /** + * @param \Twig_Token $token + * @return bool + */ + public function decideBlockEnd(\Twig_Token $token) + { + return $token->test('endscript'); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'script'; + } +} diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php new file mode 100644 index 0000000..f207686 --- /dev/null +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php @@ -0,0 +1,99 @@ +getLine(); + $stream = $this->parser->getStream(); + + list ($file, $group, $priority, $attributes) = $this->parseArguments($token); + + $content = null; + if (!$file) { + $content = $this->parser->subparse([$this, 'decideBlockEnd'], true); + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + } + + return new TwigNodeStyle($content, $file, $group, $priority, $attributes, $lineno, $this->getTag()); + } + + /** + * @param \Twig_Token $token + * @return array + */ + protected function parseArguments(\Twig_Token $token) + { + $stream = $this->parser->getStream(); + + $file = null; + if (!$stream->test(\Twig_Token::NAME_TYPE) && !$stream->test(\Twig_Token::OPERATOR_TYPE) && !$stream->test(\Twig_Token::BLOCK_END_TYPE)) { + $file = $this->parser->getExpressionParser()->parseExpression(); + } + + $group = null; + if ($stream->nextIf(\Twig_Token::OPERATOR_TYPE, 'in')) { + $group = $this->parser->getExpressionParser()->parseExpression(); + } + + $priority = null; + if ($stream->nextIf(\Twig_Token::NAME_TYPE, 'priority')) { + $stream->expect(\Twig_Token::PUNCTUATION_TYPE, ':'); + $priority = $this->parser->getExpressionParser()->parseExpression(); + } + + $attributes = null; + if ($stream->nextIf(\Twig_Token::NAME_TYPE, 'with')) { + $attributes = $this->parser->getExpressionParser()->parseExpression(); + } + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + return [$file, $group, $priority, $attributes]; + } + + /** + * @param \Twig_Token $token + * @return bool + */ + public function decideBlockEnd(\Twig_Token $token) + { + return $token->test('endstyle'); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'style'; + } +} diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php new file mode 100644 index 0000000..2da932d --- /dev/null +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php @@ -0,0 +1,138 @@ +getLine(); + $stream = $this->parser->getStream(); + + $name = $this->parser->getExpressionParser()->parseExpression(); + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + // There can be some whitespace between the {% switch %} and first {% case %} tag. + while ($stream->getCurrent()->getType() == \Twig_Token::TEXT_TYPE && trim($stream->getCurrent()->getValue()) == '') + { + $stream->next(); + } + + $stream->expect(\Twig_Token::BLOCK_START_TYPE); + + $expressionParser = $this->parser->getExpressionParser(); + + $default = null; + $cases = array(); + $end = false; + + while (!$end) + { + $next = $stream->next(); + + switch ($next->getValue()) + { + case 'case': + { + $values = array(); + + while (true) + { + $values[] = $expressionParser->parsePrimaryExpression(); + // Multiple allowed values? + if ($stream->test(\Twig_Token::OPERATOR_TYPE, 'or')) + { + $stream->next(); + } + else + { + break; + } + } + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(array($this, 'decideIfFork')); + $cases[] = new \Twig_Node(array( + 'values' => new \Twig_Node($values), + 'body' => $body + )); + break; + } + case 'default': + { + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $default = $this->parser->subparse(array($this, 'decideIfEnd')); + break; + } + case 'endswitch': + { + $end = true; + break; + } + default: + { + throw new \Twig_Error_Syntax(sprintf('Unexpected end of template. Twig was looking for the following tags "case", "default", or "endswitch" to close the "switch" block started at line %d)', $lineno), -1); + } + } + } + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + return new TwigNodeSwitch($name, new \Twig_Node($cases), $default, $lineno, $this->getTag()); + } + + /** + * Decide if current token marks switch logic. + * + * @param \Twig_Token $token + * @return bool + */ + public function decideIfFork(\Twig_Token $token) + { + return $token->test(array('case', 'default', 'endswitch')); + } + + /** + * Decide if current token marks end of swtich block. + * + * @param \Twig_Token $token + * @return bool + */ + public function decideIfEnd(\Twig_Token $token) + { + return $token->test(array('endswitch')); + } + + + /** + * {@inheritdoc} + */ + public function getTag() + { + return 'switch'; + } +} diff --git a/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php new file mode 100644 index 0000000..d639c57 --- /dev/null +++ b/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php @@ -0,0 +1,68 @@ + + * {% try %} + *
  • {{ user.get('name') }}
  • + * {% catch %} + * {{ e.message }} + * {% endcatch %} + * + */ +class TwigTokenParserTryCatch extends \Twig_TokenParser +{ + /** + * Parses a token and returns a node. + * + * @param \Twig_Token $token A Twig_Token instance + * + * @return \Twig_NodeInterface A Twig_NodeInterface instance + */ + public function parse(\Twig_Token $token) + { + $lineno = $token->getLine(); + $stream = $this->parser->getStream(); + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $try = $this->parser->subparse([$this, 'decideCatch']); + $stream->next(); + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $catch = $this->parser->subparse([$this, 'decideEnd']); + $stream->next(); + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + return new TwigNodeTryCatch($try, $catch, $lineno, $this->getTag()); + } + + public function decideCatch(\Twig_Token $token) + { + return $token->test(array('catch')); + } + + public function decideEnd(\Twig_Token $token) + { + return $token->test(array('endtry')) || $token->test(array('endcatch')); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'try'; + } +} diff --git a/system/src/Grav/Common/Twig/Twig.php b/system/src/Grav/Common/Twig/Twig.php new file mode 100644 index 0000000..e1ba281 --- /dev/null +++ b/system/src/Grav/Common/Twig/Twig.php @@ -0,0 +1,413 @@ +grav = $grav; + $this->twig_paths = []; + } + + /** + * Twig initialization that sets the twig loader chain, then the environment, then extensions + * and also the base set of twig vars + */ + public function init() + { + if (!isset($this->twig)) { + /** @var Config $config */ + $config = $this->grav['config']; + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + + /** @var Language $language */ + $language = $this->grav['language']; + + $active_language = $language->getActive(); + + // handle language templates if available + if ($language->enabled()) { + $lang_templates = $locator->findResource('theme://templates/' . ($active_language ? $active_language : $language->getDefault())); + if ($lang_templates) { + $this->twig_paths[] = $lang_templates; + } + } + + $this->twig_paths = array_merge($this->twig_paths, $locator->findResources('theme://templates')); + + $this->grav->fireEvent('onTwigTemplatePaths'); + + // Add Grav core templates location + $this->twig_paths = array_merge($this->twig_paths, $locator->findResources('system://templates')); + + $this->loader = new \Twig_Loader_Filesystem($this->twig_paths); + + $this->grav->fireEvent('onTwigLoader'); + + $this->loaderArray = new \Twig_Loader_Array([]); + $loader_chain = new \Twig_Loader_Chain([$this->loaderArray, $this->loader]); + + $params = $config->get('system.twig'); + if (!empty($params['cache'])) { + $cachePath = $locator->findResource('cache://twig', true, true); + $params['cache'] = new \Twig_Cache_Filesystem($cachePath, \Twig_Cache_Filesystem::FORCE_BYTECODE_INVALIDATION); + } + + if (!empty($this->autoescape)) { + $params['autoescape'] = $this->autoescape; + } + + $this->twig = new TwigEnvironment($loader_chain, $params); + + if ($config->get('system.twig.undefined_functions')) { + $this->twig->registerUndefinedFunctionCallback(function ($name) { + if (function_exists($name)) { + return new \Twig_Function_Function($name); + } + + return new \Twig_Function_Function(function () { + }); + }); + } + + if ($config->get('system.twig.undefined_filters')) { + $this->twig->registerUndefinedFilterCallback(function ($name) { + if (function_exists($name)) { + return new \Twig_Filter_Function($name); + } + + return new \Twig_Filter_Function(function () { + }); + }); + } + + $this->grav->fireEvent('onTwigInitialized'); + + // set default date format if set in config + if ($config->get('system.pages.dateformat.long')) { + $this->twig->getExtension('core')->setDateFormat($config->get('system.pages.dateformat.long')); + } + // enable the debug extension if required + if ($config->get('system.twig.debug')) { + $this->twig->addExtension(new \Twig_Extension_Debug()); + } + $this->twig->addExtension(new TwigExtension()); + + $this->grav->fireEvent('onTwigExtensions'); + + /** @var Pages $pages */ + $pages = $this->grav['pages']; + + // Set some standard variables for twig + $this->twig_vars = $this->twig_vars + [ + 'config' => $config, + 'system' => $config->get('system'), + 'theme' => $config->get('theme'), + 'site' => $config->get('site'), + 'uri' => $this->grav['uri'], + 'assets' => $this->grav['assets'], + 'taxonomy' => $this->grav['taxonomy'], + 'browser' => $this->grav['browser'], + 'base_dir' => rtrim(ROOT_DIR, '/'), + 'home_url' => $pages->homeUrl($active_language), + 'base_url' => $pages->baseUrl($active_language), + 'base_url_absolute' => $pages->baseUrl($active_language, true), + 'base_url_relative' => $pages->baseUrl($active_language, false), + 'base_url_simple' => $this->grav['base_url'], + 'theme_dir' => $locator->findResource('theme://'), + 'theme_url' => $this->grav['base_url'] . '/' . $locator->findResource('theme://', false), + 'html_lang' => $this->grav['language']->getActive() ?: $config->get('site.default_lang', 'en'), + 'language_codes' => new LanguageCodes, + ]; + } + } + + /** + * @return \Twig_Environment + */ + public function twig() + { + return $this->twig; + } + + /** + * @return \Twig_Loader_Filesystem + */ + public function loader() + { + return $this->loader; + } + + /** + * Adds or overrides a template. + * + * @param string $name The template name + * @param string $template The template source + */ + public function setTemplate($name, $template) + { + $this->loaderArray->setTemplate($name, $template); + } + + /** + * Twig process that renders a page item. It supports two variations: + * 1) Handles modular pages by rendering a specific page based on its modular twig template + * 2) Renders individual page items for twig processing before the site rendering + * + * @param Page $item The page item to render + * @param string $content Optional content override + * + * @return string The rendered output + * @throws \Twig_Error_Loader + */ + public function processPage(Page $item, $content = null) + { + $content = $content !== null ? $content : $item->content(); + + // override the twig header vars for local resolution + $this->grav->fireEvent('onTwigPageVariables', new Event(['page' => $item])); + $twig_vars = $this->twig_vars; + + $twig_vars['page'] = $item; + $twig_vars['media'] = $item->media(); + $twig_vars['header'] = $item->header(); + + $local_twig = clone($this->twig); + + try { + // Process Modular Twig + if ($item->modularTwig()) { + $twig_vars['content'] = $content; + $template = $item->template() . TEMPLATE_EXT; + $output = $content = $local_twig->render($template, $twig_vars); + } + + // Process in-page Twig + if ($item->shouldProcess('twig')) { + $name = '@Page:' . $item->path(); + $this->setTemplate($name, $content); + $output = $local_twig->render($name, $twig_vars); + } + + } catch (\Twig_Error_Loader $e) { + throw new \RuntimeException($e->getRawMessage(), 404, $e); + } + + return $output; + } + + /** + * Process a Twig template directly by using a template name + * and optional array of variables + * + * @param string $template template to render with + * @param array $vars Optional variables + * + * @return string + */ + public function processTemplate($template, $vars = []) + { + // override the twig header vars for local resolution + $this->grav->fireEvent('onTwigTemplateVariables'); + $vars += $this->twig_vars; + + try { + $output = $this->twig->render($template, $vars); + } catch (\Twig_Error_Loader $e) { + throw new \RuntimeException($e->getRawMessage(), 404, $e); + } + + return $output; + + } + + + /** + * Process a Twig template directly by using a Twig string + * and optional array of variables + * + * @param string $string string to render. + * @param array $vars Optional variables + * + * @return string + */ + public function processString($string, array $vars = []) + { + // override the twig header vars for local resolution + $this->grav->fireEvent('onTwigStringVariables'); + $vars += $this->twig_vars; + + $name = '@Var:' . $string; + $this->setTemplate($name, $string); + + try { + $output = $this->twig->render($name, $vars); + } catch (\Twig_Error_Loader $e) { + throw new \RuntimeException($e->getRawMessage(), 404, $e); + } + + return $output; + } + + /** + * 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, array $vars = []) + { + // set the page now its been processed + $this->grav->fireEvent('onTwigSiteVariables'); + $pages = $this->grav['pages']; + $page = $this->grav['page']; + $content = $page->content(); + + $twig_vars = $this->twig_vars; + + $twig_vars['theme'] = $this->grav['config']->get('theme'); + $twig_vars['pages'] = $pages->root(); + $twig_vars['page'] = $page; + $twig_vars['header'] = $page->header(); + $twig_vars['media'] = $page->media(); + $twig_vars['content'] = $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, $vars + $twig_vars); + } catch (\Twig_Error_Loader $e) { + $error_msg = $e->getMessage(); + // Try html version of this template if initial template was NOT html + if ($ext != '.html' . TWIG_EXT) { + try { + $page->templateFormat('html'); + $output = $this->twig->render($page->template() . '.html' . TWIG_EXT, $vars + $twig_vars); + } catch (\Twig_Error_Loader $e) { + throw new \RuntimeException($error_msg, 400, $e); + } + } else { + throw new \RuntimeException($error_msg, 400, $e); + } + } + + return $output; + } + + /** + * Wraps the Twig_Loader_Filesystem addPath method (should be used only in `onTwigLoader()` event + * @param $template_path + * @param null $namespace + */ + public function addPath($template_path, $namespace = '__main__') + { + $this->loader->addPath($template_path, $namespace); + } + + /** + * Wraps the Twig_Loader_Filesystem prependPath method (should be used only in `onTwigLoader()` event + * @param $template_path + * @param null $namespace + */ + public function prependPath($template_path, $namespace = '__main__') + { + $this->loader->prependPath($template_path, $namespace); + } + + /** + * Simple helper method to get the twig template if it has already been set, else return + * the one being passed in + * + * @param string $template the template name + * + * @return string the template name + */ + public function template($template) + { + if (isset($this->template)) { + return $this->template; + } else { + return $template; + } + } + + /** + * Overrides the autoescape setting + * + * @param boolean $state + */ + public function setAutoescape($state) { + $this->autoescape = (bool) $state; + } +} diff --git a/system/src/Grav/Common/Twig/TwigEnvironment.php b/system/src/Grav/Common/Twig/TwigEnvironment.php new file mode 100644 index 0000000..66ca8bf --- /dev/null +++ b/system/src/Grav/Common/Twig/TwigEnvironment.php @@ -0,0 +1,14 @@ +grav = Grav::instance(); + $this->debugger = isset($this->grav['debugger']) ? $this->grav['debugger'] : null; + $this->config = $this->grav['config']; + } + + /** + * Register some standard globals + * + * @return array + */ + public function getGlobals() + { + return [ + 'grav' => $this->grav, + ]; + } + + /** + * Return a list of all filters. + * + * @return array + */ + public function getFilters() + { + return [ + new \Twig_SimpleFilter('*ize', [$this, 'inflectorFilter']), + new \Twig_SimpleFilter('absolute_url', [$this, 'absoluteUrlFilter']), + new \Twig_SimpleFilter('contains', [$this, 'containsFilter']), + new \Twig_SimpleFilter('chunk_split', [$this, 'chunkSplitFilter']), + new \Twig_SimpleFilter('nicenumber', [$this, 'niceNumberFunc']), + new \Twig_SimpleFilter('nicefilesize', [$this, 'niceFilesizeFunc']), + new \Twig_SimpleFilter('nicetime', [$this, 'nicetimeFunc']), + new \Twig_SimpleFilter('defined', [$this, 'definedDefaultFilter']), + new \Twig_SimpleFilter('ends_with', [$this, 'endsWithFilter']), + new \Twig_SimpleFilter('fieldName', [$this, 'fieldNameFilter']), + new \Twig_SimpleFilter('ksort', [$this, 'ksortFilter']), + new \Twig_SimpleFilter('ltrim', [$this, 'ltrimFilter']), + new \Twig_SimpleFilter('markdown', [$this, 'markdownFunction']), + new \Twig_SimpleFilter('md5', [$this, 'md5Filter']), + new \Twig_SimpleFilter('base32_encode', [$this, 'base32EncodeFilter']), + new \Twig_SimpleFilter('base32_decode', [$this, 'base32DecodeFilter']), + new \Twig_SimpleFilter('base64_encode', [$this, 'base64EncodeFilter']), + new \Twig_SimpleFilter('base64_decode', [$this, 'base64DecodeFilter']), + new \Twig_SimpleFilter('randomize', [$this, 'randomizeFilter']), + new \Twig_SimpleFilter('modulus', [$this, 'modulusFilter']), + new \Twig_SimpleFilter('rtrim', [$this, 'rtrimFilter']), + new \Twig_SimpleFilter('pad', [$this, 'padFilter']), + new \Twig_SimpleFilter('regex_replace', [$this, 'regexReplace']), + new \Twig_SimpleFilter('safe_email', [$this, 'safeEmailFilter']), + new \Twig_SimpleFilter('safe_truncate', ['\Grav\Common\Utils', 'safeTruncate']), + new \Twig_SimpleFilter('safe_truncate_html', ['\Grav\Common\Utils', 'safeTruncateHTML']), + new \Twig_SimpleFilter('sort_by_key', [$this, 'sortByKeyFilter']), + new \Twig_SimpleFilter('starts_with', [$this, 'startsWithFilter']), + new \Twig_SimpleFilter('t', [$this, 'translate']), + new \Twig_SimpleFilter('tl', [$this, 'translateLanguage']), + new \Twig_SimpleFilter('ta', [$this, 'translateArray']), + new \Twig_SimpleFilter('truncate', ['\Grav\Common\Utils', 'truncate']), + new \Twig_SimpleFilter('truncate_html', ['\Grav\Common\Utils', 'truncateHTML']), + new \Twig_SimpleFilter('json_decode', [$this, 'jsonDecodeFilter']), + new \Twig_SimpleFilter('array_unique', 'array_unique'), + new \Twig_SimpleFilter('basename', 'basename'), + new \Twig_SimpleFilter('dirname', 'dirname'), + new \Twig_SimpleFilter('print_r', 'print_r'), + new \Twig_SimpleFilter('yaml_encode', [$this, 'yamlEncodeFilter']), + new \Twig_SimpleFilter('yaml_decode', [$this, 'yamlDecodeFilter']), + ]; + } + + /** + * Return a list of all functions. + * + * @return array + */ + public function getFunctions() + { + return [ + new \Twig_SimpleFunction('array', [$this, 'arrayFunc']), + new \Twig_SimpleFunction('array_key_value', [$this, 'arrayKeyValueFunc']), + new \Twig_SimpleFunction('array_key_exists', 'array_key_exists'), + new \Twig_SimpleFunction('array_unique', 'array_unique'), + new \Twig_SimpleFunction('array_intersect', [$this, 'arrayIntersectFunc']), + new \Twig_simpleFunction('authorize', [$this, 'authorize']), + new \Twig_SimpleFunction('debug', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]), + new \Twig_SimpleFunction('dump', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]), + new \Twig_SimpleFunction('vardump', [$this, 'vardumpFunc']), + new \Twig_SimpleFunction('print_r', 'print_r'), + new \Twig_SimpleFunction('http_response_code', 'http_response_code'), + new \Twig_SimpleFunction('evaluate', [$this, 'evaluateStringFunc'], ['needs_context' => true]), + new \Twig_SimpleFunction('evaluate_twig', [$this, 'evaluateTwigFunc'], ['needs_context' => true]), + new \Twig_SimpleFunction('gist', [$this, 'gistFunc']), + new \Twig_SimpleFunction('nonce_field', [$this, 'nonceFieldFunc']), + new \Twig_SimpleFunction('pathinfo', 'pathinfo'), + new \Twig_simpleFunction('random_string', [$this, 'randomStringFunc']), + new \Twig_SimpleFunction('repeat', [$this, 'repeatFunc']), + new \Twig_SimpleFunction('regex_replace', [$this, 'regexReplace']), + new \Twig_SimpleFunction('regex_filter', [$this, 'regexFilter']), + new \Twig_SimpleFunction('string', [$this, 'stringFunc']), + new \Twig_simpleFunction('t', [$this, 'translate']), + new \Twig_simpleFunction('tl', [$this, 'translateLanguage']), + new \Twig_simpleFunction('ta', [$this, 'translateArray']), + new \Twig_SimpleFunction('url', [$this, 'urlFunc']), + new \Twig_SimpleFunction('json_decode', [$this, 'jsonDecodeFilter']), + new \Twig_SimpleFunction('get_cookie', [$this, 'getCookie']), + new \Twig_SimpleFunction('redirect_me', [$this, 'redirectFunc']), + new \Twig_SimpleFunction('range', [$this, 'rangeFunc']), + new \Twig_SimpleFunction('isajaxrequest', [$this, 'isAjaxFunc']), + new \Twig_SimpleFunction('exif', [$this, 'exifFunc']), + new \Twig_SimpleFunction('media_directory', [$this, 'mediaDirFunc']), + new \Twig_SimpleFunction('body_class', [$this, 'bodyClassFunc']), + new \Twig_SimpleFunction('theme_var', [$this, 'themeVarFunc']), + new \Twig_SimpleFunction('header_var', [$this, 'pageHeaderVarFunc']), + new \Twig_SimpleFunction('read_file', [$this, 'readFileFunc']), + new \Twig_SimpleFunction('nicenumber', [$this, 'niceNumberFunc']), + new \Twig_SimpleFunction('nicefilesize', [$this, 'niceFilesizeFunc']), + new \Twig_SimpleFunction('nicetime', [$this, 'nicetimeFilter']), + + ]; + } + + /** + * @return array + */ + public function getTokenParsers() + { + return [ + new TwigTokenParserTryCatch(), + new TwigTokenParserScript(), + new TwigTokenParserStyle(), + new TwigTokenParserMarkdown(), + new TwigTokenParserSwitch(), + ]; + } + + /** + * Filters field name by changing dot notation into array notation. + * + * @param string $str + * + * @return string + */ + public function fieldNameFilter($str) + { + $path = explode('.', rtrim($str, '.')); + + return array_shift($path) . ($path ? '[' . implode('][', $path) . ']' : ''); + } + + /** + * Protects email address. + * + * @param string $str + * + * @return string + */ + public function safeEmailFilter($str) + { + $email = ''; + for ( $i = 0, $len = strlen( $str ); $i < $len; $i++ ) { + $j = mt_rand( 0, 1); + if ( $j === 0 ) { + $email .= '&#' . ord( $str[$i] ) . ';'; + } elseif ( $j === 1 ) { + $email .= $str[$i]; + } + } + + return str_replace( '@', '@', $email ); + } + + /** + * Returns array in a random order. + * + * @param array $original + * @param int $offset Can be used to return only slice of the array. + * + * @return array + */ + public function randomizeFilter($original, $offset = 0) + { + if (!is_array($original)) { + return $original; + } + + if ($original instanceof \Traversable) { + $original = iterator_to_array($original, false); + } + + $sorted = []; + $random = array_slice($original, $offset); + shuffle($random); + + $sizeOf = count($original); + for ($x = 0; $x < $sizeOf; $x++) { + if ($x < $offset) { + $sorted[] = $original[$x]; + } else { + $sorted[] = array_shift($random); + } + } + + return $sorted; + } + + /** + * Returns the modulus of an integer + * + * @param string|int $number + * @param int $divider + * @param array $items array of items to select from to return + * + * @return int + */ + public function modulusFilter($number, $divider, $items = null) + { + if (is_string($number)) { + $number = strlen($number); + } + + $remainder = $number % $divider; + + if (is_array($items)) { + if (isset($items[$remainder])) { + return $items[$remainder]; + } + + return $items[0]; + } + + return $remainder; + } + + /** + * Inflector supports following notations: + * + * `{{ 'person'|pluralize }} => people` + * `{{ 'shoes'|singularize }} => shoe` + * `{{ 'welcome page'|titleize }} => "Welcome Page"` + * `{{ 'send_email'|camelize }} => SendEmail` + * `{{ 'CamelCased'|underscorize }} => camel_cased` + * `{{ 'Something Text'|hyphenize }} => something-text` + * `{{ 'something_text_to_read'|humanize }} => "Something text to read"` + * `{{ '181'|monthize }} => 5` + * `{{ '10'|ordinalize }} => 10th` + * + * @param string $action + * @param string $data + * @param int $count + * + * @return mixed + */ + public function inflectorFilter($action, $data, $count = null) + { + $action = $action . 'ize'; + + $inflector = $this->grav['inflector']; + + if (\in_array( + $action, + ['titleize', 'camelize', 'underscorize', 'hyphenize', 'humanize', 'ordinalize', 'monthize'], + true + )) { + return $inflector->$action($data); + } + + if (\in_array($action, ['pluralize', 'singularize'], true)) { + if ($count) { + return $inflector->$action($data, $count); + } + + return $inflector->$action($data); + } + + return $data; + } + + /** + * Return MD5 hash from the input. + * + * @param string $str + * + * @return string + */ + public function md5Filter($str) + { + return md5($str); + } + + /** + * Return Base32 encoded string + * + * @param $str + * @return string + */ + public function base32EncodeFilter($str) + { + return Base32::encode($str); + } + + /** + * Return Base32 decoded string + * + * @param $str + * @return bool|string + */ + public function base32DecodeFilter($str) + { + return Base32::decode($str); + } + + /** + * Return Base64 encoded string + * + * @param $str + * @return string + */ + public function base64EncodeFilter($str) + { + return base64_encode($str); + } + + /** + * Return Base64 decoded string + * + * @param $str + * @return bool|string + */ + public function base64DecodeFilter($str) + { + return base64_decode($str); + } + + + /** + * Sorts a collection by key + * + * @param array $input + * @param string $filter + * @param int $direction + * @param int $sort_flags + * + * @return array + */ + public function sortByKeyFilter($input, $filter, $direction = SORT_ASC, $sort_flags = SORT_REGULAR) + { + return Utils::sortArrayByKey($input, $filter, $direction, $sort_flags); + } + + /** + * Return ksorted collection. + * + * @param array $array + * + * @return array + */ + public function ksortFilter($array) + { + if (null === $array) { + $array = []; + } + ksort($array); + + return $array; + } + + /** + * Wrapper for chunk_split() function + * + * @param $value + * @param $chars + * @param string $split + * @return string + */ + public function chunkSplitFilter($value, $chars, $split = '-') + { + return chunk_split($value, $chars, $split); + } + + /** + * determine if a string contains another + * + * @param String $haystack + * @param String $needle + * + * @return boolean + */ + public function containsFilter($haystack, $needle) + { + return (strpos($haystack, $needle) !== false); + } + + /** + * displays a facebook style 'time ago' formatted date/time + * + * @param $date + * @param $long_strings + * + * @return boolean + */ + public function nicetimeFunc($date, $long_strings = true) + { + if (empty($date)) { + return $this->grav['language']->translate('NICETIME.NO_DATE_PROVIDED', null, true); + } + + if ($long_strings) { + $periods = [ + "NICETIME.SECOND", + "NICETIME.MINUTE", + "NICETIME.HOUR", + "NICETIME.DAY", + "NICETIME.WEEK", + "NICETIME.MONTH", + "NICETIME.YEAR", + "NICETIME.DECADE" + ]; + } else { + $periods = [ + "NICETIME.SEC", + "NICETIME.MIN", + "NICETIME.HR", + "NICETIME.DAY", + "NICETIME.WK", + "NICETIME.MO", + "NICETIME.YR", + "NICETIME.DEC" + ]; + } + + $lengths = ["60", "60", "24", "7", "4.35", "12", "10"]; + + $now = time(); + + // check if unix timestamp + if ((string)(int)$date == $date) { + $unix_date = $date; + } else { + $unix_date = strtotime($date); + } + + // check validity of date + if (empty($unix_date)) { + return $this->grav['language']->translate('NICETIME.BAD_DATE', null, true); + } + + // is it future date or past date + if ($now > $unix_date) { + $difference = $now - $unix_date; + $tense = $this->grav['language']->translate('NICETIME.AGO', null, true); + + } else if ($now == $unix_date) { + $difference = $now - $unix_date; + $tense = $this->grav['language']->translate('NICETIME.JUST_NOW', null, false); + + } else { + $difference = $unix_date - $now; + $tense = $this->grav['language']->translate('NICETIME.FROM_NOW', null, true); + } + + for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) { + $difference /= $lengths[$j]; + } + + $difference = round($difference); + + if ($difference != 1) { + $periods[$j] .= '_PLURAL'; + } + + if ($this->grav['language']->getTranslation($this->grav['language']->getLanguage(), + $periods[$j] . '_MORE_THAN_TWO') + ) { + if ($difference > 2) { + $periods[$j] .= '_MORE_THAN_TWO'; + } + } + + $periods[$j] = $this->grav['language']->translate($periods[$j], null, true); + + if ($now == $unix_date) { + return "{$tense}"; + } + + return "$difference $periods[$j] {$tense}"; + } + + /** + * @param $string + * + * @return mixed + */ + public function absoluteUrlFilter($string) + { + $url = $this->grav['uri']->base(); + $string = preg_replace('/((?:href|src) *= *[\'"](?!(http|ftp)))/i', "$1$url", $string); + + return $string; + + } + + /** + * @param $string + * + * @param bool $block Block or Line processing + * @return mixed|string + */ + public function markdownFunction($string, $block = true) + { + $page = $this->grav['page']; + $defaults = $this->config->get('system.pages.markdown'); + + // Initialize the preferred variant of Parsedown + if ($defaults['extra']) { + $parsedown = new ParsedownExtra($page, $defaults); + } else { + $parsedown = new Parsedown($page, $defaults); + } + + if ($block) { + $string = $parsedown->text($string); + } else { + $string = $parsedown->line($string); + } + + + return $string; + } + + /** + * @param $haystack + * @param $needle + * + * @return bool + */ + public function startsWithFilter($haystack, $needle) + { + return Utils::startsWith($haystack, $needle); + } + + /** + * @param $haystack + * @param $needle + * + * @return bool + */ + public function endsWithFilter($haystack, $needle) + { + return Utils::endsWith($haystack, $needle); + } + + /** + * @param $value + * @param null $default + * + * @return null + */ + public function definedDefaultFilter($value, $default = null) + { + return null !== $value ? $value : $default; + } + + /** + * @param $value + * @param null $chars + * + * @return string + */ + public function rtrimFilter($value, $chars = null) + { + return rtrim($value, $chars); + } + + /** + * @param $value + * @param null $chars + * + * @return string + */ + public function ltrimFilter($value, $chars = null) + { + return ltrim($value, $chars); + } + + /** + * @return mixed + */ + public function translate() + { + return $this->grav['language']->translate(func_get_args()); + } + + /** + * Translate Strings + * + * @param $args + * @param array|null $languages + * @param bool $array_support + * @param bool $html_out + * @return mixed + */ + public function translateLanguage($args, array $languages = null, $array_support = false, $html_out = false) + { + return $this->grav['language']->translate($args, $languages, $array_support, $html_out); + } + + /** + * @param $key + * @param $index + * @param null $lang + * + * @return mixed + */ + public function translateArray($key, $index, $lang = null) + { + return $this->grav['language']->translateArray($key, $index, $lang); + } + + /** + * Repeat given string x times. + * + * @param string $input + * @param int $multiplier + * + * @return string + */ + public function repeatFunc($input, $multiplier) + { + return str_repeat($input, $multiplier); + } + + /** + * Return URL to the resource. + * + * @example {{ url('theme://images/logo.png')|default('http://www.placehold.it/150x100/f4f4f4') }} + * + * @param string $input Resource to be located. + * @param bool $domain True to include domain name. + * + * @return string|null Returns url to the resource or null if resource was not found. + */ + public function urlFunc($input, $domain = false) + { + return Utils::url($input, $domain); + } + + /** + * This function will evaluate Twig $twig through the $environment, and return its results. + * + * @param array $context + * @param string $twig + * @return mixed + */ + public function evaluateTwigFunc($context, $twig ) { + + $loader = new \Twig_Loader_Filesystem('.'); + $env = new \Twig_Environment($loader); + + $template = $env->createTemplate($twig); + return $template->render($context); +; + } + + /** + * This function will evaluate a $string through the $environment, and return its results. + * + * @param $context + * @param $string + * @return mixed + */ + public function evaluateStringFunc($context, $string ) + { + return $this->evaluateTwigFunc($context, "{{ $string }}"); + } + + + /** + * Based on Twig_Extension_Debug / twig_var_dump + * (c) 2011 Fabien Potencier + * + * @param \Twig_Environment $env + * @param $context + */ + public function dump(\Twig_Environment $env, $context) + { + if (!$env->isDebug() || !$this->debugger) { + return; + } + + $count = func_num_args(); + if (2 === $count) { + $data = []; + foreach ($context as $key => $value) { + if (is_object($value)) { + if (method_exists($value, 'toArray')) { + $data[$key] = $value->toArray(); + } else { + $data[$key] = "Object (" . get_class($value) . ")"; + } + } else { + $data[$key] = $value; + } + } + $this->debugger->addMessage($data, 'debug'); + } else { + for ($i = 2; $i < $count; $i++) { + $this->debugger->addMessage(func_get_arg($i), 'debug'); + } + } + } + + /** + * Output a Gist + * + * @param string $id + * @param string $file + * + * @return string + */ + public function gistFunc($id, $file = false) + { + $url = 'https://gist.github.com/' . $id . '.js'; + if ($file) { + $url .= '?file=' . $file; + } + return ''; + } + + /** + * Generate a random string + * + * @param int $count + * + * @return string + */ + public function randomStringFunc($count = 5) + { + return Utils::generateRandomString($count); + } + + /** + * Pad a string to a certain length with another string + * + * @param $input + * @param $pad_length + * @param string $pad_string + * @param int $pad_type + * + * @return string + */ + public static function padFilter($input, $pad_length, $pad_string = " ", $pad_type = STR_PAD_RIGHT) + { + return str_pad($input, (int)$pad_length, $pad_string, $pad_type); + } + + + /** + * Cast a value to array + * + * @param $value + * + * @return array + */ + public function arrayFunc($value) + { + return (array)$value; + } + + /** + * Workaround for twig associative array initialization + * Returns a key => val array + * + * @param string $key key of item + * @param string $val value of item + * @param array $current_array optional array to add to + * + * @return array + */ + public function arrayKeyValueFunc($key, $val, $current_array = null) + { + if (empty($current_array)) { + return array($key => $val); + } + + $current_array[$key] = $val; + return $current_array; + } + + /** + * Wrapper for array_intersect() method + * + * @param $array1 + * @param $array2 + * @return array + */ + public function arrayIntersectFunc($array1, $array2) + { + if ($array1 instanceof Collection && $array2 instanceof Collection) { + return $array1->intersect($array2); + } + + return array_intersect($array1, $array2); + } + + /** + * Returns a string from a value. If the value is array, return it json encoded + * + * @param $value + * + * @return string + */ + public function stringFunc($value) + { + if (is_array($value)) { //format the array as a string + return json_encode($value); + } + + return $value; + } + + /** + * Translate a string + * + * @return string + */ + public function translateFunc() + { + return $this->grav['language']->translate(func_get_args()); + } + + /** + * Authorize an action. Returns true if the user is logged in and + * has the right to execute $action. + * + * @param string|array $action An action or a list of actions. Each + * entry can be a string like 'group.action' + * or without dot notation an associative + * array. + * @return bool Returns TRUE if the user is authorized to + * perform the action, FALSE otherwise. + */ + public function authorize($action) + { + /** @var User $user */ + $user = $this->grav['user']; + + if (!$user->authenticated || (isset($user->authorized) && !$user->authorized)) { + return false; + } + + $action = (array) $action; + foreach ($action as $key => $perms) { + $prefix = is_int($key) ? '' : $key . '.'; + $perms = $prefix ? (array) $perms : [$perms => true]; + foreach ($perms as $action2 => $authenticated) { + if ($user->authorize($prefix . $action2)) { + return $authenticated; + } + } + } + + return false; + } + + /** + * Used to add a nonce to a form. Call {{ nonce_field('action') }} specifying a string representing the action. + * + * For maximum protection, ensure that the string representing the action is as specific as possible + * + * @param string $action the action + * @param string $nonceParamName a custom nonce param name + * + * @return string the nonce input field + */ + public function nonceFieldFunc($action, $nonceParamName = 'nonce') + { + $string = ''; + + return $string; + } + + /** + * Decodes string from JSON. + * + * @param string $str + * @param bool $assoc + * @param int $depth + * @param int $options + * @return array + */ + public function jsonDecodeFilter($str, $assoc = false, $depth = 512, $options = 0) + { + return json_decode(html_entity_decode($str), $assoc, $depth, $options); + } + + /** + * Used to retrieve a cookie value + * + * @param string $key The cookie name to retrieve + * + * @return mixed + */ + public function getCookie($key) + { + return filter_input(INPUT_COOKIE, $key, FILTER_SANITIZE_STRING); + } + + /** + * Twig wrapper for PHP's preg_replace method + * + * @param mixed $subject the content to perform the replacement on + * @param mixed $pattern the regex pattern to use for matches + * @param mixed $replace the replacement value either as a string or an array of replacements + * @param int $limit the maximum possible replacements for each pattern in each subject + * + * @return mixed the resulting content + */ + public function regexReplace($subject, $pattern, $replace, $limit = -1) + { + return preg_replace($pattern, $replace, $subject, $limit); + } + + /** + * Twig wrapper for PHP's preg_grep method + * + * @param $array + * @param $regex + * @param int $flags + * @return array + */ + public function regexFilter($array, $regex, $flags = 0) { + return preg_grep($regex, $array, $flags); + } + + /** + * redirect browser from twig + * + * @param string $url the url to redirect to + * @param int $statusCode statusCode, default 303 + */ + public function redirectFunc($url, $statusCode = 303) + { + header('Location: ' . $url, true, $statusCode); + die(); + } + + /** + * Generates an array containing a range of elements, optionally stepped + * + * @param int $start Minimum number, default 0 + * @param int $end Maximum number, default `getrandmax()` + * @param int $step Increment between elements in the sequence, default 1 + * + * @return array + */ + public function rangeFunc($start = 0, $end = 100, $step = 1) + { + return range($start, $end, $step); + } + + /** + * Check if HTTP_X_REQUESTED_WITH has been set to xmlhttprequest, + * in which case we may unsafely assume ajax. Non critical use only. + * + * @return true if HTTP_X_REQUESTED_WITH exists and has been set to xmlhttprequest + */ + public function isAjaxFunc() + { + return ( + !empty($_SERVER['HTTP_X_REQUESTED_WITH']) + && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'); + } + + /** + * Get's the Exif data for a file + * + * @param $image + * @param bool $raw + * @return mixed + */ + public function exifFunc($image, $raw = false) + { + if (isset($this->grav['exif'])) { + + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + + if ($locator->isStream($image)) { + $image = $locator->findResource($image); + } + + $exif_reader = $this->grav['exif']->getReader(); + + if (file_exists($image) && $this->config->get('system.media.auto_metadata_exif') && $exif_reader) { + + $exif_data = $exif_reader->read($image); + + if ($exif_data) { + if ($raw) { + return $exif_data->getRawData(); + } + + return $exif_data->getData(); + } + } + } + + return null; + } + + /** + * Simple function to read a file based on a filepath and output it + * + * @param $filepath + * @return bool|string + */ + public function readFileFunc($filepath) + { + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + + if ($locator->isStream($filepath)) { + $filepath = $locator->findResource($filepath); + } + + if (file_exists($filepath)) { + return file_get_contents($filepath); + } + + return false; + } + + /** + * Process a folder as Media and return a media object + * + * @param $media_dir + * @return Media|null + */ + public function mediaDirFunc($media_dir) + { + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + + if ($locator->isStream($media_dir)) { + $media_dir = $locator->findResource($media_dir); + } + + if (file_exists($media_dir)) { + return new Media($media_dir); + } + + return null; + } + + /** + * Dump a variable to the browser + * + * @param $var + */ + public function vardumpFunc($var) + { + var_dump($var); + } + + /** + * Returns a nicer more readable filesize based on bytes + * + * @param $bytes + * @return string + */ + public function niceFilesizeFunc($bytes) + { + if ($bytes >= 1073741824) + { + $bytes = number_format($bytes / 1073741824, 2) . ' GB'; + } + elseif ($bytes >= 1048576) + { + $bytes = number_format($bytes / 1048576, 2) . ' MB'; + } + elseif ($bytes >= 1024) + { + $bytes = number_format($bytes / 1024, 1) . ' KB'; + } + elseif ($bytes > 1) + { + $bytes = $bytes . ' bytes'; + } + elseif ($bytes == 1) + { + $bytes = $bytes . ' byte'; + } + else + { + $bytes = '0 bytes'; + } + + return $bytes; + } + + + /** + * Returns a nicer more readable number + * + * @param int|float $n + * @return bool|string + */ + public function niceNumberFunc($n) + { + // first strip any formatting; + $n = 0 + str_replace(',', '', $n); + + // is this a number? + if (!is_numeric($n)) { + return false; + } + + // now filter it; + if ($n > 1000000000000) { + return round(($n/1000000000000), 2).' t'; + } + if ($n > 1000000000) { + return round(($n/1000000000), 2).' b'; + } + if ($n > 1000000) { + return round(($n/1000000), 2).' m'; + } + if ($n > 1000) { + return round(($n/1000), 2).' k'; + } + + return number_format($n); + } + + /** + * Get a theme variable + * + * @param $var + * @param bool $default + * @return string + */ + public function themeVarFunc($var, $default = null) + { + $header = $this->grav['page']->header(); + $header_classes = isset($header->$var) ? $header->$var : null; + return $header_classes ?: $this->config->get('theme.' . $var, $default); + } + + /** + * takes an array of classes, and if they are not set on body_classes + * look to see if they are set in theme config + * + * @param $classes + * @return string + */ + public function bodyClassFunc($classes) + { + + $header = $this->grav['page']->header(); + $body_classes = isset($header->body_classes) ? $header->body_classes : ''; + + foreach ((array)$classes as $class) { + if (!empty($body_classes) && Utils::contains($body_classes, $class)) { + continue; + } + + $val = $this->config->get('theme.' . $class, false) ? $class : false; + $body_classes .= $val ? ' ' . $val : ''; + } + + return $body_classes; + } + + /** + * Look for a page header variable in an array of pages working its way through until a value is found + * + * @param $var + * @param null $pages + * @return mixed + */ + public function pageHeaderVarFunc($var, $pages = null) + { + if ($pages === null) { + $pages = $this->grav['page']; + } + + // Make sure pages are an array + if (!is_array($pages)) { + $pages = array($pages); + } + + // Loop over pages and look for header vars + foreach ($pages as $page) { + if (is_string($page)) { + $page = $this->grav['pages']->find($page); + } + + if ($page) { + $header = $page->header(); + if (isset($header->$var)) { + return $header->$var; + } + } + } + + return null; + } + + /** + * Dump/Encode data into YAML format + * + * @param $data + * @return mixed + */ + public function yamlEncodeFilter($data) + { + return Yaml::dump($data, 10); + } + + /** + * Decode/Parse data from YAML format + * + * @param $data + * @return mixed + */ + public function yamlDecodeFilter($data) + { + return Yaml::parse($data); + } +} diff --git a/system/src/Grav/Common/Twig/WriteCacheFileTrait.php b/system/src/Grav/Common/Twig/WriteCacheFileTrait.php new file mode 100644 index 0000000..c413ca6 --- /dev/null +++ b/system/src/Grav/Common/Twig/WriteCacheFileTrait.php @@ -0,0 +1,46 @@ +get('system.twig.umask_fix', false); + } + + if (self::$umask) { + if (!is_dir(dirname($file))) { + $old = umask(0002); + mkdir(dirname($file), 0777, true); + umask($old); + } + parent::writeCacheFile($file, $content); + chmod($file, 0775); + } else { + parent::writeCacheFile($file, $content); + } + } +} diff --git a/system/src/Grav/Common/Uri.php b/system/src/Grav/Common/Uri.php new file mode 100644 index 0000000..412a3ab --- /dev/null +++ b/system/src/Grav/Common/Uri.php @@ -0,0 +1,1352 @@ +createFromString($env); + } else { + $this->createFromEnvironment(is_array($env) ? $env : $_SERVER); + } + } + + /** + * Initialize the URI class with a url passed via parameter. + * Used for testing purposes. + * + * @param string $url the URL to use in the class + * + * @return $this + */ + public function initializeWithUrl($url = '') + { + if ($url) { + $this->createFromString($url); + } + + return $this; + } + + /** + * Initialize the URI class by providing url and root_path arguments + * + * @param string $url + * @param string $root_path + * + * @return $this + */ + public function initializeWithUrlAndRootPath($url, $root_path) + { + $this->initializeWithUrl($url); + $this->root_path = $root_path; + + return $this; + } + + /** + * Validate a hostname + * + * @param string $hostname The hostname + * + * @return boolean + */ + public function validateHostname($hostname) + { + return (bool)preg_match(static::HOSTNAME_REGEX, $hostname); + } + + /** + * Initializes the URI object based on the url set on the object + */ + public function init() + { + $grav = Grav::instance(); + + /** @var Config $config */ + $config = $grav['config']; + + /** @var Language $language */ + $language = $grav['language']; + + // add the port to the base for non-standard ports + if ($this->port !== null && $config->get('system.reverse_proxy_setup') === false) { + $this->base .= ':' . (string)$this->port; + } + + // Handle custom base + $custom_base = rtrim($grav['config']->get('system.custom_base_url'), '/'); + + if ($custom_base) { + $custom_parts = parse_url($custom_base); + $orig_root_path = $this->root_path; + $this->root_path = isset($custom_parts['path']) ? rtrim($custom_parts['path'], '/') : ''; + if (isset($custom_parts['scheme'])) { + $this->base = $custom_parts['scheme'] . '://' . $custom_parts['host']; + $this->root = $custom_base; + } else { + $this->root = $this->base . $this->root_path; + } + $this->uri = Utils::replaceFirstOccurrence($orig_root_path, $this->root_path, $this->uri); + } else { + $this->root = $this->base . $this->root_path; + } + + $this->url = $this->base . $this->uri; + + $uri = str_replace(static::filterPath($this->root), '', $this->url); + + + // remove the setup.php based base if set: + $setup_base = $grav['pages']->base(); + if ($setup_base) { + $uri = str_replace($setup_base, '', $uri); + } + + // If configured to, redirect trailing slash URI's with a 302 redirect + $redirect = str_replace($this->root, '', rtrim($uri, '/')); + if ($redirect && $uri !== '/' && $redirect !== $this->base() && $config->get('system.pages.redirect_trailing_slash', false) && Utils::endsWith($uri, '/')) { + $grav->redirect($redirect, 302); + } + + // process params + $uri = $this->processParams($uri, $config->get('system.param_sep')); + + // set active language + $uri = $language->setActiveFromUri($uri); + + // split the URL and params + $bits = parse_url($uri); + + //process fragment + if (isset($bits['fragment'])) { + $this->fragment = $bits['fragment']; + } + + // Get the path. If there's no path, make sure pathinfo() still returns dirname variable + $path = isset($bits['path']) ? $bits['path'] : '/'; + + // remove the extension if there is one set + $parts = pathinfo($path); + + // set the original basename + $this->basename = $parts['basename']; + + // set the extension + if (isset($parts['extension'])) { + $this->extension = $parts['extension']; + } + + $valid_page_types = implode('|', $config->get('system.pages.types')); + + // Strip the file extension for valid page types + if (preg_match('/\.(' . $valid_page_types . ')$/', $parts['basename'])) { + $path = rtrim(str_replace(DIRECTORY_SEPARATOR, DS, $parts['dirname']), DS) . '/' . $parts['filename']; + } + + // set the new url + $this->url = $this->root . $path; + $this->path = static::cleanPath($path); + $this->content_path = trim(str_replace($this->base, '', $this->path), '/'); + if ($this->content_path !== '') { + $this->paths = explode('/', $this->content_path); + } + + // Set some Grav stuff + $grav['base_url_absolute'] = $grav['config']->get('system.custom_base_url') ?: $this->rootUrl(true); + $grav['base_url_relative'] = $this->rootUrl(false); + $grav['base_url'] = $grav['config']->get('system.absolute_urls') ? $grav['base_url_absolute'] : $grav['base_url_relative']; + + RouteFactory::setRoot($this->root_path); + RouteFactory::setLanguage($language->getLanguageURLPrefix()); + } + + /** + * Return URI path. + * + * @param string $id + * + * @return string|string[] + */ + public function paths($id = null) + { + if ($id !== null) { + return $this->paths[$id]; + } + + return $this->paths; + } + + /** + * Return route to the current URI. By default route doesn't include base path. + * + * @param bool $absolute True to include full path. + * @param bool $domain True to include domain. Works only if first parameter is also true. + * + * @return string + */ + public function route($absolute = false, $domain = false) + { + return ($absolute ? $this->rootUrl($domain) : '') . '/' . implode('/', $this->paths); + } + + /** + * Return full query string or a single query attribute. + * + * @param string $id Optional attribute. Get a single query attribute if set + * @param bool $raw If true and $id is not set, return the full query array. Otherwise return the query string + * + * @return string|array Returns an array if $id = null and $raw = true + */ + public function query($id = null, $raw = false) + { + if ($id !== null) { + return isset($this->queries[$id]) ? $this->queries[$id] : null; + } + + if ($raw) { + return $this->queries; + } + + if (!$this->queries) { + return ''; + } + + return http_build_query($this->queries); + } + + /** + * Return all or a single query parameter as a URI compatible string. + * + * @param string $id Optional parameter name. + * @param boolean $array return the array format or not + * + * @return null|string|array + */ + public function params($id = null, $array = false) + { + $config = Grav::instance()['config']; + $sep = $config->get('system.param_sep'); + + $params = null; + if ($id === null) { + if ($array) { + return $this->params; + } + $output = []; + foreach ($this->params as $key => $value) { + $output[] = "{$key}{$sep}{$value}"; + $params = '/' . implode('/', $output); + } + } elseif (isset($this->params[$id])) { + if ($array) { + return $this->params[$id]; + } + $params = "/{$id}{$sep}{$this->params[$id]}"; + } + + return $params; + } + + /** + * Get URI parameter. + * + * @param string $id + * + * @return bool|string + */ + public function param($id) + { + if (isset($this->params[$id])) { + return html_entity_decode(rawurldecode($this->params[$id])); + } + + return false; + } + + /** + * Gets the Fragment portion of a URI (eg #target) + * + * @param string $fragment + * + * @return string|null + */ + public function fragment($fragment = null) + { + if ($fragment !== null) { + $this->fragment = $fragment; + } + return $this->fragment; + } + + /** + * Return URL. + * + * @param bool $include_host Include hostname. + * + * @return string + */ + public function url($include_host = false) + { + if ($include_host) { + return $this->url; + } + + $url = str_replace($this->base, '', rtrim($this->url, '/')); + + return $url ?: '/'; + } + + /** + * Return the Path + * + * @return String The path of the URI + */ + public function path() + { + return $this->path; + } + + /** + * Return the Extension of the URI + * + * @param string|null $default + * + * @return string The extension of the URI + */ + public function extension($default = null) + { + if (!$this->extension) { + $this->extension = $default; + } + + return $this->extension; + } + + /** + * Return the scheme of the URI + * + * @param bool $raw + * @return string The scheme of the URI + */ + public function scheme($raw = false) + { + if (!$raw) { + $scheme = ''; + if ($this->scheme) { + $scheme = $this->scheme . '://'; + } elseif ($this->host) { + $scheme = '//'; + } + + return $scheme; + } + + return $this->scheme; + } + + + /** + * Return the host of the URI + * + * @return string|null The host of the URI + */ + public function host() + { + return $this->host; + } + + /** + * Return the port number if it can be figured out + * + * @param bool $raw + * @return int|null + */ + public function port($raw = false) + { + $port = $this->port; + // If not in raw mode and port is not set, figure it out from scheme. + if (!$raw && $port === null) { + if ($this->scheme === 'http') { + $this->port = 80; + } elseif ($this->scheme === 'https') { + $this->port = 443; + } + } + + return $this->port; + } + + /** + * Return user + * + * @return string|null + */ + public function user() + { + return $this->user; + } + + /** + * Return password + * + * @return string|null + */ + public function password() + { + return $this->password; + } + + /** + * Gets the environment name + * + * @return String + */ + public function environment() + { + return $this->env; + } + + + /** + * Return the basename of the URI + * + * @return String The basename of the URI + */ + public function basename() + { + return $this->basename; + } + + /** + * Return the full uri + * + * @param bool $include_root + * @return mixed + */ + public function uri($include_root = true) + { + if ($include_root) { + return $this->uri; + } else { + $uri = str_replace($this->root_path, '', $this->uri); + return $uri; + } + + } + + /** + * Return the base of the URI + * + * @return String The base of the URI + */ + public function base() + { + return $this->base; + } + + /** + * Return the base relative URL including the language prefix + * or the base relative url if multi-language is not enabled + * + * @return String The base of the URI + */ + public function baseIncludingLanguage() + { + $grav = Grav::instance(); + + // Link processing should prepend language + $language = $grav['language']; + $language_append = ''; + if ($language->enabled()) { + $language_append = $language->getLanguageURLPrefix(); + } + + $base = $grav['base_url_relative']; + + return rtrim($base . $grav['pages']->base(), '/') . $language_append; + } + + /** + * Return root URL to the site. + * + * @param bool $include_host Include hostname. + * + * @return mixed + */ + public function rootUrl($include_host = false) + { + if ($include_host) { + return $this->root; + } + + return str_replace($this->base, '', $this->root); + } + + /** + * Return current page number. + * + * @return int + */ + public function currentPage() + { + return isset($this->params['page']) ? $this->params['page'] : 1; + } + + /** + * Return relative path to the referrer defaulting to current or given page. + * + * @param string $default + * @param string $attributes + * + * @return string + */ + public function referrer($default = null, $attributes = null) + { + $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null; + + // Check that referrer came from our site. + $root = $this->rootUrl(true); + if ($referrer) { + // Referrer should always have host set and it should come from the same base address. + if (stripos($referrer, $root) !== 0) { + $referrer = null; + } + } + + if (!$referrer) { + $referrer = $default ?: $this->route(true, true); + } + + if ($attributes) { + $referrer .= $attributes; + } + + // Return relative path. + return substr($referrer, strlen($root)); + } + + public function __toString() + { + return static::buildUrl($this->toArray()); + } + + public function toArray() + { + return [ + 'scheme' => $this->scheme, + 'host' => $this->host, + 'port' => $this->port, + 'user' => $this->user, + 'pass' => $this->password, + 'path' => $this->path, + 'params' => $this->params, + 'query' => $this->query, + 'fragment' => $this->fragment + ]; + } + + /** + * Calculate the parameter regex based on the param_sep setting + * + * @return string + */ + public static function paramsRegex() + { + return '/\/([^\:\#\/\?]*' . Grav::instance()['config']->get('system.param_sep') . '[^\:\#\/\?]*)/'; + } + + /** + * Return the IP address of the current user + * + * @return string ip address + */ + public static function ip() + { + if (getenv('HTTP_CLIENT_IP')) { + $ip = getenv('HTTP_CLIENT_IP'); + } elseif (getenv('HTTP_X_FORWARDED_FOR')) { + $ip = getenv('HTTP_X_FORWARDED_FOR'); + } elseif (getenv('HTTP_X_FORWARDED')) { + $ip = getenv('HTTP_X_FORWARDED'); + } elseif (getenv('HTTP_FORWARDED_FOR')) { + $ip = getenv('HTTP_FORWARDED_FOR'); + } elseif (getenv('HTTP_FORWARDED')) { + $ip = getenv('HTTP_FORWARDED'); + } elseif (getenv('REMOTE_ADDR')){ + $ip = getenv('REMOTE_ADDR'); + } else { + $ip = 'UNKNOWN'; + } + + return $ip; + + } + /** + + * Returns current Uri. + * + * @return \Grav\Framework\Uri\Uri + */ + public static function getCurrentUri() + { + if (!static::$currentUri) { + static::$currentUri = UriFactory::createFromEnvironment($_SERVER); + } + + return static::$currentUri; + } + + /** + * Returns current route. + * + * @return \Grav\Framework\Route\Route + */ + public static function getCurrentRoute() + { + if (!static::$currentRoute) { + $uri = Grav::instance()['uri']; + static::$currentRoute = RouteFactory::createFromParts($uri->toArray()); + } + + return static::$currentRoute; + } + + /** + * Is this an external URL? if it starts with `http` then yes, else false + * + * @param string $url the URL in question + * + * @return boolean is eternal state + */ + public static function isExternal($url) + { + return Utils::startsWith($url, 'http'); + } + + /** + * The opposite of built-in PHP method parse_url() + * + * @param array $parsed_url + * + * @return string + */ + public static function buildUrl($parsed_url) + { + $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : (isset($parsed_url['host']) ? '//' : ''); + $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; + $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; + $user = isset($parsed_url['user']) ? $parsed_url['user'] : ''; + $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : ''; + $pass = ($user || $pass) ? "{$pass}@" : ''; + $path = isset($parsed_url['path']) ? $parsed_url['path'] : ''; + $path = !empty($parsed_url['params']) ? rtrim($path, '/') . static::buildParams($parsed_url['params']) : $path; + $query = !empty($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; + $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; + + return "{$scheme}{$user}{$pass}{$host}{$port}{$path}{$query}{$fragment}"; + } + + /** + * @param array $params + * @return string + */ + public static function buildParams(array $params) + { + if (!$params) { + return ''; + } + + $grav = Grav::instance(); + $sep = $grav['config']->get('system.param_sep'); + + $output = []; + foreach ($params as $key => $value) { + $output[] = "{$key}{$sep}{$value}"; + } + + return '/' . implode('/', $output); + } + + /** + * Converts links from absolute '/' or relative (../..) to a Grav friendly format + * + * @param Page $page the current page to use as reference + * @param string|array $url the URL as it was written in the markdown + * @param string $type the type of URL, image | link + * @param bool $absolute if null, will use system default, if true will use absolute links internally + * @param bool $route_only only return the route, not full URL path + * @return string the more friendly formatted url + */ + public static function convertUrl(Page $page, $url, $type = 'link', $absolute = false, $route_only = false) + { + $grav = Grav::instance(); + + $uri = $grav['uri']; + + // Link processing should prepend language + $language = $grav['language']; + $language_append = ''; + if ($type === 'link' && $language->enabled()) { + $language_append = $language->getLanguageURLPrefix(); + } + + // Handle Excerpt style $url array + $url_path = is_array($url) ? $url['path'] : $url; + + $external = false; + $base = $grav['base_url_relative']; + $base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append; + $pages_dir = $grav['locator']->findResource('page://'); + + // if absolute and starts with a base_url move on + if (isset($url['scheme']) && Utils::startsWith($url['scheme'], 'http')) { + $external = true; + } elseif ($url_path === '' && isset($url['fragment'])) { + $external = true; + } elseif ($url_path === '/' || ($base_url !== '' && Utils::startsWith($url_path, $base_url))) { + $url_path = $base_url . $url_path; + } else { + + // see if page is relative to this or absolute + if (Utils::startsWith($url_path, '/')) { + $normalized_url = Utils::normalizePath($base_url . $url_path); + $normalized_path = Utils::normalizePath($pages_dir . $url_path); + } else { + $page_route = ($page->home() && !empty($url_path)) ? $page->rawRoute() : $page->route(); + $normalized_url = $base_url . Utils::normalizePath($page_route . '/' . $url_path); + $normalized_path = Utils::normalizePath($page->path() . '/' . $url_path); + } + + // special check to see if path checking is required. + $just_path = str_replace($normalized_url, '', $normalized_path); + if ($normalized_url === '/' || $just_path === $page->path()) { + $url_path = $normalized_url; + } else { + $url_bits = static::parseUrl($normalized_path); + $full_path = $url_bits['path']; + $raw_full_path = rawurldecode($full_path); + + if (file_exists($raw_full_path)) { + $full_path = $raw_full_path; + } elseif (!file_exists($full_path)) { + $full_path = false; + } + + if ($full_path) { + $path_info = pathinfo($full_path); + $page_path = $path_info['dirname']; + $filename = ''; + + if ($url_path === '..') { + $page_path = $full_path; + } else { + // save the filename if a file is part of the path + if (is_file($full_path)) { + if ($path_info['extension'] !== 'md') { + $filename = '/' . $path_info['basename']; + } + } else { + $page_path = $full_path; + } + } + + // get page instances and try to find one that fits + $instances = $grav['pages']->instances(); + if (isset($instances[$page_path])) { + /** @var Page $target */ + $target = $instances[$page_path]; + $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename; + + $url_path = Uri::buildUrl($url_bits); + } else { + $url_path = $normalized_url; + } + } else { + $url_path = $normalized_url; + } + } + } + + // handle absolute URLs + if (is_array($url) && !$external && ($absolute === true || $grav['config']->get('system.absolute_urls', false))) { + + $url['scheme'] = $uri->scheme(true); + $url['host'] = $uri->host(); + $url['port'] = $uri->port(true); + + // check if page exists for this route, and if so, check if it has SSL enabled + $pages = $grav['pages']; + $routes = $pages->routes(); + + // if this is an image, get the proper path + $url_bits = pathinfo($url_path); + if (isset($url_bits['extension'])) { + $target_path = $url_bits['dirname']; + } else { + $target_path = $url_path; + } + + // strip base from this path + $target_path = str_replace($uri->rootUrl(), '', $target_path); + + // set to / if root + if (empty($target_path)) { + $target_path = '/'; + } + + // look to see if this page exists and has ssl enabled + if (isset($routes[$target_path])) { + $target_page = $pages->get($routes[$target_path]); + if ($target_page) { + $ssl_enabled = $target_page->ssl(); + if ($ssl_enabled !== null) { + if ($ssl_enabled) { + $url['scheme'] = 'https'; + } else { + $url['scheme'] = 'http'; + } + } + } + } + } + + // Handle route only + if ($route_only) { + $url_path = str_replace(static::filterPath($base_url), '', $url_path); + } + + // transform back to string/array as needed + if (is_array($url)) { + $url['path'] = $url_path; + } else { + $url = $url_path; + } + + return $url; + } + + public static function parseUrl($url) + { + $grav = Grav::instance(); + $parts = parse_url($url); + + list($stripped_path, $params) = static::extractParams($parts['path'], $grav['config']->get('system.param_sep')); + + if (!empty($params)) { + $parts['path'] = $stripped_path; + $parts['params'] = $params; + } + + return $parts; + } + + public static function extractParams($uri, $delimiter) + { + $params = []; + + if (strpos($uri, $delimiter) !== false) { + preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER); + + foreach ($matches as $match) { + $param = explode($delimiter, $match[1]); + if (count($param) === 2) { + $plain_var = filter_var(rawurldecode($param[1]), FILTER_SANITIZE_STRING); + $params[$param[0]] = $plain_var; + $uri = str_replace($match[0], '', $uri); + } + } + } + + return [$uri, $params]; + } + + /** + * Converts links from absolute '/' or relative (../..) to a Grav friendly format + * + * @param Page $page the current page to use as reference + * @param string $markdown_url the URL as it was written in the markdown + * @param string $type the type of URL, image | link + * @param null $relative if null, will use system default, if true will use relative links internally + * + * @return string the more friendly formatted url + */ + public static function convertUrlOld(Page $page, $markdown_url, $type = 'link', $relative = null) + { + $grav = Grav::instance(); + + $language = $grav['language']; + + // Link processing should prepend language + $language_append = ''; + if ($type === 'link' && $language->enabled()) { + $language_append = $language->getLanguageURLPrefix(); + } + $pages_dir = $grav['locator']->findResource('page://'); + if ($relative === null) { + $base = $grav['base_url']; + } else { + $base = $relative ? $grav['base_url_relative'] : $grav['base_url_absolute']; + } + + $base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append; + + // if absolute and starts with a base_url move on + if (pathinfo($markdown_url, PATHINFO_DIRNAME) === '.' && $page->url() === '/') { + return '/' . $markdown_url; + } + // no path to convert + if ($base_url !== '' && Utils::startsWith($markdown_url, $base_url)) { + return $markdown_url; + } + // if contains only a fragment + if (Utils::startsWith($markdown_url, '#')) { + return $markdown_url; + } + + $target = null; + // see if page is relative to this or absolute + if (Utils::startsWith($markdown_url, '/')) { + $normalized_url = Utils::normalizePath($base_url . $markdown_url); + $normalized_path = Utils::normalizePath($pages_dir . $markdown_url); + } else { + $normalized_url = $base_url . Utils::normalizePath($page->route() . '/' . $markdown_url); + $normalized_path = Utils::normalizePath($page->path() . '/' . $markdown_url); + } + + // special check to see if path checking is required. + $just_path = str_replace($normalized_url, '', $normalized_path); + if ($just_path === $page->path()) { + return $normalized_url; + } + + $url_bits = parse_url($normalized_path); + $full_path = $url_bits['path']; + + if (file_exists($full_path)) { + // do nothing + } elseif (file_exists(rawurldecode($full_path))) { + $full_path = rawurldecode($full_path); + } else { + return $normalized_url; + } + + $path_info = pathinfo($full_path); + $page_path = $path_info['dirname']; + $filename = ''; + + if ($markdown_url === '..') { + $page_path = $full_path; + } else { + // save the filename if a file is part of the path + if (is_file($full_path)) { + if ($path_info['extension'] !== 'md') { + $filename = '/' . $path_info['basename']; + } + } else { + $page_path = $full_path; + } + } + + // get page instances and try to find one that fits + $instances = $grav['pages']->instances(); + if (isset($instances[$page_path])) { + /** @var Page $target */ + $target = $instances[$page_path]; + $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename; + + return static::buildUrl($url_bits); + } + + return $normalized_url; + } + + /** + * Adds the nonce to a URL for a specific action + * + * @param string $url the url + * @param string $action the action + * @param string $nonceParamName the param name to use + * + * @return string the url with the nonce + */ + public static function addNonce($url, $action, $nonceParamName = 'nonce') + { + $fake = $url && $url[0] === '/'; + + if ($fake) { + $url = 'http://domain.com' . $url; + } + $uri = new static($url); + $parts = $uri->toArray(); + $nonce = Utils::getNonce($action); + $parts['params'] = (isset($parts['params']) ? $parts['params'] : []) + [$nonceParamName => $nonce]; + + if ($fake) { + unset($parts['scheme'], $parts['host']); + } + + return static::buildUrl($parts); + } + + /** + * Is the passed in URL a valid URL? + * + * @param $url + * @return bool + */ + public static function isValidUrl($url) + { + $regex = '/^(?:(https?|ftp|telnet):)?\/\/((?:[a-z0-9@:.-]|%[0-9A-F]{2}){3,})(?::(\d+))?((?:\/(?:[a-z0-9-._~!$&\'\(\)\*\+\,\;\=\:\@]|%[0-9A-F]{2})*)*)(?:\?((?:[a-z0-9-._~!$&\'\(\)\*\+\,\;\=\:\/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&\'\(\)\*\+\,\;\=\:\/?@]|%[0-9A-F]{2})*))?/'; + if (preg_match($regex, $url)) { + return true; + } + + return false; + } + + /** + * Removes extra double slashes and fixes back-slashes + * + * @param $path + * @return mixed|string + */ + public static function cleanPath($path) + { + $regex = '/(\/)\/+/'; + $path = str_replace(['\\', '/ /'], '/', $path); + $path = preg_replace($regex,'$1',$path); + + return $path; + } + + /** + * Filters the user info string. + * + * @param string $info The raw user or password. + * @return string The percent-encoded user or password string. + */ + public static function filterUserInfo($info) + { + return $info !== null ? UriPartsFilter::filterUserInfo($info) : ''; + } + + /** + * Filter Uri path. + * + * This method percent-encodes all reserved + * characters in the provided path string. This method + * will NOT double-encode characters that are already + * percent-encoded. + * + * @param string $path The raw uri path. + * @return string The RFC 3986 percent-encoded uri path. + * @link http://www.faqs.org/rfcs/rfc3986.html + */ + public static function filterPath($path) + { + return $path !== null ? UriPartsFilter::filterPath($path) : ''; + } + + /** + * Filters the query string or fragment of a URI. + * + * @param string $query The raw uri query string. + * @return string The percent-encoded query string. + */ + public static function filterQuery($query) + { + return $query !== null ? UriPartsFilter::filterQueryOrFragment($query) : ''; + } + + /** + * @param array $env + */ + protected function createFromEnvironment(array $env) + { + // Build scheme. + if (isset($env['REQUEST_SCHEME'])) { + $this->scheme = $env['REQUEST_SCHEME']; + } else { + $https = isset($env['HTTPS']) ? $env['HTTPS'] : ''; + $this->scheme = (empty($https) || strtolower($https) === 'off') ? 'http' : 'https'; + } + + // Build user and password. + $this->user = isset($env['PHP_AUTH_USER']) ? $env['PHP_AUTH_USER'] : null; + $this->password = isset($env['PHP_AUTH_PW']) ? $env['PHP_AUTH_PW'] : null; + + // Build host. + $hostname = 'localhost'; + if (isset($env['HTTP_HOST'])) { + $hostname = $env['HTTP_HOST']; + } elseif (isset($env['SERVER_NAME'])) { + $hostname = $env['SERVER_NAME']; + } + // Remove port from HTTP_HOST generated $hostname + $hostname = Utils::substrToString($hostname, ':'); + // Validate the hostname + $this->host = $this->validateHostname($hostname) ? $hostname : 'unknown'; + + // Build port. + $this->port = isset($env['SERVER_PORT']) ? (int)$env['SERVER_PORT'] : null; + if ($this->hasStandardPort()) { + $this->port = null; + } + + // Build path. + $request_uri = isset($env['REQUEST_URI']) ? $env['REQUEST_URI'] : ''; + $this->path = rawurldecode(parse_url('http://example.com' . $request_uri, PHP_URL_PATH)); + + // Build query string. + $this->query = isset($env['QUERY_STRING']) ? $env['QUERY_STRING'] : ''; + if ($this->query === '') { + $this->query = parse_url('http://example.com' . $request_uri, PHP_URL_QUERY); + } + + // Support ngnix routes. + if (strpos($this->query, '_url=') === 0) { + parse_str($this->query, $query); + unset($query['_url']); + $this->query = http_build_query($query); + } + + // Build fragment. + $this->fragment = null; + + // Filter userinfo, path and query string. + $this->user = $this->user !== null ? static::filterUserInfo($this->user) : null; + $this->password = $this->password !== null ? static::filterUserInfo($this->password) : null; + $this->path = empty($this->path) ? '/' : static::filterPath($this->path); + $this->query = static::filterQuery($this->query); + + $this->reset(); + } + + /** + * Does this Uri use a standard port? + * + * @return bool + */ + protected function hasStandardPort() + { + return ($this->scheme === 'http' && $this->port === 80) || ($this->scheme === 'https' && $this->port === 443); + } + + /** + * @param string $url + */ + protected function createFromString($url) + { + // Set Uri parts. + $parts = parse_url($url); + if ($parts === false) { + throw new \RuntimeException('Malformed URL: ' . $url); + } + $this->scheme = isset($parts['scheme']) ? $parts['scheme'] : null; + $this->user = isset($parts['user']) ? $parts['user'] : null; + $this->password = isset($parts['pass']) ? $parts['pass'] : null; + $this->host = isset($parts['host']) ? $parts['host'] : null; + $this->port = isset($parts['port']) ? (int)$parts['port'] : null; + $this->path = isset($parts['path']) ? $parts['path'] : ''; + $this->query = isset($parts['query']) ? $parts['query'] : ''; + $this->fragment = isset($parts['fragment']) ? $parts['fragment'] : null; + + // Validate the hostname + if ($this->host) { + $this->host = $this->validateHostname($this->host) ? $this->host : 'unknown'; + } + // Filter userinfo, path, query string and fragment. + $this->user = $this->user !== null ? static::filterUserInfo($this->user) : null; + $this->password = $this->password !== null ? static::filterUserInfo($this->password) : null; + $this->path = empty($this->path) ? '/' : static::filterPath($this->path); + $this->query = static::filterQuery($this->query); + $this->fragment = $this->fragment !== null ? static::filterQuery($this->fragment) : null; + + $this->reset(); + } + + protected function reset() + { + // resets + parse_str($this->query, $this->queries); + $this->extension = null; + $this->basename = null; + $this->paths = []; + $this->params = []; + $this->env = $this->buildEnvironment(); + $this->uri = $this->path . (!empty($this->query) ? '?' . $this->query : ''); + + $this->base = $this->buildBaseUrl(); + $this->root_path = $this->buildRootPath(); + $this->root = $this->base . $this->root_path; + $this->url = $this->base . $this->uri; + } + + /** + * Get's post from either $_POST or JSON response object + * By default returns all data, or can return a single item + * + * @param string $element + * @param string $filter_type + * @return array|mixed|null + */ + public function post($element = null, $filter_type = null) + { + if (!$this->post) { + $content_type = $this->getContentType(); + if ($content_type == 'application/json') { + $json = file_get_contents('php://input'); + $this->post = json_decode($json, true); + } elseif (!empty($_POST)) { + $this->post = (array)$_POST; + } + } + + if ($this->post && !is_null($element)) { + $item = Utils::getDotNotation($this->post, $element); + if ($filter_type) { + $item = filter_var($item, $filter_type); + } + return $item; + } + + return $this->post; + } + + /** + * Get content type from request + * + * @param bool $short + * @return null|string + */ + private function getContentType($short = true) + { + if (isset($_SERVER['CONTENT_TYPE'])) { + $content_type = $_SERVER['CONTENT_TYPE']; + if ($short) { + return Utils::substrToString($content_type,';'); + } + return $content_type; + } + return null; + } + + /** + * Get the base URI with port if needed + * + * @return string + */ + private function buildBaseUrl() + { + return $this->scheme() . $this->host; + } + + /** + * Get the Grav Root Path + * + * @return string + */ + private function buildRootPath() + { + // In Windows script path uses backslash, convert it: + $scriptPath = str_replace('\\', '/', $_SERVER['PHP_SELF']); + $rootPath = str_replace(' ', '%20', rtrim(substr($scriptPath, 0, strpos($scriptPath, 'index.php')), '/')); + + // check if userdir in the path and workaround PHP bug with PHP_SELF + if (strpos($this->uri, '/~') !== false && strpos($scriptPath, '/~') === false) { + $rootPath = substr($this->uri, 0, strpos($this->uri, '/', 1)) . $rootPath; + } + + return $rootPath; + } + + private function buildEnvironment() + { + // check for localhost variations + if ($this->host === '127.0.0.1' || $this->host === '::1') { + return 'localhost'; + } + + return $this->host ?: 'unknown'; + } + + /** + * Process any params based in this URL, supports any valid delimiter + * + * @param $uri + * @param string $delimiter + * + * @return string + */ + private function processParams($uri, $delimiter = ':') + { + if (strpos($uri, $delimiter) !== false) { + preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER); + + foreach ($matches as $match) { + $param = explode($delimiter, $match[1]); + if (count($param) === 2) { + $plain_var = filter_var($param[1], FILTER_SANITIZE_STRING); + $this->params[$param[0]] = $plain_var; + $uri = str_replace($match[0], '', $uri); + } + } + } + return $uri; + } +} diff --git a/system/src/Grav/Common/User/Authentication.php b/system/src/Grav/Common/User/Authentication.php new file mode 100644 index 0000000..b46750c --- /dev/null +++ b/system/src/Grav/Common/User/Authentication.php @@ -0,0 +1,54 @@ +get('groups', []); + } + + /** + * Get the groups list + * + * @return array + */ + public static function groupNames() + { + $groups = []; + + foreach(static::groups() as $groupname => $group) { + $groups[$groupname] = isset($group['readableName']) ? $group['readableName'] : $groupname; + } + + return $groups; + } + + /** + * Checks if a group exists + * + * @param string $groupname + * + * @return bool + */ + public static function groupExists($groupname) + { + return isset(self::groups()[$groupname]); + } + + /** + * Get a group by name + * + * @param string $groupname + * + * @return object + */ + public static function load($groupname) + { + $groups = self::groups(); + + $content = isset($groups[$groupname]) ? $groups[$groupname] : []; + $content += ['groupname' => $groupname]; + + $blueprints = new Blueprints; + $blueprint = $blueprints->get('user/group'); + + return new Group($content, $blueprint); + } + + /** + * Save a group + */ + public function save() + { + $grav = Grav::instance(); + + /** @var Config $config */ + $config = $grav['config']; + + $blueprints = new Blueprints; + $blueprint = $blueprints->get('user/group'); + + $config->set("groups.{$this->groupname}", []); + + $fields = $blueprint->fields(); + foreach ($fields as $field) { + if ($field['type'] === 'text') { + $value = $field['name']; + if (isset($this->items['data'][$value])) { + $config->set("groups.{$this->groupname}.{$value}", $this->items['data'][$value]); + } + } + if ($field['type'] === 'array' || $field['type'] === 'permissions') { + $value = $field['name']; + $arrayValues = Utils::getDotNotation($this->items['data'], $field['name']); + + if ($arrayValues) { + foreach ($arrayValues as $arrayIndex => $arrayValue) { + $config->set("groups.{$this->groupname}.{$value}.{$arrayIndex}", $arrayValue); + } + } + } + } + + $type = 'groups'; + $blueprints = $this->blueprints("config/{$type}"); + + $filename = CompiledYamlFile::instance($grav['locator']->findResource("config://{$type}.yaml")); + + $obj = new Data($config->get($type), $blueprints); + $obj->file($filename); + $obj->save(); + } + + /** + * Remove a group + * + * @param string $groupname + * + * @return bool True if the action was performed + */ + public static function remove($groupname) + { + $grav = Grav::instance(); + + /** @var Config $config */ + $config = $grav['config']; + + $blueprints = new Blueprints; + $blueprint = $blueprints->get('user/group'); + + $type = 'groups'; + + $groups = $config->get($type); + unset($groups[$groupname]); + $config->set($type, $groups); + + $filename = CompiledYamlFile::instance($grav['locator']->findResource("config://{$type}.yaml")); + + $obj = new Data($groups, $blueprint); + $obj->file($filename); + $obj->save(); + + return true; + } +} diff --git a/system/src/Grav/Common/User/User.php b/system/src/Grav/Common/User/User.php new file mode 100644 index 0000000..512b292 --- /dev/null +++ b/system/src/Grav/Common/User/User.php @@ -0,0 +1,287 @@ +exists(). + * + * @param string $username + * @param bool $setConfig + * + * @return User + */ + public static function load($username) + { + $grav = Grav::instance(); + /** @var UniformResourceLocator $locator */ + $locator = $grav['locator']; + + // force lowercase of username + $username = strtolower($username); + + $blueprints = new Blueprints; + $blueprint = $blueprints->get('user/account'); + + $file_path = $locator->findResource('account://' . $username . YAML_EXT); + $file = CompiledYamlFile::instance($file_path); + $content = (array)$file->content() + ['username' => $username, 'state' => 'enabled']; + + $user = new User($content, $blueprint); + $user->file($file); + + return $user; + } + + /** + * Find a user by username, email, etc + * + * @param string $query the query to search for + * @param array $fields the fields to search + * @return User + */ + public static function find($query, $fields = ['username', 'email']) + { + $account_dir = Grav::instance()['locator']->findResource('account://'); + $files = $account_dir ? array_diff(scandir($account_dir), ['.', '..']) : []; + + // Try with username first, you never know! + if (in_array('username', $fields, true)) { + $user = User::load($query); + unset($fields[array_search('username', $fields, true)]); + } else { + $user = User::load(''); + } + + // If not found, try the fields + if (!$user->exists()) { + foreach ($files as $file) { + if (Utils::endsWith($file, YAML_EXT)) { + $find_user = User::load(trim(pathinfo($file, PATHINFO_FILENAME))); + foreach ($fields as $field) { + if ($find_user[$field] === $query) { + return $find_user; + } + } + } + } + } + return $user; + } + + /** + * Remove user account. + * + * @param string $username + * + * @return bool True if the action was performed + */ + public static function remove($username) + { + $file_path = Grav::instance()['locator']->findResource('account://' . $username . YAML_EXT); + + return $file_path && unlink($file_path); + } + + /** + * @param string $offset + * @return bool + */ + public function offsetExists($offset) + { + $value = parent::offsetExists($offset); + + // Handle special case where user was logged in before 'authorized' was added to the user object. + if (false === $value && $offset === 'authorized') { + $value = $this->offsetExists('authenticated'); + } + + return $value; + } + + /** + * @param string $offset + * @return mixed + */ + public function offsetGet($offset) + { + $value = parent::offsetGet($offset); + + // Handle special case where user was logged in before 'authorized' was added to the user object. + if (null === $value && $offset === 'authorized') { + $value = $this->offsetGet('authenticated'); + $this->offsetSet($offset, $value); + } + + return $value; + } + + /** + * Authenticate user. + * + * If user password needs to be updated, new information will be saved. + * + * @param string $password Plaintext password. + * + * @return bool + */ + public function authenticate($password) + { + $save = false; + + // Plain-text is still stored + if ($this->password) { + if ($password !== $this->password) { + // Plain-text passwords do not match, we know we should fail but execute + // verify to protect us from timing attacks and return false regardless of + // the result + Authentication::verify( + $password, + Grav::instance()['config']->get('system.security.default_hash') + ); + + return false; + } + + // Plain-text does match, we can update the hash and proceed + $save = true; + + $this->hashed_password = Authentication::create($this->password); + unset($this->password); + + } + + $result = Authentication::verify($password, $this->hashed_password); + + // Password needs to be updated, save the file. + if ($result === 2) { + $save = true; + $this->hashed_password = Authentication::create($password); + } + + if ($save) { + $this->save(); + } + + return (bool)$result; + } + + /** + * Save user without the username + */ + public function save() + { + $file = $this->file(); + + if ($file) { + $username = $this->get('username'); + + if (!$file->filename()) { + $locator = Grav::instance()['locator']; + $file->filename($locator->findResource('account://') . DS . strtolower($username) . YAML_EXT); + } + + // if plain text password, hash it and remove plain text + if ($this->password) { + $this->hashed_password = Authentication::create($this->password); + unset($this->password); + } + + unset($this->username); + $file->save($this->items); + $this->set('username', $username); + } + } + + /** + * Checks user authorization to the action. + * + * @param string $action + * + * @return bool + */ + public function authorize($action) + { + if (empty($this->items)) { + return false; + } + + if (!$this->authenticated) { + return false; + } + + if (isset($this->state) && $this->state !== 'enabled') { + return false; + } + + $return = false; + + //Check group access level + $groups = $this->get('groups'); + if ($groups) { + foreach ((array)$groups as $group) { + $permission = Grav::instance()['config']->get("groups.{$group}.access.{$action}"); + $return = Utils::isPositive($permission); + if ($return === true) { + break; + } + } + } + + //Check user access level + if ($this->get('access')) { + if (Utils::getDotNotation($this->get('access'), $action) !== null) { + $permission = $this->get("access.{$action}"); + $return = Utils::isPositive($permission); + } + } + + return $return; + } + + /** + * Checks user authorization to the action. + * Ensures backwards compatibility + * + * @param string $action + * + * @deprecated use authorize() + * @return bool + */ + public function authorise($action) + { + return $this->authorize($action); + } + + /** + * Return the User's avatar URL + * + * @return string + */ + public function avatarUrl() + { + if ($this->avatar) { + $avatar = $this->avatar; + $avatar = array_shift($avatar); + return Grav::instance()['base_url'] . '/' . $avatar['path']; + } + + return 'https://www.gravatar.com/avatar/' . md5($this->email); + } +} diff --git a/system/src/Grav/Common/Utils.php b/system/src/Grav/Common/Utils.php new file mode 100644 index 0000000..02d5e15 --- /dev/null +++ b/system/src/Grav/Common/Utils.php @@ -0,0 +1,1109 @@ +get('system.absolute_urls', false)) { + $domain = true; + } + + if (Grav::instance()['uri']->isExternal($input)) { + return $input; + } + + $input = ltrim((string)$input, '/'); + + if (Utils::contains((string)$input, '://')) { + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + + // Get relative path to the resource (or false if not found). + $resource = $locator->findResource($input, false); + } else { + $resource = $input; + } + + /** @var Uri $uri */ + $uri = Grav::instance()['uri']; + + return $resource ? rtrim($uri->rootUrl($domain), '/') . '/' . $resource : null; + } + + /** + * Check if the $haystack string starts with the substring $needle + * + * @param string $haystack + * @param string|string[] $needle + * + * @return bool + */ + public static function startsWith($haystack, $needle) + { + $status = false; + + foreach ((array)$needle as $each_needle) { + $status = $each_needle === '' || strpos($haystack, $each_needle) === 0; + if ($status) { + break; + } + } + + return $status; + } + + /** + * Check if the $haystack string ends with the substring $needle + * + * @param string $haystack + * @param string|string[] $needle + * + * @return bool + */ + public static function endsWith($haystack, $needle) + { + $status = false; + + foreach ((array)$needle as $each_needle) { + $status = $each_needle === '' || substr($haystack, -strlen($each_needle)) === $each_needle; + if ($status) { + break; + } + } + + return $status; + } + + /** + * Check if the $haystack string contains the substring $needle + * + * @param string $haystack + * @param string|string[] $needle + * + * @return bool + */ + public static function contains($haystack, $needle) + { + $status = false; + + foreach ((array)$needle as $each_needle) { + $status = $each_needle === '' || strpos($haystack, $each_needle) !== false; + if ($status) { + break; + } + } + + return $status; + } + + /** + * Returns the substring of a string up to a specified needle. if not found, return the whole haystack + * + * @param $haystack + * @param $needle + * + * @return string + */ + public static function substrToString($haystack, $needle) + { + if (static::contains($haystack, $needle)) { + return substr($haystack, 0, strpos($haystack, $needle)); + } + + return $haystack; + } + + /** + * Utility method to replace only the first occurrence in a string + * + * @param $search + * @param $replace + * @param $subject + * @return mixed + */ + public static function replaceFirstOccurrence($search, $replace, $subject) + { + if (!$search) { + return $subject; + } + $pos = strpos($subject, $search); + if ($pos !== false) { + $subject = substr_replace($subject, $replace, $pos, strlen($search)); + } + return $subject; + } + + /** + * Utility method to replace only the last occurrence in a string + * + * @param $search + * @param $replace + * @param $subject + * @return mixed + */ + public static function replaceLastOccurrence($search, $replace, $subject) + { + $pos = strrpos($subject, $search); + + if($pos !== false) + { + $subject = substr_replace($subject, $replace, $pos, strlen($search)); + } + + return $subject; + } + + /** + * Merge two objects into one. + * + * @param object $obj1 + * @param object $obj2 + * + * @return object + */ + public static function mergeObjects($obj1, $obj2) + { + return (object)array_merge((array)$obj1, (array)$obj2); + } + + /** + * Recursive Merge with uniqueness + * + * @param $array1 + * @param $array2 + * @return mixed + */ + public static function arrayMergeRecursiveUnique($array1, $array2) + { + if (empty($array1)) { + // Optimize the base case + return $array2; + } + + foreach ($array2 as $key => $value) { + if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) { + $value = static::arrayMergeRecursiveUnique($array1[$key], $value); + } + $array1[$key] = $value; + } + + return $array1; + } + + /** + * Return the Grav date formats allowed + * + * @return array + */ + public static function dateFormats() + { + $now = new DateTime(); + + $date_formats = [ + 'd-m-Y H:i' => 'd-m-Y H:i (e.g. '.$now->format('d-m-Y H:i').')', + 'Y-m-d H:i' => 'Y-m-d H:i (e.g. '.$now->format('Y-m-d H:i').')', + 'm/d/Y h:i a' => 'm/d/Y h:i a (e.g. '.$now->format('m/d/Y h:i a').')', + 'H:i d-m-Y' => 'H:i d-m-Y (e.g. '.$now->format('H:i d-m-Y').')', + 'h:i a m/d/Y' => 'h:i a m/d/Y (e.g. '.$now->format('h:i a m/d/Y').')', + ]; + $default_format = Grav::instance()['config']->get('system.pages.dateformat.default'); + if ($default_format) { + $date_formats = array_merge([$default_format => $default_format.' (e.g. '.$now->format($default_format).')'], $date_formats); + } + + return $date_formats; + } + + /** + * Truncate text by number of characters but can cut off words. + * + * @param string $string + * @param int $limit Max number of characters. + * @param bool $up_to_break truncate up to breakpoint after char count + * @param string $break Break point. + * @param string $pad Appended padding to the end of the string. + * + * @return string + */ + public static function truncate($string, $limit = 150, $up_to_break = false, $break = " ", $pad = "…") + { + // return with no change if string is shorter than $limit + if (mb_strlen($string) <= $limit) { + return $string; + } + + // is $break present between $limit and the end of the string? + if ($up_to_break && false !== ($breakpoint = mb_strpos($string, $break, $limit))) { + if ($breakpoint < mb_strlen($string) - 1) { + $string = mb_substr($string, 0, $breakpoint) . $break; + } + } else { + $string = mb_substr($string, 0, $limit) . $pad; + } + + return $string; + } + + /** + * Truncate text by number of characters in a "word-safe" manor. + * + * @param string $string + * @param int $limit + * + * @return string + */ + public static function safeTruncate($string, $limit = 150) + { + return static::truncate($string, $limit, true); + } + + + /** + * Truncate HTML by number of characters. not "word-safe"! + * + * @param string $text + * @param int $length in characters + * @param string $ellipsis + * + * @return string + */ + public static function truncateHtml($text, $length = 100, $ellipsis = '...') + { + return Truncator::truncateLetters($text, $length, $ellipsis); + } + + /** + * Truncate HTML by number of characters in a "word-safe" manor. + * + * @param string $text + * @param int $length in words + * @param string $ellipsis + * + * @return string + */ + public static function safeTruncateHtml($text, $length = 25, $ellipsis = '...') + { + return Truncator::truncateWords($text, $length, $ellipsis); + } + + /** + * Generate a random string of a given length + * + * @param int $length + * + * @return string + */ + public static function generateRandomString($length = 5) + { + return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length); + } + + /** + * Provides the ability to download a file to the browser + * + * @param string $file the full path to the file to be downloaded + * @param bool $force_download as opposed to letting browser choose if to download or render + * @param int $sec Throttling, try 0.1 for some speed throttling of downloads + * @param int $bytes Size of chunks to send in bytes. Default is 1024 + * @throws \Exception + */ + public static function download($file, $force_download = true, $sec = 0, $bytes = 1024) + { + if (file_exists($file)) { + // fire download event + Grav::instance()->fireEvent('onBeforeDownload', new Event(['file' => $file])); + + $file_parts = pathinfo($file); + $mimetype = static::getMimeByExtension($file_parts['extension']); + $size = filesize($file); // File size + + // clean all buffers + while (ob_get_level()) { + ob_end_clean(); + } + + // required for IE, otherwise Content-Disposition may be ignored + if (ini_get('zlib.output_compression')) { + ini_set('zlib.output_compression', 'Off'); + } + + header('Content-Type: ' . $mimetype); + header('Accept-Ranges: bytes'); + + if ($force_download) { + // output the regular HTTP headers + header('Content-Disposition: attachment; filename="' . $file_parts['basename'] . '"'); + } + + // multipart-download and download resuming support + if (isset($_SERVER['HTTP_RANGE'])) { + list($a, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); + list($range) = explode(',', $range, 2); + list($range, $range_end) = explode('-', $range); + $range = (int)$range; + if (!$range_end) { + $range_end = $size - 1; + } else { + $range_end = (int)$range_end; + } + $new_length = $range_end - $range + 1; + header('HTTP/1.1 206 Partial Content'); + header("Content-Length: {$new_length}"); + header("Content-Range: bytes {$range}-{$range_end}/{$size}"); + } else { + $range = 0; + $new_length = $size; + header('Content-Length: ' . $size); + + if (Grav::instance()['config']->get('system.cache.enabled')) { + $expires = Grav::instance()['config']->get('system.pages.expires'); + if ($expires > 0) { + $expires_date = gmdate('D, d M Y H:i:s T', time() + $expires); + header('Cache-Control: max-age=' . $expires); + header('Expires: ' . $expires_date); + header('Pragma: cache'); + } + header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file))); + + // Return 304 Not Modified if the file is already cached in the browser + if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && + strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) + { + header('HTTP/1.1 304 Not Modified'); + exit(); + } + } + } + + /* output the file itself */ + $chunksize = $bytes * 8; //you may want to change this + $bytes_send = 0; + + $fp = @fopen($file, 'rb'); + if ($fp) { + if ($range) { + fseek($fp, $range); + } + while (!feof($fp) && (!connection_aborted()) && ($bytes_send < $new_length) ) { + $buffer = fread($fp, $chunksize); + echo($buffer); //echo($buffer); // is also possible + flush(); + usleep($sec * 1000000); + $bytes_send += strlen($buffer); + } + fclose($fp); + } else { + throw new \RuntimeException('Error - can not open file.'); + } + + exit; + } + } + + /** + * Return the mimetype based on filename extension + * + * @param string $extension Extension of file (eg "txt") + * @param string $default + * + * @return string + */ + public static function getMimeByExtension($extension, $default = 'application/octet-stream') + { + $extension = strtolower($extension); + + // look for some standard types + switch ($extension) { + case null: + return $default; + case 'json': + return 'application/json'; + case 'html': + return 'text/html'; + case 'atom': + return 'application/atom+xml'; + case 'rss': + return 'application/rss+xml'; + case 'xml': + return 'application/xml'; + } + + $media_types = Grav::instance()['config']->get('media.types'); + + if (isset($media_types[$extension])) { + if (isset($media_types[$extension]['mime'])) { + return $media_types[$extension]['mime']; + } + } + + return $default; + } + + /** + * Return the mimetype based on filename extension + * + * @param string $mime mime type (eg "text/html") + * @param string $default default value + * + * @return string + */ + public static function getExtensionByMime($mime, $default = 'html') + { + $mime = strtolower($mime); + + // look for some standard mime types + switch ($mime) { + case '*/*': + case 'text/*': + case 'text/html': + return 'html'; + case 'application/json': + return 'json'; + case 'application/atom+xml': + return 'atom'; + case 'application/rss+xml': + return 'rss'; + case 'application/xml': + return 'xml'; + } + + $media_types = (array)Grav::instance()['config']->get('media.types'); + + foreach ($media_types as $extension => $type) { + if ($extension === 'defaults') { + continue; + } + if (isset($type['mime']) && $type['mime'] === $mime) { + return $extension; + } + } + + return $default; + } + + /** + * Normalize path by processing relative `.` and `..` syntax and merging path + * + * @param string $path + * + * @return string + */ + public static function normalizePath($path) + { + $root = ($path[0] === '/') ? '/' : ''; + + $segments = explode('/', trim($path, '/')); + $ret = []; + foreach ($segments as $segment) { + if (($segment === '.') || $segment === '') { + continue; + } + if ($segment === '..') { + array_pop($ret); + } else { + $ret[] = $segment; + } + } + + return $root . implode('/', $ret); + } + + /** + * Check whether a function is disabled in the PHP settings + * + * @param string $function the name of the function to check + * + * @return bool + */ + public static function isFunctionDisabled($function) + { + return in_array($function, explode(',', ini_get('disable_functions')), true); + } + + /** + * Get the formatted timezones list + * + * @return array + */ + public static function timezones() + { + $timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL); + $offsets = []; + $testDate = new \DateTime; + + foreach ($timezones as $zone) { + $tz = new \DateTimeZone($zone); + $offsets[$zone] = $tz->getOffset($testDate); + } + + asort($offsets); + + $timezone_list = []; + foreach ($offsets as $timezone => $offset) { + $offset_prefix = $offset < 0 ? '-' : '+'; + $offset_formatted = gmdate('H:i', abs($offset)); + + $pretty_offset = "UTC${offset_prefix}${offset_formatted}"; + + $timezone_list[$timezone] = "(${pretty_offset}) ".str_replace('_', ' ', $timezone); + } + + return $timezone_list; + } + + /** + * Recursively filter an array, filtering values by processing them through the $fn function argument + * + * @param array $source the Array to filter + * @param callable $fn the function to pass through each array item + * + * @return array + */ + public static function arrayFilterRecursive(Array $source, $fn) + { + $result = []; + foreach ($source as $key => $value) { + if (is_array($value)) { + $result[$key] = static::arrayFilterRecursive($value, $fn); + continue; + } + if ($fn($key, $value)) { + $result[$key] = $value; // KEEP + continue; + } + } + + return $result; + } + + /** + * Flatten an array + * + * @param array $array + * @return array + */ + public static function arrayFlatten($array) + { + $flatten = array(); + foreach ($array as $key => $inner){ + if (is_array($inner)) { + foreach ($inner as $inner_key => $value) { + $flatten[$inner_key] = $value; + } + } else { + $flatten[$key] = $inner; + } + } + return $flatten; + } + + /** + * Checks if the passed path contains the language code prefix + * + * @param string $string The path + * + * @return bool + */ + public static function pathPrefixedByLangCode($string) + { + if (strlen($string) <= 3) { + return false; + } + + $languages_enabled = Grav::instance()['config']->get('system.languages.supported', []); + + if ($string[0] === '/' && $string[3] === '/' && in_array(substr($string, 1, 2), $languages_enabled)) { + return true; + } + + return false; + } + + /** + * Get the timestamp of a date + * + * @param string $date a String expressed in the system.pages.dateformat.default format, with fallback to a + * strtotime argument + * @param string $format a date format to use if possible + * @return int the timestamp + */ + public static function date2timestamp($date, $format = null) + { + $config = Grav::instance()['config']; + $dateformat = $format ?: $config->get('system.pages.dateformat.default'); + + // try to use DateTime and default format + if ($dateformat) { + $datetime = DateTime::createFromFormat($dateformat, $date); + } else { + $datetime = new DateTime($date); + } + + // fallback to strtotime() if DateTime approach failed + if ($datetime !== false) { + return $datetime->getTimestamp(); + } + + return strtotime($date); + } + + /** + * @param array $array + * @param string $path + * @param null $default + * @return mixed + * + * @deprecated Use getDotNotation() method instead + */ + public static function resolve(array $array, $path, $default = null) + { + return static::getDotNotation($array, $path, $default); + } + + /** + * Checks if a value is positive + * + * @param string $value + * + * @return boolean + */ + public static function isPositive($value) + { + return in_array($value, [true, 1, '1', 'yes', 'on', 'true'], true); + } + + /** + * Generates a nonce string to be hashed. Called by self::getNonce() + * We removed the IP portion in this version because it causes too many inconsistencies + * with reverse proxy setups. + * + * @param string $action + * @param bool $plusOneTick if true, generates the token for the next tick (the next 12 hours) + * + * @return string the nonce string + */ + private static function generateNonceString($action, $plusOneTick = false) + { + $username = ''; + if (isset(Grav::instance()['user'])) { + $user = Grav::instance()['user']; + $username = $user->username; + } + + $token = session_id(); + $i = self::nonceTick(); + + if ($plusOneTick) { + $i++; + } + + return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . Grav::instance()['config']->get('security.salt')); + } + + //Added in version 1.0.8 to ensure that existing nonces are not broken. + private static function generateNonceStringOldStyle($action, $plusOneTick = false) + { + if (isset(Grav::instance()['user'])) { + $user = Grav::instance()['user']; + $username = $user->username; + if (isset($_SERVER['REMOTE_ADDR'])) { + $username .= $_SERVER['REMOTE_ADDR']; + } + } else { + $username = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; + } + $token = session_id(); + $i = self::nonceTick(); + if ($plusOneTick) { + $i++; + } + + return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . Grav::instance()['config']->get('security.salt')); + } + + /** + * Get the time-dependent variable for nonce creation. + * + * Now a tick lasts a day. Once the day is passed, the nonce is not valid any more. Find a better way + * to ensure nonces issued near the end of the day do not expire in that small amount of time + * + * @return int the time part of the nonce. Changes once every 24 hours + */ + private static function nonceTick() + { + $secondsInHalfADay = 60 * 60 * 12; + + return (int)ceil(time() / $secondsInHalfADay); + } + + /** + * Creates a hashed nonce tied to the passed action. Tied to the current user and time. The nonce for a given + * action is the same for 12 hours. + * + * @param string $action the action the nonce is tied to (e.g. save-user-admin or move-page-homepage) + * @param bool $plusOneTick if true, generates the token for the next tick (the next 12 hours) + * + * @return string the nonce + */ + public static function getNonce($action, $plusOneTick = false) + { + // Don't regenerate this again if not needed + if (isset(static::$nonces[$action])) { + return static::$nonces[$action]; + } + $nonce = md5(self::generateNonceString($action, $plusOneTick)); + static::$nonces[$action] = $nonce; + + return static::$nonces[$action]; + } + + //Added in version 1.0.8 to ensure that existing nonces are not broken. + public static function getNonceOldStyle($action, $plusOneTick = false) + { + // Don't regenerate this again if not needed + if (isset(static::$nonces[$action])) { + return static::$nonces[$action]; + } + $nonce = md5(self::generateNonceStringOldStyle($action, $plusOneTick)); + static::$nonces[$action] = $nonce; + + return static::$nonces[$action]; + } + + /** + * Verify the passed nonce for the give action + * + * @param string|string[] $nonce the nonce to verify + * @param string $action the action to verify the nonce to + * + * @return boolean verified or not + */ + public static function verifyNonce($nonce, $action) + { + //Safety check for multiple nonces + if (is_array($nonce)) { + $nonce = array_shift($nonce); + } + + //Nonce generated 0-12 hours ago + if ($nonce === self::getNonce($action)) { + return true; + } + + //Nonce generated 12-24 hours ago + $plusOneTick = true; + if ($nonce === self::getNonce($action, $plusOneTick)) { + return true; + } + + //Added in version 1.0.8 to ensure that existing nonces are not broken. + //Nonce generated 0-12 hours ago + if ($nonce === self::getNonceOldStyle($action)) { + return true; + } + + //Nonce generated 12-24 hours ago + $plusOneTick = true; + if ($nonce === self::getNonceOldStyle($action, $plusOneTick)) { + return true; + } + + //Invalid nonce + return false; + } + + /** + * Simple helper method to get whether or not the admin plugin is active + * + * @return bool + */ + public static function isAdminPlugin() + { + if (isset(Grav::instance()['admin'])) { + return true; + } + + return false; + } + + /** + * Get a portion of an array (passed by reference) with dot-notation key + * + * @param $array + * @param $key + * @param null $default + * @return mixed + */ + public static function getDotNotation($array, $key, $default = null) + { + if (null === $key) { + return $array; + } + + if (isset($array[$key])) { + return $array[$key]; + } + + foreach (explode('.', $key) as $segment) { + if (!is_array($array) || !array_key_exists($segment, $array)) { + return $default; + } + + $array = $array[$segment]; + } + + return $array; + } + + /** + * Set portion of array (passed by reference) for a dot-notation key + * and set the value + * + * @param $array + * @param $key + * @param $value + * @param bool $merge + * + * @return mixed + */ + public static function setDotNotation(&$array, $key, $value, $merge = false) + { + if (null === $key) { + return $array = $value; + } + + $keys = explode('.', $key); + + while (count($keys) > 1) { + $key = array_shift($keys); + + if ( ! isset($array[$key]) || ! is_array($array[$key])) + { + $array[$key] = array(); + } + + $array =& $array[$key]; + } + + $key = array_shift($keys); + + if (!$merge || !isset($array[$key])) { + $array[$key] = $value; + } else { + $array[$key] = array_merge($array[$key], $value); + } + + + return $array; + } + + /** + * Utility method to determine if the current OS is Windows + * + * @return bool + */ + public static function isWindows() + { + return strncasecmp(PHP_OS, 'WIN', 3) === 0; + } + + /** + * Utility to determine if the server running PHP is Apache + * + * @return bool + */ + public static function isApache() { + return isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false; + } + + /** + * Sort a multidimensional array by another array of ordered keys + * + * @param array $array + * @param array $orderArray + * @return array + */ + public static function sortArrayByArray(array $array, array $orderArray) + { + $ordered = array(); + foreach ($orderArray as $key) { + if (array_key_exists($key, $array)) { + $ordered[$key] = $array[$key]; + unset($array[$key]); + } + } + return $ordered + $array; + } + + /** + * Sort an array by a key value in the array + * + * @param $array + * @param $array_key + * @param int $direction + * @param int $sort_flags + * @return array + */ + public static function sortArrayByKey($array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR ) + { + $output = []; + + if (!is_array($array) || !$array) { + return $output; + } + + foreach ($array as $key => $row) { + $output[$key] = $row[$array_key]; + } + + array_multisort($output, $direction, $sort_flags, $array); + + return $array; + } + + /** + * Get's path based on a token + * + * @param $path + * @param Page|null $page + * @return string + * @throws \RuntimeException + */ + public static function getPagePathFromToken($path, $page = null) + { + $path_parts = pathinfo($path); + $grav = Grav::instance(); + + $basename = ''; + if (isset($path_parts['extension'])) { + $basename = '/' . $path_parts['basename']; + $path = rtrim($path_parts['dirname'], ':'); + } + + $regex = '/(@self|self@)|((?:@page|page@):(?:.*))|((?:@theme|theme@):(?:.*))/'; + preg_match($regex, $path, $matches); + + if ($matches) { + if ($matches[1]) { + if (null === $page) { + throw new \RuntimeException('Page not available for this self@ reference'); + } + } elseif ($matches[2]) { + // page@ + $parts = explode(':', $path); + $route = $parts[1]; + $page = $grav['page']->find($route); + } elseif ($matches[3]) { + // theme@ + $parts = explode(':', $path); + $route = $parts[1]; + $theme = str_replace(ROOT_DIR, '', $grav['locator']->findResource("theme://")); + + return $theme . $route . $basename; + } + } else { + return $path . $basename; + } + + if (!$page) { + throw new \RuntimeException('Page route not found: ' . $path); + } + + $path = str_replace($matches[0], rtrim($page->relativePagePath(), '/'), $path); + + return $path . $basename; + } + + public static function getUploadLimit() + { + static $max_size = -1; + + if ($max_size < 0) { + $post_max_size = static::parseSize(ini_get('post_max_size')); + if ($post_max_size > 0) { + $max_size = $post_max_size; + } + + $upload_max = static::parseSize(ini_get('upload_max_filesize')); + if ($upload_max > 0 && $upload_max < $max_size) { + $max_size = $upload_max; + } + } + + return $max_size; + } + + /** + * Parse a readable file size and return a value in bytes + * + * @param $size + * @return int + */ + public static function parseSize($size) + { + $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); + $size = preg_replace('/[^0-9\.]/', '', $size); + if ($unit) { + return (int)($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); + } + + return (int)$size; + } + + /** + * Multibyte-safe Parse URL function + * + * @param $url + * @return mixed + * @throws \InvalidArgumentException + */ + public static function multibyteParseUrl($url) + { + $enc_url = preg_replace_callback( + '%[^:/@?&=#]+%usD', + function ($matches) { + return urlencode($matches[0]); + }, + $url + ); + + $parts = parse_url($enc_url); + + if($parts === false) { + throw new \InvalidArgumentException('Malformed URL: ' . $url); + } + + foreach($parts as $name => $value) { + $parts[$name] = urldecode($value); + } + + return $parts; + } +} diff --git a/system/src/Grav/Console/Cli/BackupCommand.php b/system/src/Grav/Console/Cli/BackupCommand.php new file mode 100644 index 0000000..4a53869 --- /dev/null +++ b/system/src/Grav/Console/Cli/BackupCommand.php @@ -0,0 +1,90 @@ +setName("backup") + ->addArgument( + 'destination', + InputArgument::OPTIONAL, + 'Where to store the backup (/backup is default)' + + ) + ->setDescription("Creates a backup of the Grav instance") + ->setHelp('The backup creates a zipped backup. Optionally can be saved in a different destination.'); + + $this->source = getcwd(); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $this->progress = new ProgressBar($this->output); + $this->progress->setFormat('Archiving %current% files [%bar%] %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(''); + + } + + /** + * @param $args + */ + public function output($args) + { + switch ($args['type']) { + case 'message': + $this->output->writeln($args['message']); + break; + case 'progress': + if ($args['complete']) { + $this->progress->finish(); + } else { + $this->progress->advance(); + } + break; + } + } + +} + diff --git a/system/src/Grav/Console/Cli/CleanCommand.php b/system/src/Grav/Console/Cli/CleanCommand.php new file mode 100644 index 0000000..32e2b75 --- /dev/null +++ b/system/src/Grav/Console/Cli/CleanCommand.php @@ -0,0 +1,278 @@ +setName("clean") + ->setDescription("Handles cleaning chores for Grav distribution") + ->setHelp('The clean clean extraneous folders and data'); + } + + /** + * @param InputInterface $input + * @param OutputInterface $output + * + * @return int|null|void + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $this->setupConsole($input, $output); + + $this->cleanPaths(); + } + + private function cleanPaths() + { + $this->output->writeln(''); + $this->output->writeln('DELETING'); + $anything = false; + foreach ($this->paths_to_remove as $path) { + $path = ROOT_DIR . $path; + if (is_dir($path) && @Folder::delete($path)) { + $anything = true; + $this->output->writeln('dir: ' . $path); + } elseif (is_file($path) && @unlink($path)) { + $anything = true; + $this->output->writeln('file: ' . $path); + } + } + if (!$anything) { + $this->output->writeln(''); + $this->output->writeln('Nothing to clean...'); + } + } + + /** + * Set colors style definition for the formatter. + * + * @param InputInterface $input + * @param OutputInterface $output + */ + public function setupConsole(InputInterface $input, OutputInterface $output) + { + $this->input = $input; + $this->output = $output; + + $this->output->getFormatter()->setStyle('normal', new OutputFormatterStyle('white')); + $this->output->getFormatter()->setStyle('yellow', new OutputFormatterStyle('yellow', null, ['bold'])); + $this->output->getFormatter()->setStyle('red', new OutputFormatterStyle('red', null, ['bold'])); + $this->output->getFormatter()->setStyle('cyan', new OutputFormatterStyle('cyan', null, ['bold'])); + $this->output->getFormatter()->setStyle('green', new OutputFormatterStyle('green', null, ['bold'])); + $this->output->getFormatter()->setStyle('magenta', new OutputFormatterStyle('magenta', null, ['bold'])); + $this->output->getFormatter()->setStyle('white', new OutputFormatterStyle('white', null, ['bold'])); + } + +} diff --git a/system/src/Grav/Console/Cli/ClearCacheCommand.php b/system/src/Grav/Console/Cli/ClearCacheCommand.php new file mode 100644 index 0000000..cb5ffe8 --- /dev/null +++ b/system/src/Grav/Console/Cli/ClearCacheCommand.php @@ -0,0 +1,70 @@ +setName('clear-cache') + ->setAliases(['clearcache']) + ->setDescription('Clears Grav cache') + ->addOption('all', null, InputOption::VALUE_NONE, 'If set will remove all including compiled, twig, doctrine caches') + ->addOption('assets-only', null, InputOption::VALUE_NONE, 'If set will remove only assets/*') + ->addOption('images-only', null, InputOption::VALUE_NONE, 'If set will remove only images/*') + ->addOption('cache-only', null, InputOption::VALUE_NONE, 'If set will remove only cache/*') + ->addOption('tmp-only', null, InputOption::VALUE_NONE, 'If set will remove only tmp/*') + ->setHelp('The clear-cache deletes all cache files'); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $this->cleanPaths(); + } + + /** + * loops over the array of paths and deletes the files/folders + */ + private function cleanPaths() + { + $this->output->writeln(''); + $this->output->writeln('Clearing cache'); + $this->output->writeln(''); + + if ($this->input->getOption('all')) { + $remove = 'all'; + } elseif ($this->input->getOption('assets-only')) { + $remove = 'assets-only'; + } elseif ($this->input->getOption('images-only')) { + $remove = 'images-only'; + } elseif ($this->input->getOption('cache-only')) { + $remove = 'cache-only'; + } elseif ($this->input->getOption('tmp-only')) { + $remove = 'tmp-only'; + } else { + $remove = 'standard'; + } + + foreach (Cache::clearCache($remove) as $result) { + $this->output->writeln($result); + } + } +} + diff --git a/system/src/Grav/Console/Cli/ComposerCommand.php b/system/src/Grav/Console/Cli/ComposerCommand.php new file mode 100644 index 0000000..4f9c18f --- /dev/null +++ b/system/src/Grav/Console/Cli/ComposerCommand.php @@ -0,0 +1,72 @@ +setName("composer") + ->addOption( + 'install', + 'i', + InputOption::VALUE_NONE, + 'install the dependencies' + ) + ->addOption( + 'update', + 'u', + InputOption::VALUE_NONE, + 'update the dependencies' + ) + ->setDescription("Updates the composer vendor dependencies needed by Grav.") + ->setHelp('The composer command updates the composer vendor dependencies needed by Grav'); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $action = $this->input->getOption('install') ? 'install' : ($this->input->getOption('update') ? 'update' : 'install'); + + if ($this->input->getOption('install')) { + $action = 'install'; + } + + // Updates composer first + $this->output->writeln("\nInstalling vendor dependencies"); + $this->output->writeln($this->composerUpdate(GRAV_ROOT, $action)); + } + +} diff --git a/system/src/Grav/Console/Cli/InstallCommand.php b/system/src/Grav/Console/Cli/InstallCommand.php new file mode 100644 index 0000000..ac00256 --- /dev/null +++ b/system/src/Grav/Console/Cli/InstallCommand.php @@ -0,0 +1,175 @@ +setName("install") + ->addOption( + 'symlink', + 's', + InputOption::VALUE_NONE, + 'Symlink the required bits' + ) + ->addArgument( + 'destination', + InputArgument::OPTIONAL, + 'Where to install the required bits (default to current project)' + ) + ->setDescription("Installs the dependencies needed by Grav. Optionally can create symbolic links") + ->setHelp('The install command installs the dependencies needed by Grav. Optionally can create symbolic links'); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $dependencies_file = '.dependencies'; + $this->destination = ($this->input->getArgument('destination')) ? $this->input->getArgument('destination') : ROOT_DIR; + + // fix trailing slash + $this->destination = rtrim($this->destination, DS) . DS; + $this->user_path = $this->destination . USER_PATH; + if ($local_config_file = $this->loadLocalConfig()) { + $this->output->writeln('Read local config from ' . $local_config_file . ''); + } + + // Look for dependencies file in ROOT and USER dir + if (file_exists($this->user_path . $dependencies_file)) { + $this->config = Yaml::parse(file_get_contents($this->user_path . $dependencies_file)); + } elseif (file_exists($this->destination . $dependencies_file)) { + $this->config = Yaml::parse(file_get_contents($this->destination . $dependencies_file)); + } else { + $this->output->writeln('ERROR Missing .dependencies file in user/ folder'); + if ($this->input->getArgument('destination')) { + $this->output->writeln('HINT Are you trying to install a plugin or a theme? Make sure you use bin/gpm install , not bin/grav install. This command is only used to install Grav skeletons.'); + } else { + $this->output->writeln('HINT Are you trying to install Grav? Grav is already installed. You need to run this command only if you download a skeleton from GitHub directly.'); + } + + return; + } + + // If yaml config, process + if ($this->config) { + if (!$this->input->getOption('symlink')) { + // Updates composer first + $this->output->writeln("\nInstalling vendor dependencies"); + $this->output->writeln($this->composerUpdate(GRAV_ROOT, 'install')); + + $this->gitclone(); + } else { + $this->symlink(); + } + } else { + $this->output->writeln('ERROR invalid YAML in ' . $dependencies_file); + } + + + } + + /** + * Clones from Git + */ + private function gitclone() + { + $this->output->writeln(''); + $this->output->writeln('Cloning Bits'); + $this->output->writeln('============'); + $this->output->writeln(''); + + foreach ($this->config['git'] as $repo => $data) { + $this->destination = rtrim($this->destination, DS); + $path = $this->destination . DS . $data['path']; + if (!file_exists($path)) { + exec('cd "' . $this->destination . '" && git clone -b ' . $data['branch'] . ' --depth 1 ' . $data['url'] . ' ' . $data['path'], $output, $return); + + if (!$return) { + $this->output->writeln('SUCCESS cloned ' . $data['url'] . ' -> ' . $path . ''); + } else { + $this->output->writeln('ERROR cloning ' . $data['url']); + + } + + $this->output->writeln(''); + } else { + $this->output->writeln('' . $path . ' already exists, skipping...'); + $this->output->writeln(''); + } + + } + } + + /** + * Symlinks + */ + private function symlink() + { + $this->output->writeln(''); + $this->output->writeln('Symlinking Bits'); + $this->output->writeln('==============='); + $this->output->writeln(''); + + if (!$this->local_config) { + $this->output->writeln('No local configuration available, aborting...'); + $this->output->writeln(''); + return; + } + + exec('cd ' . $this->destination); + foreach ($this->config['links'] as $repo => $data) { + $from = $this->local_config[$data['scm'] . '_repos'] . $data['src']; + $to = $this->destination . $data['path']; + + if (file_exists($from)) { + if (!file_exists($to)) { + symlink($from, $to); + $this->output->writeln('SUCCESS symlinked ' . $data['src'] . ' -> ' . $data['path'] . ''); + $this->output->writeln(''); + } else { + $this->output->writeln('destination: ' . $to . ' already exists, skipping...'); + $this->output->writeln(''); + } + } else { + $this->output->writeln('source: ' . $from . ' does not exists, skipping...'); + $this->output->writeln(''); + } + + } + } +} diff --git a/system/src/Grav/Console/Cli/NewProjectCommand.php b/system/src/Grav/Console/Cli/NewProjectCommand.php new file mode 100644 index 0000000..5a8f3d1 --- /dev/null +++ b/system/src/Grav/Console/Cli/NewProjectCommand.php @@ -0,0 +1,65 @@ +setName('new-project') + ->setAliases(['newproject']) + ->addArgument( + 'destination', + InputArgument::REQUIRED, + 'The destination directory of your new Grav project' + ) + ->addOption( + 'symlink', + 's', + InputOption::VALUE_NONE, + 'Symlink the required bits' + ) + ->setDescription('Creates a new Grav project with all the dependencies installed') + ->setHelp("The new-project command is a combination of the `setup` and `install` commands.\nCreates a new Grav instance and performs the installation of all the required dependencies."); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $sandboxCommand = $this->getApplication()->find('sandbox'); + $installCommand = $this->getApplication()->find('install'); + + $sandboxArguments = new ArrayInput([ + 'command' => 'sandbox', + 'destination' => $this->input->getArgument('destination'), + '-s' => $this->input->getOption('symlink') + ]); + + $installArguments = new ArrayInput([ + 'command' => 'install', + 'destination' => $this->input->getArgument('destination'), + '-s' => $this->input->getOption('symlink') + ]); + + $sandboxCommand->run($sandboxArguments, $this->output); + $installCommand->run($installArguments, $this->output); + + } +} diff --git a/system/src/Grav/Console/Cli/SandboxCommand.php b/system/src/Grav/Console/Cli/SandboxCommand.php new file mode 100644 index 0000000..284878e --- /dev/null +++ b/system/src/Grav/Console/Cli/SandboxCommand.php @@ -0,0 +1,304 @@ + '/.gitignore', + '/CHANGELOG.md' => '/CHANGELOG.md', + '/LICENSE.txt' => '/LICENSE.txt', + '/README.md' => '/README.md', + '/CONTRIBUTING.md' => '/CONTRIBUTING.md', + '/index.php' => '/index.php', + '/composer.json' => '/composer.json', + '/bin' => '/bin', + '/system' => '/system', + '/vendor' => '/vendor', + '/webserver-configs' => '/webserver-configs', + ]; + + /** + * @var string + */ + + protected $default_file = "---\ntitle: HomePage\n---\n# HomePage\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque porttitor eu felis sed ornare. Sed a mauris venenatis, pulvinar velit vel, dictum enim. Phasellus ac rutrum velit. Nunc lorem purus, hendrerit sit amet augue aliquet, iaculis ultricies nisl. Suspendisse tincidunt euismod risus, quis feugiat arcu tincidunt eget. Nulla eros mi, commodo vel ipsum vel, aliquet congue odio. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque velit orci, laoreet at adipiscing eu, interdum quis nibh. Nunc a accumsan purus."; + + protected $source; + protected $destination; + + /** + * + */ + protected function configure() + { + $this + ->setName('sandbox') + ->setDescription('Setup of a base Grav system in your webroot, good for development, playing around or starting fresh') + ->addArgument( + 'destination', + InputArgument::REQUIRED, + 'The destination directory to symlink into' + ) + ->addOption( + 'symlink', + 's', + InputOption::VALUE_NONE, + 'Symlink the base grav system' + ) + ->setHelp("The sandbox command help create a development environment that can optionally use symbolic links to link the core of grav to the git cloned repository.\nGood for development, playing around or starting fresh"); + $this->source = getcwd(); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $this->destination = $this->input->getArgument('destination'); + + // Symlink the Core Stuff + if ($this->input->getOption('symlink')) { + // Create Some core stuff if it doesn't exist + $this->createDirectories(); + + // Loop through the symlink mappings and create the symlinks + $this->symlink(); + + // Copy the Core STuff + } else { + // Create Some core stuff if it doesn't exist + $this->createDirectories(); + + // Loop through the symlink mappings and copy what otherwise would be symlinks + $this->copy(); + } + + $this->pages(); + $this->initFiles(); + $this->perms(); + } + + /** + * + */ + private function createDirectories() + { + $this->output->writeln(''); + $this->output->writeln('Creating Directories'); + $dirs_created = false; + + if (!file_exists($this->destination)) { + mkdir($this->destination, 0777, true); + } + + foreach ($this->directories as $dir) { + if (!file_exists($this->destination . $dir)) { + $dirs_created = true; + $this->output->writeln(' ' . $dir . ''); + mkdir($this->destination . $dir, 0777, true); + } + } + + if (!$dirs_created) { + $this->output->writeln(' Directories already exist'); + } + } + + /** + * + */ + private function copy() + { + $this->output->writeln(''); + $this->output->writeln('Copying Files'); + + + foreach ($this->mappings as $source => $target) { + if ((int)$source == $source) { + $source = $target; + } + + $from = $this->source . $source; + $to = $this->destination . $target; + + $this->output->writeln(' ' . $source . ' -> ' . $to); + @Folder::rcopy($from, $to); + } + } + + /** + * + */ + private function symlink() + { + $this->output->writeln(''); + $this->output->writeln('Resetting Symbolic Links'); + + + foreach ($this->mappings as $source => $target) { + if ((int)$source == $source) { + $source = $target; + } + + $from = $this->source . $source; + $to = $this->destination . $target; + + $this->output->writeln(' ' . $source . ' -> ' . $to); + + if (is_dir($to)) { + @Folder::delete($to); + } else { + @unlink($to); + } + symlink($from, $to); + } + } + + /** + * + */ + private function initFiles() + { + $this->check(); + + $this->output->writeln(''); + $this->output->writeln('File Initializing'); + $files_init = false; + + // Copy files if they do not exist + foreach ($this->files as $source => $target) { + if ((int)$source == $source) { + $source = $target; + } + + $from = $this->source . $source; + $to = $this->destination . $target; + + if (!file_exists($to)) { + $files_init = true; + copy($from, $to); + $this->output->writeln(' ' . $target . ' -> Created'); + } + } + + if (!$files_init) { + $this->output->writeln(' Files already exist'); + } + } + + /** + * + */ + private function pages() + { + $this->output->writeln(''); + $this->output->writeln('Pages Initializing'); + + // get pages files and initialize if no pages exist + $pages_dir = $this->destination . '/user/pages'; + $pages_files = array_diff(scandir($pages_dir), ['..', '.']); + + if (count($pages_files) == 0) { + $destination = $this->source . '/user/pages'; + Folder::rcopy($destination, $pages_dir); + $this->output->writeln(' ' . $destination . ' -> Created'); + + } + } + + /** + * + */ + private function perms() + { + $this->output->writeln(''); + $this->output->writeln('Permissions Initializing'); + + $dir_perms = 0755; + + $binaries = glob($this->destination . DS . 'bin' . DS . '*'); + + foreach ($binaries as $bin) { + chmod($bin, $dir_perms); + $this->output->writeln(' bin/' . basename($bin) . ' permissions reset to ' . decoct($dir_perms)); + } + + $this->output->writeln(""); + } + + /** + * + */ + private function check() + { + $success = true; + + if (!file_exists($this->destination)) { + $this->output->writeln(' file: $this->destination does not exist!'); + $success = false; + } + + foreach ($this->directories as $dir) { + if (!file_exists($this->destination . $dir)) { + $this->output->writeln(' directory: ' . $dir . ' does not exist!'); + $success = false; + } + } + + foreach ($this->mappings as $target => $link) { + if (!file_exists($this->destination . $target)) { + $this->output->writeln(' mappings: ' . $target . ' does not exist!'); + $success = false; + } + } + + if (!$success) { + $this->output->writeln(''); + $this->output->writeln('install should be run with --symlink|--s to symlink first'); + exit; + } + } +} diff --git a/system/src/Grav/Console/ConsoleCommand.php b/system/src/Grav/Console/ConsoleCommand.php new file mode 100644 index 0000000..a9c2217 --- /dev/null +++ b/system/src/Grav/Console/ConsoleCommand.php @@ -0,0 +1,47 @@ +setupConsole($input, $output); + $this->serve(); + } + + /** + * + */ + protected function serve() + { + + } + + protected function displayGPMRelease() + { + $this->output->writeln(''); + $this->output->writeln('GPM Releases Configuration: ' . ucfirst(Grav::instance()['config']->get('system.gpm.releases')) . ''); + $this->output->writeln(''); + } + +} diff --git a/system/src/Grav/Console/ConsoleTrait.php b/system/src/Grav/Console/ConsoleTrait.php new file mode 100644 index 0000000..b6ab3bf --- /dev/null +++ b/system/src/Grav/Console/ConsoleTrait.php @@ -0,0 +1,132 @@ +set('system.cache.cli_compatibility', true); + Grav::instance()['cache']; + + $this->argv = $_SERVER['argv'][0]; + $this->input = $input; + $this->output = $output; + + $this->output->getFormatter()->setStyle('normal', new OutputFormatterStyle('white')); + $this->output->getFormatter()->setStyle('yellow', new OutputFormatterStyle('yellow', null, array('bold'))); + $this->output->getFormatter()->setStyle('red', new OutputFormatterStyle('red', null, array('bold'))); + $this->output->getFormatter()->setStyle('cyan', new OutputFormatterStyle('cyan', null, array('bold'))); + $this->output->getFormatter()->setStyle('green', new OutputFormatterStyle('green', null, array('bold'))); + $this->output->getFormatter()->setStyle('magenta', new OutputFormatterStyle('magenta', null, array('bold'))); + $this->output->getFormatter()->setStyle('white', new OutputFormatterStyle('white', null, array('bold'))); + } + + /** + * @param $path + */ + public function isGravInstance($path) + { + if (!file_exists($path)) { + $this->output->writeln(''); + $this->output->writeln("ERROR: Destination doesn't exist:"); + $this->output->writeln(" $path"); + $this->output->writeln(''); + exit; + } + + if (!is_dir($path)) { + $this->output->writeln(''); + $this->output->writeln("ERROR: Destination chosen to install is not a directory:"); + $this->output->writeln(" $path"); + $this->output->writeln(''); + exit; + } + + if (!file_exists($path . DS . 'index.php') || !file_exists($path . DS . '.dependencies') || !file_exists($path . DS . 'system' . DS . 'config' . DS . 'system.yaml')) { + $this->output->writeln(''); + $this->output->writeln("ERROR: Destination chosen to install does not appear to be a Grav instance:"); + $this->output->writeln(" $path"); + $this->output->writeln(''); + exit; + } + } + + public function composerUpdate($path, $action = 'install') + { + $composer = Composer::getComposerExecutor(); + + return system($composer . ' --working-dir="'.$path.'" --no-interaction --no-dev --prefer-dist -o '. $action); + } + + /** + * @param array $all + * + * @return int + * @throws \Exception + */ + public function clearCache($all = []) + { + if ($all) { + $all = ['--all' => true]; + } + + $command = new ClearCacheCommand(); + $input = new ArrayInput($all); + return $command->run($input, $this->output); + } + + /** + * Load the local config file + * + * @return mixed string the local config file name. false if local config does not exist + */ + public function loadLocalConfig() + { + $home_folder = getenv('HOME') ?: getenv('HOMEDRIVE') . getenv('HOMEPATH'); + $local_config_file = $home_folder . '/.grav/config'; + + if (file_exists($local_config_file)) { + $this->local_config = Yaml::parse(file_get_contents($local_config_file)); + return $local_config_file; + } + + return false; + } +} diff --git a/system/src/Grav/Console/Gpm/DirectInstallCommand.php b/system/src/Grav/Console/Gpm/DirectInstallCommand.php new file mode 100644 index 0000000..60c5fa8 --- /dev/null +++ b/system/src/Grav/Console/Gpm/DirectInstallCommand.php @@ -0,0 +1,267 @@ +setName("direct-install") + ->setAliases(['directinstall']) + ->addArgument( + 'package-file', + InputArgument::REQUIRED, + 'Installable package local or remote . Can install specific version' + ) + ->addOption( + 'all-yes', + 'y', + InputOption::VALUE_NONE, + 'Assumes yes (or best approach) instead of prompting' + ) + ->addOption( + 'destination', + 'd', + InputOption::VALUE_OPTIONAL, + 'The destination where the package should be installed at. By default this would be where the grav instance has been launched from', + GRAV_ROOT + ) + ->setDescription("Installs Grav, plugin, or theme directly from a file or a URL") + ->setHelp('The direct-install command installs Grav, plugin, or theme directly from a file or a URL'); + } + + /** + * @return bool + */ + protected function serve() + { + // Making sure the destination is usable + $this->destination = realpath($this->input->getOption('destination')); + + if ( + !Installer::isGravInstance($this->destination) || + !Installer::isValidDestination($this->destination, [Installer::EXISTS, Installer::IS_LINK]) + ) { + $this->output->writeln("ERROR: " . Installer::lastErrorMsg()); + exit; + } + + + $this->all_yes = $this->input->getOption('all-yes'); + + $package_file = $this->input->getArgument('package-file'); + + $helper = $this->getHelper('question'); + $question = new ConfirmationQuestion('Are you sure you want to direct-install '.$package_file.' [y|N] ', false); + + $answer = $this->all_yes ? true : $helper->ask($this->input, $this->output, $question); + + if (!$answer) { + $this->output->writeln("exiting..."); + $this->output->writeln(''); + exit; + } + + $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true); + $tmp_zip = $tmp_dir . '/Grav-' . uniqid(); + + $this->output->writeln(""); + $this->output->writeln("Preparing to install " . $package_file . ""); + + + if (Response::isRemote($package_file)) { + $this->output->write(" |- Downloading package... 0%"); + try { + $zip = GPM::downloadPackage($package_file, $tmp_zip); + } catch (\RuntimeException $e) { + $this->output->writeln(''); + $this->output->writeln(" `- ERROR: " . $e->getMessage() . ""); + $this->output->writeln(''); + exit; + } + + if ($zip) { + $this->output->write("\x0D"); + $this->output->write(" |- Downloading package... 100%"); + $this->output->writeln(''); + } + } else { + $this->output->write(" |- Copying package... 0%"); + $zip = GPM::copyPackage($package_file, $tmp_zip); + if ($zip) { + $this->output->write("\x0D"); + $this->output->write(" |- Copying package... 100%"); + $this->output->writeln(''); + } + } + + if (file_exists($zip)) { + $tmp_source = $tmp_dir . '/Grav-' . uniqid(); + + $this->output->write(" |- Extracting package... "); + $extracted = Installer::unZip($zip, $tmp_source); + + if (!$extracted) { + $this->output->write("\x0D"); + $this->output->writeln(" |- Extracting package... failed"); + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + exit; + } + + $this->output->write("\x0D"); + $this->output->writeln(" |- Extracting package... ok"); + + + $type = GPM::getPackageType($extracted); + + if (!$type) { + $this->output->writeln(" '- ERROR: Not a valid Grav package"); + $this->output->writeln(''); + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + exit; + } + + $blueprint = GPM::getBlueprints($extracted); + if ($blueprint) { + if (isset($blueprint['dependencies'])) { + $depencencies = []; + foreach ($blueprint['dependencies'] as $dependency) { + if (is_array($dependency)){ + if (isset($dependency['name'])) { + $depencencies[] = $dependency['name']; + } + if (isset($dependency['github'])) { + $depencencies[] = $dependency['github']; + } + } else { + $depencencies[] = $dependency; + } + } + $this->output->writeln(" |- Dependencies found... [" . implode(',', $depencencies) . "]"); + + $question = new ConfirmationQuestion(" | '- Dependencies will not be satisfied. Continue ? [y|N] ", false); + $answer = $this->all_yes ? true : $helper->ask($this->input, $this->output, $question); + + if (!$answer) { + $this->output->writeln("exiting..."); + $this->output->writeln(''); + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + exit; + } + } + } + + if ($type == 'grav') { + + $this->output->write(" |- Checking destination... "); + Installer::isValidDestination(GRAV_ROOT . '/system'); + if (Installer::IS_LINK === Installer::lastErrorCode()) { + $this->output->write("\x0D"); + $this->output->writeln(" |- Checking destination... symbolic link"); + $this->output->writeln(" '- ERROR: symlinks found... " . GRAV_ROOT.""); + $this->output->writeln(''); + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + exit; + } + + $this->output->write("\x0D"); + $this->output->writeln(" |- Checking destination... ok"); + + $this->output->write(" |- Installing package... "); + Installer::install($zip, GRAV_ROOT, ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true], $extracted); + } else { + $name = GPM::getPackageName($extracted); + + if (!$name) { + $this->output->writeln("ERROR: Name could not be determined. Please specify with --name|-n"); + $this->output->writeln(''); + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + exit; + } + + $install_path = GPM::getInstallPath($type, $name); + $is_update = file_exists($install_path); + + $this->output->write(" |- Checking destination... "); + + Installer::isValidDestination(GRAV_ROOT . DS . $install_path); + if (Installer::lastErrorCode() == Installer::IS_LINK) { + $this->output->write("\x0D"); + $this->output->writeln(" |- Checking destination... symbolic link"); + $this->output->writeln(" '- ERROR: symlink found... " . GRAV_ROOT . DS . $install_path . ''); + $this->output->writeln(''); + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + exit; + + } else { + $this->output->write("\x0D"); + $this->output->writeln(" |- Checking destination... ok"); + } + + $this->output->write(" |- Installing package... "); + + Installer::install( + $zip, + $this->destination, + $options = [ + 'install_path' => $install_path, + 'theme' => (($type == 'theme')), + 'is_update' => $is_update + ], + $extracted + ); + } + + Folder::delete($tmp_source); + + $this->output->write("\x0D"); + + if(Installer::lastErrorCode()) { + $this->output->writeln(" '- " . Installer::lastErrorMsg() . ""); + $this->output->writeln(''); + } else { + $this->output->writeln(" |- Installing package... ok"); + $this->output->writeln(" '- Success! "); + $this->output->writeln(''); + } + + } else { + $this->output->writeln(" '- ERROR: ZIP package could not be found"); + } + + Folder::delete($tmp_zip); + + // clear cache after successful upgrade + $this->clearCache(); + + return true; + + } +} diff --git a/system/src/Grav/Console/Gpm/IndexCommand.php b/system/src/Grav/Console/Gpm/IndexCommand.php new file mode 100644 index 0000000..8c45706 --- /dev/null +++ b/system/src/Grav/Console/Gpm/IndexCommand.php @@ -0,0 +1,272 @@ +setName("index") + ->addOption( + 'force', + 'f', + InputOption::VALUE_NONE, + 'Force re-fetching the data from remote' + ) + ->addOption( + 'filter', + 'F', + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + 'Allows to limit the results based on one or multiple filters input. This can be either portion of a name/slug or a regex' + ) + ->addOption( + 'themes-only', + 'T', + InputOption::VALUE_NONE, + 'Filters the results to only Themes' + ) + ->addOption( + 'plugins-only', + 'P', + InputOption::VALUE_NONE, + 'Filters the results to only Plugins' + ) + ->addOption( + 'updates-only', + 'U', + InputOption::VALUE_NONE, + 'Filters the results to Updatable Themes and Plugins only' + ) + ->addOption( + 'installed-only', + 'I', + InputOption::VALUE_NONE, + 'Filters the results to only the Themes and Plugins you have installed' + ) + ->addOption( + 'sort', + 's', + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + 'Allows to sort (ASC) the results based on one or multiple keys. SORT can be either "name", "slug", "author", "date"', + ['date'] + ) + ->addOption( + 'desc', + 'D', + InputOption::VALUE_NONE, + 'Reverses the order of the output.' + ) + ->setDescription("Lists the plugins and themes available for installation") + ->setHelp('The index command lists the plugins and themes available for installation') + ; + } + + /** + * @return int|null|void + */ + protected function serve() + { + $this->options = $this->input->getOptions(); + $this->gpm = new GPM($this->options['force']); + $this->displayGPMRelease(); + $this->data = $this->gpm->getRepository(); + + $data = $this->filter($this->data); + + $climate = new CLImate; + $climate->extend('Grav\Console\TerminalObjects\Table'); + + if (!$data) { + $this->output->writeln('No data was found in the GPM repository stored locally.'); + $this->output->writeln('Please try clearing cache and running the bin/gpm index -f command again'); + $this->output->writeln('If this doesn\'t work try tweaking your GPM system settings.'); + $this->output->writeln(''); + $this->output->writeln('For more help go to:'); + $this->output->writeln(' -> https://learn.getgrav.org/troubleshooting/common-problems#cannot-connect-to-the-gpm'); + + die; + } + + foreach ($data as $type => $packages) { + $this->output->writeln("" . strtoupper($type) . " [ " . count($packages) . " ]"); + $packages = $this->sort($packages); + + if (!empty($packages)) { + + $table = []; + $index = 0; + + foreach ($packages as $slug => $package) { + $row = [ + 'Count' => $index++ + 1, + 'Name' => "" . Utils::truncate($package->name, 20, false, ' ', '...') . " ", + 'Slug' => $slug, + 'Version'=> $this->version($package), + 'Installed' => $this->installed($package) + ]; + $table[] = $row; + } + + $climate->table($table); + } + + $this->output->writeln(''); + } + + $this->output->writeln('You can either get more informations about a package by typing:'); + $this->output->writeln(' ' . $this->argv . ' info '); + $this->output->writeln(''); + $this->output->writeln('Or you can install a package by typing:'); + $this->output->writeln(' ' . $this->argv . ' install '); + $this->output->writeln(''); + } + + /** + * @param $package + * + * @return string + */ + private function version($package) + { + $list = $this->gpm->{'getUpdatable' . ucfirst($package->package_type)}(); + $package = isset($list[$package->slug]) ? $list[$package->slug] : $package; + $type = ucfirst(preg_replace("/s$/", '', $package->package_type)); + $updatable = $this->gpm->{'is' . $type . 'Updatable'}($package->slug); + $installed = $this->gpm->{'is' . $type . 'Installed'}($package->slug); + $local = $this->gpm->{'getInstalled' . $type}($package->slug); + + if (!$installed || !$updatable) { + $version = $installed ? $local->version : $package->version; + return "v" . $version . ""; + } + + if ($updatable) { + return "v" . $package->version . " -> v" . $package->available . ""; + } + + return ''; + } + + /** + * @param $package + * + * @return string + */ + private function installed($package) + { + $package = isset($list[$package->slug]) ? $list[$package->slug] : $package; + $type = ucfirst(preg_replace("/s$/", '', $package->package_type)); + $installed = $this->gpm->{'is' . $type . 'Installed'}($package->slug); + + return !$installed ? 'not installed' : 'installed'; + } + + /** + * @param $data + * + * @return mixed + */ + public function filter($data) + { + // filtering and sorting + if ($this->options['plugins-only']) { + unset($data['themes']); + } + if ($this->options['themes-only']) { + unset($data['plugins']); + } + + $filter = [ + $this->options['filter'], + $this->options['installed-only'], + $this->options['updates-only'], + $this->options['desc'] + ]; + + if (count(array_filter($filter))) { + foreach ($data as $type => $packages) { + foreach ($packages as $slug => $package) { + $filter = true; + + // Filtering by string + if ($this->options['filter']) { + $filter = preg_grep('/(' . (implode('|', $this->options['filter'])) . ')/i', [$slug, $package->name]); + } + + // Filtering updatables only + if ($this->options['installed-only'] && $filter) { + $method = ucfirst(preg_replace("/s$/", '', $package->package_type)); + $filter = $this->gpm->{'is' . $method . 'Installed'}($package->slug); + } + + // Filtering updatables only + if ($this->options['updates-only'] && $filter) { + $method = ucfirst(preg_replace("/s$/", '', $package->package_type)); + $filter = $this->gpm->{'is' . $method . 'Updatable'}($package->slug); + } + + if (!$filter) { + unset($data[$type][$slug]); + } + } + } + } + + return $data; + } + + /** + * @param $packages + */ + public function sort($packages) + { + foreach ($this->options['sort'] as $key) { + $packages = $packages->sort(function ($a, $b) use ($key) { + switch ($key) { + case 'author': + return strcmp($a->{$key}['name'], $b->{$key}['name']); + break; + default: + return strcmp($a->$key, $b->$key); + } + }, $this->options['desc'] ? true : false); + } + + return $packages; + } +} diff --git a/system/src/Grav/Console/Gpm/InfoCommand.php b/system/src/Grav/Console/Gpm/InfoCommand.php new file mode 100644 index 0000000..8c1d50e --- /dev/null +++ b/system/src/Grav/Console/Gpm/InfoCommand.php @@ -0,0 +1,181 @@ +setName("info") + ->addOption( + 'force', + 'f', + InputOption::VALUE_NONE, + 'Force fetching the new data remotely' + ) + ->addOption( + 'all-yes', + 'y', + InputOption::VALUE_NONE, + 'Assumes yes (or best approach) instead of prompting' + ) + ->addArgument( + 'package', + InputArgument::REQUIRED, + 'The package of which more informations are desired. Use the "index" command for a list of packages' + ) + ->setDescription("Shows more informations about a package") + ->setHelp('The info shows more informations about a package'); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $this->gpm = new GPM($this->input->getOption('force')); + + $this->all_yes = $this->input->getOption('all-yes'); + + $this->displayGPMRelease(); + + $foundPackage = $this->gpm->findPackage($this->input->getArgument('package')); + + if (!$foundPackage) { + $this->output->writeln("The package '" . $this->input->getArgument('package') . "' was not found in the Grav repository."); + $this->output->writeln(''); + $this->output->writeln("You can list all the available packages by typing:"); + $this->output->writeln(" " . $this->argv . " index"); + $this->output->writeln(''); + exit; + } + + $this->output->writeln("Found package '" . $this->input->getArgument('package') . "' under the '" . ucfirst($foundPackage->package_type) . "' section"); + $this->output->writeln(''); + $this->output->writeln("" . $foundPackage->name . " [" . $foundPackage->slug . "]"); + $this->output->writeln(str_repeat('-', strlen($foundPackage->name) + strlen($foundPackage->slug) + 3)); + $this->output->writeln("" . strip_tags($foundPackage->description_plain) . ""); + $this->output->writeln(''); + + $packageURL = ''; + if (isset($foundPackage->author['url'])) { + $packageURL = '<' . $foundPackage->author['url'] . '>'; + } + + $this->output->writeln("" . str_pad("Author", + 12) . ": " . $foundPackage->author['name'] . ' <' . $foundPackage->author['email'] . '> ' . $packageURL); + + foreach ([ + 'version', + 'keywords', + 'date', + 'homepage', + 'demo', + 'docs', + 'guide', + 'repository', + 'bugs', + 'zipball_url', + 'license' + ] as $info) { + if (isset($foundPackage->$info)) { + $name = ucfirst($info); + $data = $foundPackage->$info; + + if ($info == 'zipball_url') { + $name = "Download"; + } + + if ($info == 'date') { + $name = "Last Update"; + $data = date('D, j M Y, H:i:s, P ', strtotime('2014-09-16T00:07:16Z')); + } + + $name = str_pad($name, 12); + $this->output->writeln("" . $name . ": " . $data); + } + } + + $type = rtrim($foundPackage->package_type, 's'); + $updatable = $this->gpm->{'is' . $type . 'Updatable'}($foundPackage->slug); + $installed = $this->gpm->{'is' . $type . 'Installed'}($foundPackage->slug); + + // display current version if installed and different + if ($installed && $updatable) { + $local = $this->gpm->{'getInstalled'. $type}($foundPackage->slug); + $this->output->writeln(''); + $this->output->writeln("Currently installed version: " . $local->version . ""); + $this->output->writeln(''); + } + + // display changelog information + $questionHelper = $this->getHelper('question'); + $question = new ConfirmationQuestion("Would you like to read the changelog? [y|N] ", + false); + $answer = $this->all_yes ? true : $questionHelper->ask($this->input, $this->output, $question); + + if ($answer) { + $changelog = $foundPackage->changelog; + + $this->output->writeln(""); + foreach ($changelog as $version => $log) { + $title = $version . ' [' . $log['date'] . ']'; + $content = preg_replace_callback('/\d\.\s\[\]\(#(.*)\)/', function ($match) { + return "\n" . ucfirst($match[1]) . ":"; + }, $log['content']); + + $this->output->writeln(''.$title.''); + $this->output->writeln(str_repeat('-', strlen($title))); + $this->output->writeln($content); + $this->output->writeln(""); + + $question = new ConfirmationQuestion("Press [ENTER] to continue or [q] to quit ", true); + $answer = $this->all_yes ? false : $questionHelper->ask($this->input, $this->output, $question); + if (!$answer) { + break; + } + $this->output->writeln(""); + } + } + + $this->output->writeln(''); + + if ($installed && $updatable) { + $this->output->writeln("You can update this package by typing:"); + $this->output->writeln(" " . $this->argv . " update " . $foundPackage->slug . ""); + } else { + $this->output->writeln("You can install this package by typing:"); + $this->output->writeln(" " . $this->argv . " install " . $foundPackage->slug . ""); + } + + $this->output->writeln(''); + + } +} diff --git a/system/src/Grav/Console/Gpm/InstallCommand.php b/system/src/Grav/Console/Gpm/InstallCommand.php new file mode 100644 index 0000000..d7e932e --- /dev/null +++ b/system/src/Grav/Console/Gpm/InstallCommand.php @@ -0,0 +1,693 @@ +setName("install") + ->addOption( + 'force', + 'f', + InputOption::VALUE_NONE, + 'Force re-fetching the data from remote' + ) + ->addOption( + 'all-yes', + 'y', + InputOption::VALUE_NONE, + 'Assumes yes (or best approach) instead of prompting' + ) + ->addOption( + 'destination', + 'd', + InputOption::VALUE_OPTIONAL, + 'The destination where the package should be installed at. By default this would be where the grav instance has been launched from', + GRAV_ROOT + ) + ->addArgument( + 'package', + InputArgument::IS_ARRAY | InputArgument::REQUIRED, + 'Package(s) to install. Use "bin/gpm index" to list packages. Use "bin/gpm direct-install" to install a specific version' + ) + ->setDescription("Performs the installation of plugins and themes") + ->setHelp('The install command allows to install plugins and themes'); + } + + /** + * Allows to set the GPM object, used for testing the class + * + * @param $gpm + */ + public function setGpm($gpm) + { + $this->gpm = $gpm; + } + + /** + * @return bool + */ + protected function serve() + { + $this->gpm = new GPM($this->input->getOption('force')); + + $this->all_yes = $this->input->getOption('all-yes'); + + $this->displayGPMRelease(); + + $this->destination = realpath($this->input->getOption('destination')); + + $packages = array_map('strtolower', $this->input->getArgument('package')); + $this->data = $this->gpm->findPackages($packages); + $this->loadLocalConfig(); + + if ( + !Installer::isGravInstance($this->destination) || + !Installer::isValidDestination($this->destination, [Installer::EXISTS, Installer::IS_LINK]) + ) { + $this->output->writeln("ERROR: " . Installer::lastErrorMsg()); + exit; + } + + $this->output->writeln(''); + + if (!$this->data['total']) { + $this->output->writeln("Nothing to install."); + $this->output->writeln(''); + exit; + } + + if (count($this->data['not_found'])) { + $this->output->writeln("These packages were not found on Grav: " . implode(', ', + array_keys($this->data['not_found'])) . ""); + } + + unset($this->data['not_found']); + unset($this->data['total']); + + + if (isset($this->local_config)) { + // Symlinks available, ask if Grav should use them + $this->use_symlinks = false; + $helper = $this->getHelper('question'); + $question = new ConfirmationQuestion('Should Grav use the symlinks if available? [y|N] ', false); + + $answer = $this->all_yes ? false : $helper->ask($this->input, $this->output, $question); + + if ($answer) { + $this->use_symlinks = true; + } + + + } + + $this->output->writeln(''); + + try { + $dependencies = $this->gpm->getDependencies($packages); + } catch (\Exception $e) { + //Error out if there are incompatible packages requirements and tell which ones, and what to do + //Error out if there is any error in parsing the dependencies and their versions, and tell which one is broken + $this->output->writeln("" . $e->getMessage() . ""); + return false; + } + + if ($dependencies) { + try { + $this->installDependencies($dependencies, 'install', "The following dependencies need to be installed..."); + $this->installDependencies($dependencies, 'update', "The following dependencies need to be updated..."); + $this->installDependencies($dependencies, 'ignore', "The following dependencies can be updated as there is a newer version, but it's not mandatory...", false); + } catch (\Exception $e) { + $this->output->writeln("Installation aborted"); + return false; + } + + $this->output->writeln("Dependencies are OK"); + $this->output->writeln(""); + } + + + //We're done installing dependencies. Install the actual packages + foreach ($this->data as $data) { + foreach ($data as $package_name => $package) { + if (array_key_exists($package_name, $dependencies)) { + $this->output->writeln("Package " . $package_name . " already installed as dependency"); + } else { + $is_valid_destination = Installer::isValidDestination($this->destination . DS . $package->install_path); + if ($is_valid_destination || Installer::lastErrorCode() == Installer::NOT_FOUND) { + $this->processPackage($package, false); + } else { + if (Installer::lastErrorCode() == Installer::EXISTS) { + + try { + $this->askConfirmationIfMajorVersionUpdated($package); + $this->gpm->checkNoOtherPackageNeedsThisDependencyInALowerVersion($package->slug, $package->available, array_keys($data)); + } catch (\Exception $e) { + $this->output->writeln("" . $e->getMessage() . ""); + return false; + } + + $helper = $this->getHelper('question'); + $question = new ConfirmationQuestion("The package $package_name is already installed, overwrite? [y|N] ", false); + $answer = $this->all_yes ? true : $helper->ask($this->input, $this->output, $question); + + if ($answer) { + $is_update = true; + $this->processPackage($package, $is_update); + } else { + $this->output->writeln("Package " . $package_name . " not overwritten"); + } + } else { + if (Installer::lastErrorCode() == Installer::IS_LINK) { + $this->output->writeln("Cannot overwrite existing symlink for $package_name"); + $this->output->writeln(""); + } + } + } + } + } + } + + if (count($this->demo_processing) > 0) { + foreach ($this->demo_processing as $package) { + $this->installDemoContent($package); + } + } + + // clear cache after successful upgrade + $this->clearCache(); + + return true; + } + + /** + * If the package is updated from an older major release, show warning and ask confirmation + * + * @param $package + */ + public function askConfirmationIfMajorVersionUpdated($package) + { + $helper = $this->getHelper('question'); + $package_name = $package->name; + $new_version = $package->available ? $package->available : $this->gpm->getLatestVersionOfPackage($package->slug); + $old_version = $package->version; + + $major_version_changed = explode('.', $new_version)[0] !== explode('.', $old_version)[0]; + + if ($major_version_changed) { + if ($this->all_yes) { + $this->output->writeln("The package $package_name will be updated to a new major version $new_version, from $old_version"); + return; + } + + $question = new ConfirmationQuestion("The package $package_name will be updated to a new major version $new_version, from $old_version. Be sure to read what changed with the new major release. Continue? [y|N] ", false); + + if (!$helper->ask($this->input, $this->output, $question)) { + $this->output->writeln("Package " . $package_name . " not updated"); + exit; + } + } + } + + /** + * Given a $dependencies list, filters their type according to $type and + * shows $message prior to listing them to the user. Then asks the user a confirmation prior + * to installing them. + * + * @param array $dependencies The dependencies array + * @param string $type The type of dependency to show: install, update, ignore + * @param string $message A message to be shown prior to listing the dependencies + * @param bool $required A flag that determines if the installation is required or optional + * + * @throws \Exception + */ + public function installDependencies($dependencies, $type, $message, $required = true) + { + $packages = array_filter($dependencies, function ($action) use ($type) { return $action === $type; }); + if (count($packages) > 0) { + $this->output->writeln($message); + + foreach ($packages as $dependencyName => $dependencyVersion) { + $this->output->writeln(" |- Package " . $dependencyName . ""); + } + + $this->output->writeln(""); + + $helper = $this->getHelper('question'); + + if ($type == 'install') { + $questionAction = 'Install'; + } else { + $questionAction = 'Update'; + } + + if (count($packages) == 1) { + $questionArticle = 'this'; + } else { + $questionArticle = 'these'; + } + + if (count($packages) == 1) { + $questionNoun = 'package'; + } else { + $questionNoun = 'packages'; + } + + $question = new ConfirmationQuestion("$questionAction $questionArticle $questionNoun? [Y|n] ", true); + $answer = $this->all_yes ? true : $helper->ask($this->input, $this->output, $question); + + if ($answer) { + foreach ($packages as $dependencyName => $dependencyVersion) { + $package = $this->gpm->findPackage($dependencyName); + $this->processPackage($package, ($type == 'update') ? true : false); + } + $this->output->writeln(''); + } else { + if ($required) { + throw new \Exception(); + } + } + } + } + + /** + * @param $package + * @param bool $is_update True if the package is an update + */ + private function processPackage($package, $is_update = false) + { + if (!$package) { + $this->output->writeln("Package not found on the GPM! "); + $this->output->writeln(''); + return; + } + + $symlink = false; + if ($this->use_symlinks) { + if ($this->getSymlinkSource($package) || !isset($package->version)) { + $symlink = true; + } + } + + $symlink ? $this->processSymlink($package) : $this->processGpm($package, $is_update); + + $this->processDemo($package); + } + + /** + * Add package to the queue to process the demo content, if demo content exists + * + * @param $package + */ + private function processDemo($package) + { + $demo_dir = $this->destination . DS . $package->install_path . DS . '_demo'; + if (file_exists($demo_dir)) { + $this->demo_processing[] = $package; + } + } + + /** + * Prompt to install the demo content of a package + * + * @param $package + */ + private function installDemoContent($package) + { + $demo_dir = $this->destination . DS . $package->install_path . DS . '_demo'; + + if (file_exists($demo_dir)) { + $dest_dir = $this->destination . DS . 'user'; + $pages_dir = $dest_dir . DS . 'pages'; + + // Demo content exists, prompt to install it. + $this->output->writeln("Attention: " . $package->name . " contains demo content"); + $helper = $this->getHelper('question'); + $question = new ConfirmationQuestion('Do you wish to install this demo content? [y|N] ', false); + + $answer = $this->all_yes ? true : $helper->ask($this->input, $this->output, $question); + + if (!$answer) { + $this->output->writeln(" '- Skipped! "); + $this->output->writeln(''); + + return; + } + + // if pages folder exists in demo + if (file_exists($demo_dir . DS . 'pages')) { + $pages_backup = 'pages.' . date('m-d-Y-H-i-s'); + $question = new ConfirmationQuestion('This will backup your current `user/pages` folder to `user/' . $pages_backup . '`, continue? [y|N]', false); + $answer = $this->all_yes ? true : $helper->ask($this->input, $this->output, $question); + + if (!$answer) { + $this->output->writeln(" '- Skipped! "); + $this->output->writeln(''); + + return; + } + + // backup current pages folder + if (file_exists($dest_dir)) { + if (rename($pages_dir, $dest_dir . DS . $pages_backup)) { + $this->output->writeln(" |- Backing up pages... ok"); + } else { + $this->output->writeln(" |- Backing up pages... failed"); + } + } + } + + // Confirmation received, copy over the data + $this->output->writeln(" |- Installing demo content... ok "); + Folder::rcopy($demo_dir, $dest_dir); + $this->output->writeln(" '- Success! "); + $this->output->writeln(''); + } + } + + /** + * @param $package + * + * @return array|bool + */ + private function getGitRegexMatches($package) + { + if (isset($package->repository)) { + $repository = $package->repository; + } else { + return false; + } + + preg_match(GIT_REGEX, $repository, $matches); + + return $matches; + } + + /** + * @param $package + * + * @return bool|string + */ + private function getSymlinkSource($package) + { + $matches = $this->getGitRegexMatches($package); + + foreach ($this->local_config as $path) { + if (Utils::endsWith($matches[2], '.git')) { + $repo_dir = preg_replace('/\.git$/', '', $matches[2]); + } else { + $repo_dir = $matches[2]; + } + + $from = rtrim($path, '/') . '/' . $repo_dir; + + if (file_exists($from)) { + return $from; + } + } + + return false; + } + + /** + * @param $package + */ + private function processSymlink($package) + { + + exec('cd ' . $this->destination); + + $to = $this->destination . DS . $package->install_path; + $from = $this->getSymlinkSource($package); + + $this->output->writeln("Preparing to Symlink " . $package->name . ""); + $this->output->write(" |- Checking source... "); + + if (file_exists($from)) { + $this->output->writeln("ok"); + + $this->output->write(" |- Checking destination... "); + $checks = $this->checkDestination($package); + + if (!$checks) { + $this->output->writeln(" '- Installation failed or aborted."); + $this->output->writeln(''); + } else { + if (file_exists($to)) { + $this->output->writeln(" '- Symlink cannot overwrite an existing package, please remove first"); + $this->output->writeln(''); + } else { + symlink($from, $to); + + // extra white spaces to clear out the buffer properly + $this->output->writeln(" |- Symlinking package... ok "); + $this->output->writeln(" '- Success! "); + $this->output->writeln(''); + } + } + + return; + } + + $this->output->writeln("not found!"); + $this->output->writeln(" '- Installation failed or aborted."); + } + + /** + * @param $package + * @param bool $is_update + * + * @return bool + */ + private function processGpm($package, $is_update = false) + { + $version = isset($package->available) ? $package->available : $package->version; + $license = Licenses::get($package->slug); + + $this->output->writeln("Preparing to install " . $package->name . " [v" . $version . "]"); + + $this->output->write(" |- Downloading package... 0%"); + $this->file = $this->downloadPackage($package, $license); + + if (!$this->file) { + $this->output->writeln(" '- Installation failed or aborted."); + $this->output->writeln(''); + + return false; + } + + $this->output->write(" |- Checking destination... "); + $checks = $this->checkDestination($package); + + if (!$checks) { + $this->output->writeln(" '- Installation failed or aborted."); + $this->output->writeln(''); + } else { + $this->output->write(" |- Installing package... "); + $installation = $this->installPackage($package, $is_update); + if (!$installation) { + $this->output->writeln(" '- Installation failed or aborted."); + $this->output->writeln(''); + } else { + $this->output->writeln(" '- Success! "); + $this->output->writeln(''); + + return true; + } + } + + return false; + } + + /** + * @param Package $package + * + * @param string $license + * + * @return string + */ + private function downloadPackage($package, $license = null) + { + $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true); + $this->tmp = $tmp_dir . '/Grav-' . uniqid(); + $filename = $package->slug . basename($package->zipball_url); + $filename = preg_replace('/[\\\\\/:"*?&<>|]+/mi', '-', $filename); + $query = ''; + + if ($package->premium) { + $query = \json_encode(array_merge( + $package->premium, + [ + 'slug' => $package->slug, + 'filename' => $package->premium['filename'], + 'license_key' => $license + ] + )); + + $query = '?d=' . base64_encode($query); + } + + try { + $output = Response::get($package->zipball_url . $query, [], [$this, 'progress']); + } catch (\Exception $e) { + $error = str_replace("\n", "\n | '- ", $e->getMessage()); + $this->output->write("\x0D"); + // extra white spaces to clear out the buffer properly + $this->output->writeln(" |- Downloading package... error "); + $this->output->writeln(" | '- " . $error); + + return false; + } + + Folder::mkdir($this->tmp); + + $this->output->write("\x0D"); + $this->output->write(" |- Downloading package... 100%"); + $this->output->writeln(''); + + file_put_contents($this->tmp . DS . $filename, $output); + + return $this->tmp . DS . $filename; + } + + /** + * @param $package + * + * @return bool + */ + private function checkDestination($package) + { + $question_helper = $this->getHelper('question'); + + Installer::isValidDestination($this->destination . DS . $package->install_path); + + if (Installer::lastErrorCode() == Installer::IS_LINK) { + $this->output->write("\x0D"); + $this->output->writeln(" |- Checking destination... symbolic link"); + + if ($this->all_yes) { + $this->output->writeln(" | '- Skipped automatically."); + + return false; + } + + $question = new ConfirmationQuestion(" | '- Destination has been detected as symlink, delete symbolic link first? [y|N] ", + false); + $answer = $question_helper->ask($this->input, $this->output, $question); + + if (!$answer) { + $this->output->writeln(" | '- You decided to not delete the symlink automatically."); + + return false; + } else { + unlink($this->destination . DS . $package->install_path); + } + } + + $this->output->write("\x0D"); + $this->output->writeln(" |- Checking destination... ok"); + + return true; + } + + /** + * Install a package + * + * @param Package $package + * @param bool $is_update True if it's an update. False if it's an install + * + * @return bool + */ + private function installPackage($package, $is_update = false) + { + $type = $package->package_type; + + Installer::install($this->file, $this->destination, ['install_path' => $package->install_path, 'theme' => (($type == 'themes')), 'is_update' => $is_update]); + $error_code = Installer::lastErrorCode(); + Folder::delete($this->tmp); + + if ($error_code) { + $this->output->write("\x0D"); + // extra white spaces to clear out the buffer properly + $this->output->writeln(" |- Installing package... error "); + $this->output->writeln(" | '- " . Installer::lastErrorMsg()); + + return false; + } + + $message = Installer::getMessage(); + if ($message) { + $this->output->write("\x0D"); + // extra white spaces to clear out the buffer properly + $this->output->writeln(" |- " . $message); + } + + $this->output->write("\x0D"); + // extra white spaces to clear out the buffer properly + $this->output->writeln(" |- Installing package... ok "); + + return true; + } + + /** + * @param $progress + */ + public function progress($progress) + { + $this->output->write("\x0D"); + $this->output->write(" |- Downloading package... " . str_pad($progress['percent'], 5, " ", + STR_PAD_LEFT) . '%'); + } +} diff --git a/system/src/Grav/Console/Gpm/SelfupgradeCommand.php b/system/src/Grav/Console/Gpm/SelfupgradeCommand.php new file mode 100644 index 0000000..d406a95 --- /dev/null +++ b/system/src/Grav/Console/Gpm/SelfupgradeCommand.php @@ -0,0 +1,262 @@ +setName("self-upgrade") + ->setAliases(['selfupgrade', 'selfupdate']) + ->addOption( + 'force', + 'f', + InputOption::VALUE_NONE, + 'Force re-fetching the data from remote' + ) + ->addOption( + 'all-yes', + 'y', + InputOption::VALUE_NONE, + 'Assumes yes (or best approach) instead of prompting' + ) + ->addOption( + 'overwrite', + 'o', + InputOption::VALUE_NONE, + 'Option to overwrite packages if they already exist' + ) + ->setDescription("Detects and performs an update of Grav itself when available") + ->setHelp('The update command updates Grav itself when a new version is available'); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $this->upgrader = new Upgrader($this->input->getOption('force')); + $this->all_yes = $this->input->getOption('all-yes'); + $this->overwrite = $this->input->getOption('overwrite'); + + $this->displayGPMRelease(); + + $update = $this->upgrader->getAssets()['grav-update']; + + $local = $this->upgrader->getLocalVersion(); + $remote = $this->upgrader->getRemoteVersion(); + $release = strftime('%c', strtotime($this->upgrader->getReleaseDate())); + + if (!$this->upgrader->meetsRequirements()) { + $this->output->writeln("ATTENTION:"); + $this->output->writeln(" Grav has increased the minimum PHP requirement."); + $this->output->writeln(" You are currently running PHP " . phpversion() . ", but PHP " . $this->upgrader->minPHPVersion() . " is required."); + $this->output->writeln(" Additional information: http://getgrav.org/blog/changing-php-requirements"); + $this->output->writeln(""); + $this->output->writeln("Selfupgrade aborted."); + $this->output->writeln(""); + exit; + } + + if (!$this->overwrite && !$this->upgrader->isUpgradable()) { + $this->output->writeln("You are already running the latest version of Grav (v" . $local . ") released on " . $release); + exit; + } + + Installer::isValidDestination(GRAV_ROOT . '/system'); + if (Installer::IS_LINK === Installer::lastErrorCode()) { + $this->output->writeln("ATTENTION: Grav is symlinked, cannot upgrade, aborting..."); + $this->output->writeln(''); + $this->output->writeln("You are currently running a symbolically linked Grav v" . $local . ". Latest available is v". $remote . "."); + exit; + } + + // not used but preloaded just in case! + new ArrayInput([]); + + $questionHelper = $this->getHelper('question'); + + + $this->output->writeln("Grav v$remote is now available [release date: $release]."); + $this->output->writeln("You are currently using v" . GRAV_VERSION . "."); + + if (!$this->all_yes) { + $question = new ConfirmationQuestion("Would you like to read the changelog before proceeding? [y|N] ", + false); + $answer = $questionHelper->ask($this->input, $this->output, $question); + + if ($answer) { + $changelog = $this->upgrader->getChangelog(GRAV_VERSION); + + $this->output->writeln(""); + foreach ($changelog as $version => $log) { + $title = $version . ' [' . $log['date'] . ']'; + $content = preg_replace_callback('/\d\.\s\[\]\(#(.*)\)/', function ($match) { + return "\n" . ucfirst($match[1]) . ":"; + }, $log['content']); + + $this->output->writeln($title); + $this->output->writeln(str_repeat('-', strlen($title))); + $this->output->writeln($content); + $this->output->writeln(""); + } + + $question = new ConfirmationQuestion("Press [ENTER] to continue.", true); + $questionHelper->ask($this->input, $this->output, $question); + } + + $question = new ConfirmationQuestion("Would you like to upgrade now? [y|N] ", false); + $answer = $questionHelper->ask($this->input, $this->output, $question); + + if (!$answer) { + $this->output->writeln("Aborting..."); + + exit; + } + } + + $this->output->writeln(""); + $this->output->writeln("Preparing to upgrade to v$remote.."); + + $this->output->write(" |- Downloading upgrade [" . $this->formatBytes($update['size']) . "]... 0%"); + $this->file = $this->download($update); + + $this->output->write(" |- Installing upgrade... "); + $installation = $this->upgrade(); + + if (!$installation) { + $this->output->writeln(" '- Installation failed or aborted."); + $this->output->writeln(''); + } else { + $this->output->writeln(" '- Success! "); + $this->output->writeln(''); + } + + // clear cache after successful upgrade + $this->clearCache('all'); + } + + /** + * @param $package + * + * @return string + */ + private function download($package) + { + $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true); + $this->tmp = $tmp_dir . '/Grav-' . uniqid(); + $output = Response::get($package['download'], [], [$this, 'progress']); + + Folder::mkdir($this->tmp); + + $this->output->write("\x0D"); + $this->output->write(" |- Downloading upgrade [" . $this->formatBytes($package['size']) . "]... 100%"); + $this->output->writeln(''); + + file_put_contents($this->tmp . DS . $package['name'], $output); + + return $this->tmp . DS . $package['name']; + } + + /** + * @return bool + */ + private function upgrade() + { + Installer::install($this->file, GRAV_ROOT, + ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true]); + $errorCode = Installer::lastErrorCode(); + Folder::delete($this->tmp); + + if ($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)) { + $this->output->write("\x0D"); + // extra white spaces to clear out the buffer properly + $this->output->writeln(" |- Installing upgrade... error "); + $this->output->writeln(" | '- " . Installer::lastErrorMsg()); + + return false; + } + + $this->output->write("\x0D"); + // extra white spaces to clear out the buffer properly + $this->output->writeln(" |- Installing upgrade... ok "); + + return true; + } + + /** + * @param $progress + */ + public function progress($progress) + { + $this->output->write("\x0D"); + $this->output->write(" |- Downloading upgrade [" . $this->formatBytes($progress["filesize"]) . "]... " . str_pad($progress['percent'], + 5, " ", STR_PAD_LEFT) . '%'); + } + + /** + * @param $size + * @param int $precision + * + * @return string + */ + public function formatBytes($size, $precision = 2) + { + $base = log($size) / log(1024); + $suffixes = array('', 'k', 'M', 'G', 'T'); + + return round(pow(1024, $base - floor($base)), $precision) . $suffixes[(int)floor($base)]; + } +} diff --git a/system/src/Grav/Console/Gpm/UninstallCommand.php b/system/src/Grav/Console/Gpm/UninstallCommand.php new file mode 100644 index 0000000..34b04ee --- /dev/null +++ b/system/src/Grav/Console/Gpm/UninstallCommand.php @@ -0,0 +1,302 @@ +setName("uninstall") + ->addOption( + 'all-yes', + 'y', + InputOption::VALUE_NONE, + 'Assumes yes (or best approach) instead of prompting' + ) + ->addArgument( + 'package', + InputArgument::IS_ARRAY | InputArgument::REQUIRED, + 'The package(s) that are desired to be removed. Use the "index" command for a list of packages' + ) + ->setDescription("Performs the uninstallation of plugins and themes") + ->setHelp('The uninstall command allows to uninstall plugins and themes'); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $this->gpm = new GPM(); + + $this->all_yes = $this->input->getOption('all-yes'); + + $packages = array_map('strtolower', $this->input->getArgument('package')); + $this->data = ['total' => 0, 'not_found' => []]; + + foreach ($packages as $package) { + $plugin = $this->gpm->getInstalledPlugin($package); + $theme = $this->gpm->getInstalledTheme($package); + if ($plugin || $theme) { + $this->data[strtolower($package)] = $plugin ?: $theme; + $this->data['total']++; + } else { + $this->data['not_found'][] = $package; + } + } + + $this->output->writeln(''); + + if (!$this->data['total']) { + $this->output->writeln("Nothing to uninstall."); + $this->output->writeln(''); + exit; + } + + if (count($this->data['not_found'])) { + $this->output->writeln("These packages were not found installed: " . implode(', ', + $this->data['not_found']) . ""); + } + + unset($this->data['not_found']); + unset($this->data['total']); + + foreach ($this->data as $slug => $package) { + $this->output->writeln("Preparing to uninstall " . $package->name . " [v" . $package->version . "]"); + + $this->output->write(" |- Checking destination... "); + $checks = $this->checkDestination($slug, $package); + + if (!$checks) { + $this->output->writeln(" '- Installation failed or aborted."); + $this->output->writeln(''); + } else { + $uninstall = $this->uninstallPackage($slug, $package); + + if (!$uninstall) { + $this->output->writeln(" '- Uninstallation failed or aborted."); + } else { + $this->output->writeln(" '- Success! "); + } + } + + } + + // clear cache after successful upgrade + $this->clearCache(); + } + + + /** + * @param $slug + * @param $package + * + * @return bool + */ + private function uninstallPackage($slug, $package, $is_dependency = false) + { + if (!$slug) { + return false; + } + + //check if there are packages that have this as a dependency. Abort and show list + $dependent_packages = $this->gpm->getPackagesThatDependOnPackage($slug); + if (count($dependent_packages) > ($is_dependency ? 1 : 0)) { + $this->output->writeln(''); + $this->output->writeln(''); + $this->output->writeln("Uninstallation failed."); + $this->output->writeln(''); + if (count($dependent_packages) > ($is_dependency ? 2 : 1)) { + $this->output->writeln("The installed packages " . implode(', ', $dependent_packages) . " depends on this package. Please remove those first."); + } else { + $this->output->writeln("The installed package " . implode(', ', $dependent_packages) . " depends on this package. Please remove it first."); + } + + $this->output->writeln(''); + return false; + } + + if (isset($package->dependencies)) { + + $dependencies = $package->dependencies; + + if ($is_dependency) { + foreach ($dependencies as $key => $dependency) { + if (in_array($dependency['name'], $this->dependencies)) { + unset($dependencies[$key]); + } + } + } else { + if (count($dependencies) > 0) { + $this->output->writeln(' `- Dependencies found...'); + $this->output->writeln(''); + } + } + + $questionHelper = $this->getHelper('question'); + + foreach ($dependencies as $dependency) { + + $this->dependencies[] = $dependency['name']; + + if (is_array($dependency)) { + $dependency = $dependency['name']; + } + if ($dependency === 'grav' || $dependency === 'php') { + continue; + } + + $dependencyPackage = $this->gpm->findPackage($dependency); + + $dependency_exists = $this->packageExists($dependency, $dependencyPackage); + + if ($dependency_exists == Installer::EXISTS) { + $this->output->writeln("A dependency on " . $dependencyPackage->name . " [v" . $dependencyPackage->version . "] was found"); + + $question = new ConfirmationQuestion(" |- Uninstall " . $dependencyPackage->name . "? [y|N] ", false); + $answer = $this->all_yes ? true : $questionHelper->ask($this->input, $this->output, $question); + + if ($answer) { + $uninstall = $this->uninstallPackage($dependency, $dependencyPackage, true); + + if (!$uninstall) { + $this->output->writeln(" '- Uninstallation failed or aborted."); + } else { + $this->output->writeln(" '- Success! "); + + } + $this->output->writeln(''); + } else { + $this->output->writeln(" '- You decided not to uninstall " . $dependencyPackage->name . "."); + $this->output->writeln(''); + } + } + + } + } + + + $locator = Grav::instance()['locator']; + $path = $locator->findResource($package->package_type . '://' . $slug); + Installer::uninstall($path); + $errorCode = Installer::lastErrorCode(); + + if ($errorCode && $errorCode !== Installer::IS_LINK && $errorCode !== Installer::EXISTS) { + $this->output->writeln(" |- Uninstalling " . $package->name . " package... error "); + $this->output->writeln(" | '- " . Installer::lastErrorMsg().""); + + return false; + } + + $message = Installer::getMessage(); + if ($message) { + $this->output->writeln(" |- " . $message); + } + + if (!$is_dependency && $this->dependencies) { + $this->output->writeln("Finishing up uninstalling " . $package->name . ""); + } + $this->output->writeln(" |- Uninstalling " . $package->name . " package... ok "); + + + + return true; + } + + /** + * @param $slug + * @param $package + * + * @return bool + */ + + private function checkDestination($slug, $package) + { + $questionHelper = $this->getHelper('question'); + + $exists = $this->packageExists($slug, $package); + + if ($exists == Installer::IS_LINK) { + $this->output->write("\x0D"); + $this->output->writeln(" |- Checking destination... symbolic link"); + + if ($this->all_yes) { + $this->output->writeln(" | '- Skipped automatically."); + + return false; + } + + $question = new ConfirmationQuestion(" | '- Destination has been detected as symlink, delete symbolic link first? [y|N] ", + false); + $answer = $this->all_yes ? true : $questionHelper->ask($this->input, $this->output, $question); + + if (!$answer) { + $this->output->writeln(" | '- You decided not to delete the symlink automatically."); + + return false; + } + } + + $this->output->write("\x0D"); + $this->output->writeln(" |- Checking destination... ok"); + + return true; + } + + /** + * Check if package exists + * + * @param $slug + * @param $package + * @return int + */ + private function packageExists($slug, $package) + { + $path = Grav::instance()['locator']->findResource($package->package_type . '://' . $slug); + Installer::isValidDestination($path); + return Installer::lastErrorCode(); + } +} diff --git a/system/src/Grav/Console/Gpm/UpdateCommand.php b/system/src/Grav/Console/Gpm/UpdateCommand.php new file mode 100644 index 0000000..06913b1 --- /dev/null +++ b/system/src/Grav/Console/Gpm/UpdateCommand.php @@ -0,0 +1,285 @@ +setName("update") + ->addOption( + 'force', + 'f', + InputOption::VALUE_NONE, + 'Force re-fetching the data from remote' + ) + ->addOption( + 'destination', + 'd', + InputOption::VALUE_OPTIONAL, + 'The grav instance location where the updates should be applied to. By default this would be where the grav cli has been launched from', + GRAV_ROOT + ) + ->addOption( + 'all-yes', + 'y', + InputOption::VALUE_NONE, + 'Assumes yes (or best approach) instead of prompting' + ) + ->addOption( + 'overwrite', + 'o', + InputOption::VALUE_NONE, + 'Option to overwrite packages if they already exist' + ) + ->addOption( + 'plugins', + 'p', + InputOption::VALUE_NONE, + 'Update only plugins' + ) + ->addOption( + 'themes', + 't', + InputOption::VALUE_NONE, + 'Update only themes' + ) + ->addArgument( + 'package', + InputArgument::IS_ARRAY | InputArgument::OPTIONAL, + 'The package or packages that is desired to update. By default all available updates will be applied.' + ) + ->setDescription("Detects and performs an update of plugins and themes when available") + ->setHelp('The update command updates plugins and themes when a new version is available'); + } + + /** + * @return int|null|void + */ + protected function serve() + { + $this->upgrader = new Upgrader($this->input->getOption('force')); + $local = $this->upgrader->getLocalVersion(); + $remote = $this->upgrader->getRemoteVersion(); + if ($local !== $remote) { + $this->output->writeln("WARNING: A new version of Grav is available. You should update Grav before updating plugins and themes. If you continue without updating Grav, some plugins or themes may stop working."); + $this->output->writeln(""); + $questionHelper = $this->getHelper('question'); + $question = new ConfirmationQuestion("Continue with the update process? [Y|n] ", true); + $answer = $questionHelper->ask($this->input, $this->output, $question); + + if (!$answer) { + $this->output->writeln("Update aborted. Exiting..."); + exit; + } + } + + $this->gpm = new GPM($this->input->getOption('force')); + + $this->all_yes = $this->input->getOption('all-yes'); + $this->overwrite = $this->input->getOption('overwrite'); + + $this->displayGPMRelease(); + + $this->destination = realpath($this->input->getOption('destination')); + + if (!Installer::isGravInstance($this->destination)) { + $this->output->writeln("ERROR: " . Installer::lastErrorMsg()); + exit; + } + if ($this->input->getOption('plugins') === false && $this->input->getOption('themes') === false) { + $list_type = ['plugins' => true, 'themes' => true]; + } else { + $list_type['plugins'] = $this->input->getOption('plugins'); + $list_type['themes'] = $this->input->getOption('themes'); + } + + if ($this->overwrite) { + $this->data = $this->gpm->getInstallable($list_type); + $description = " can be overwritten"; + } else { + $this->data = $this->gpm->getUpdatable($list_type); + $description = " need updating"; + } + + $only_packages = array_map('strtolower', $this->input->getArgument('package')); + + if (!$this->overwrite && !$this->data['total']) { + $this->output->writeln("Nothing to update."); + exit; + } + + $this->output->write("Found " . $this->gpm->countInstalled() . " packages installed of which " . $this->data['total'] . "" . $description); + + $limit_to = $this->userInputPackages($only_packages); + + $this->output->writeln(''); + + unset($this->data['total']); + unset($limit_to['total']); + + + // updates review + $slugs = []; + + $index = 0; + foreach ($this->data as $packages) { + foreach ($packages as $slug => $package) { + if (count($only_packages) && !array_key_exists($slug, $limit_to)) { + continue; + } + + if (!$package->available) { + $package->available = $package->version; + } + + $this->output->writeln( + // index + str_pad($index++ + 1, 2, '0', STR_PAD_LEFT) . ". " . + // name + "" . str_pad($package->name, 15) . " " . + // version + "[v" . $package->version . " -> v" . $package->available . "]" + ); + $slugs[] = $slug; + } + } + + if (!$this->all_yes) { + // prompt to continue + $this->output->writeln(""); + $questionHelper = $this->getHelper('question'); + $question = new ConfirmationQuestion("Continue with the update process? [Y|n] ", true); + $answer = $questionHelper->ask($this->input, $this->output, $question); + + if (!$answer) { + $this->output->writeln("Update aborted. Exiting..."); + exit; + } + } + + // finally update + $install_command = $this->getApplication()->find('install'); + + $args = new ArrayInput([ + 'command' => 'install', + 'package' => $slugs, + '-f' => $this->input->getOption('force'), + '-d' => $this->destination, + '-y' => true + ]); + $command_exec = $install_command->run($args, $this->output); + + if ($command_exec != 0) { + $this->output->writeln("Error: An error occurred while trying to install the packages"); + exit; + } + } + + /** + * @param $only_packages + * + * @return array + */ + private function userInputPackages($only_packages) + { + $found = ['total' => 0]; + $ignore = []; + + if (!count($only_packages)) { + $this->output->writeln(''); + } else { + foreach ($only_packages as $only_package) { + $find = $this->gpm->findPackage($only_package); + + if (!$find || (!$this->overwrite && !$this->gpm->isUpdatable($find->slug))) { + $name = isset($find->slug) ? $find->slug : $only_package; + $ignore[$name] = $name; + } else { + $found[$find->slug] = $find; + $found['total']++; + } + } + + if ($found['total']) { + $list = $found; + unset($list['total']); + $list = array_keys($list); + + if ($found['total'] !== $this->data['total']) { + $this->output->write(", only " . $found['total'] . " will be updated"); + } + + $this->output->writeln(''); + $this->output->writeln("Limiting updates for only " . implode(', ', + $list) . ""); + } + + if (count($ignore)) { + $this->output->writeln(''); + $this->output->writeln("Packages not found or not requiring updates: " . implode(', ', + $ignore) . ""); + + } + } + + return $found; + } +} diff --git a/system/src/Grav/Console/Gpm/VersionCommand.php b/system/src/Grav/Console/Gpm/VersionCommand.php new file mode 100644 index 0000000..c828106 --- /dev/null +++ b/system/src/Grav/Console/Gpm/VersionCommand.php @@ -0,0 +1,113 @@ +setName("version") + ->addOption( + 'force', + 'f', + InputOption::VALUE_NONE, + 'Force re-fetching the data from remote' + ) + ->addArgument( + 'package', + InputArgument::IS_ARRAY | InputArgument::OPTIONAL, + 'The package or packages that is desired to know the version of. By default and if not specified this would be grav' + ) + ->setDescription("Shows the version of an installed package. If available also shows pending updates.") + ->setHelp('The version command displays the current version of a package installed and, if available, the available version of pending updates'); + } + + /** + * @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' . $upgrader->getRemoteVersion() . ']'; + } + + } 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' . $installed->available . ']'; + } + } + } + + $updatable = $updatable ?: ''; + + if ($installed || $package == 'grav') { + $this->output->writeln('You are running ' . $name . ' v' . $version . '' . $updatable); + } else { + $this->output->writeln('Package ' . $package . ' not found'); + } + } + } +} diff --git a/system/src/Grav/Console/TerminalObjects/Table.php b/system/src/Grav/Console/TerminalObjects/Table.php new file mode 100644 index 0000000..c3078a9 --- /dev/null +++ b/system/src/Grav/Console/TerminalObjects/Table.php @@ -0,0 +1,29 @@ +column_widths = $this->getColumnWidths(); + $this->table_width = $this->getWidth(); + $this->border = $this->getBorder(); + + $this->buildHeaderRow(); + + foreach ($this->data as $key => $columns) { + $this->rows[] = $this->buildRow($columns); + } + + $this->rows[] = $this->border; + + return $this->rows; + } +} diff --git a/system/src/Grav/Framework/Cache/AbstractCache.php b/system/src/Grav/Framework/Cache/AbstractCache.php new file mode 100644 index 0000000..de749a1 --- /dev/null +++ b/system/src/Grav/Framework/Cache/AbstractCache.php @@ -0,0 +1,30 @@ +init($namespace, $defaultLifetime); + } +} diff --git a/system/src/Grav/Framework/Cache/Adapter/ChainCache.php b/system/src/Grav/Framework/Cache/Adapter/ChainCache.php new file mode 100644 index 0000000..041b676 --- /dev/null +++ b/system/src/Grav/Framework/Cache/Adapter/ChainCache.php @@ -0,0 +1,197 @@ +caches = array_values($caches); + $this->count = count($caches); + } + + /** + * @inheritdoc + */ + public function doGet($key, $miss) + { + foreach ($this->caches as $i => $cache) { + $value = $cache->doGet($key, $miss); + if ($value !== $miss) { + while (--$i >= 0) { + // Update all the previous caches with missing value. + $this->caches[$i]->doSet($key, $value, $this->getDefaultLifetime()); + } + + return $value; + } + } + + return $miss; + } + + /** + * @inheritdoc + */ + public function doSet($key, $value, $ttl) + { + $success = true; + $i = $this->count; + + while ($i--) { + $success = $this->caches[$i]->doSet($key, $value, $ttl) && $success; + } + + return $success; + } + + /** + * @inheritdoc + */ + public function doDelete($key) + { + $success = true; + $i = $this->count; + + while ($i--) { + $success = $this->caches[$i]->doDelete($key) && $success; + } + + return $success; + } + + /** + * @inheritdoc + */ + public function doClear() + { + $success = true; + $i = $this->count; + + while ($i--) { + $success = $this->caches[$i]->doClear() && $success; + } + return $success; + } + + /** + * @inheritdoc + */ + public function doGetMultiple($keys, $miss) + { + $list = []; + foreach ($this->caches as $i => $cache) { + $list[$i] = $cache->doGetMultiple($keys, $miss); + + $keys = array_diff_key($keys, $list[$i]); + + if (!$keys) { + break; + } + } + + $values = []; + // Update all the previous caches with missing values. + foreach (array_reverse($list) as $i => $items) { + $values += $items; + if ($i && $values) { + $this->caches[$i-1]->doSetMultiple($values, $this->getDefaultLifetime()); + } + } + + return $values; + } + + /** + * @inheritdoc + */ + public function doSetMultiple($values, $ttl) + { + $success = true; + $i = $this->count; + + while ($i--) { + $success = $this->caches[$i]->doSetMultiple($values, $ttl) && $success; + } + + return $success; + } + + /** + * @inheritdoc + */ + public function doDeleteMultiple($keys) + { + $success = true; + $i = $this->count; + + while ($i--) { + $success = $this->caches[$i]->doDeleteMultiple($keys) && $success; + } + + return $success; + } + + /** + * @inheritdoc + */ + public function doHas($key) + { + foreach ($this->caches as $cache) { + if ($cache->doHas($key)) { + return true; + } + } + + return false; + } +} diff --git a/system/src/Grav/Framework/Cache/Adapter/DoctrineCache.php b/system/src/Grav/Framework/Cache/Adapter/DoctrineCache.php new file mode 100644 index 0000000..3a69c1f --- /dev/null +++ b/system/src/Grav/Framework/Cache/Adapter/DoctrineCache.php @@ -0,0 +1,123 @@ +getNamespace(); + $namespace && $doctrineCache->setNamespace($namespace); + + $this->driver = $doctrineCache; + } + + /** + * @inheritdoc + */ + public function doGet($key, $miss) + { + $value = $this->driver->fetch($key); + + // Doctrine cache does not differentiate between no result and cached 'false'. Make sure that we do. + return $value !== false || $this->driver->contains($key) ? $value : $miss; + } + + /** + * @inheritdoc + */ + public function doSet($key, $value, $ttl) + { + return $this->driver->save($key, $value, (int) $ttl); + } + + /** + * @inheritdoc + */ + public function doDelete($key) + { + return $this->driver->delete($key); + } + + /** + * @inheritdoc + */ + public function doClear() + { + return $this->driver->deleteAll(); + } + + /** + * @inheritdoc + */ + public function doGetMultiple($keys, $miss) + { + return $this->driver->fetchMultiple($keys); + } + + /** + * @inheritdoc + */ + public function doSetMultiple($values, $ttl) + { + return $this->driver->saveMultiple($values, (int) $ttl); + } + + /** + * @inheritdoc + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function doDeleteMultiple($keys) + { + // TODO: Remove when Doctrine Cache has been updated to support the feature. + if (!method_exists($this->driver, 'deleteMultiple')) { + $success = true; + foreach ($keys as $key) { + $success = $this->delete($key) && $success; + } + + return $success; + } + + return $this->driver->deleteMultiple($keys); + } + + /** + * @inheritdoc + */ + public function doHas($key) + { + return $this->driver->contains($key); + } +} diff --git a/system/src/Grav/Framework/Cache/Adapter/FileCache.php b/system/src/Grav/Framework/Cache/Adapter/FileCache.php new file mode 100644 index 0000000..389b626 --- /dev/null +++ b/system/src/Grav/Framework/Cache/Adapter/FileCache.php @@ -0,0 +1,210 @@ +getFile($key); + + if (!file_exists($file) || !$h = @fopen($file, 'rb')) { + return $miss; + } + + if ($now >= (int) $expiresAt = fgets($h)) { + fclose($h); + @unlink($file); + } else { + $i = rawurldecode(rtrim(fgets($h))); + $value = stream_get_contents($h); + fclose($h); + + if ($i === $key) { + return unserialize($value); + } + } + + return $miss; + } + + /** + * @inheritdoc + * @throws \Psr\SimpleCache\CacheException + */ + public function doSet($key, $value, $ttl) + { + $expiresAt = time() + (int)$ttl; + + $result = $this->write( + $this->getFile($key, true), + $expiresAt . "\n" . rawurlencode($key) . "\n" . serialize($value), + $expiresAt + ); + + if (!$result && !is_writable($this->directory)) { + throw new CacheException(sprintf('Cache directory is not writable (%s)', $this->directory)); + } + + return $result; + } + + /** + * @inheritdoc + */ + public function doDelete($key) + { + $file = $this->getFile($key); + + return (!file_exists($file) || @unlink($file) || !file_exists($file)); + } + + /** + * @inheritdoc + */ + public function doClear() + { + $result = true; + $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS)); + + foreach ($iterator as $file) { + $result = ($file->isDir() || @unlink($file) || !file_exists($file)) && $result; + } + + return $result; + } + + /** + * @inheritdoc + */ + public function doHas($key) + { + $file = $this->getFile($key); + + return file_exists($file) && (@filemtime($file) > time() || $this->doGet($key, null)); + } + + /** + * @param string $key + * @param bool $mkdir + * @return string + */ + protected function getFile($key, $mkdir = false) + { + $hash = str_replace('/', '-', base64_encode(hash('sha256', static::class . $key, true))); + $dir = $this->directory . $hash[0] . DIRECTORY_SEPARATOR . $hash[1] . DIRECTORY_SEPARATOR; + + if ($mkdir && !file_exists($dir)) { + @mkdir($dir, 0777, true); + } + + return $dir . substr($hash, 2, 20); + } + + /** + * @param string $namespace + * @param string $directory + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + private function init($namespace, $directory) + { + if (!isset($directory[0])) { + $directory = sys_get_temp_dir() . '/grav-cache'; + } else { + $directory = realpath($directory) ?: $directory; + } + + if (isset($namespace[0])) { + if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) { + throw new InvalidArgumentException(sprintf('Namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0])); + } + $directory .= DIRECTORY_SEPARATOR . $namespace; + } + + if (!file_exists($directory)) { + @mkdir($directory, 0777, true); + } + + $directory .= DIRECTORY_SEPARATOR; + // On Windows the whole path is limited to 258 chars + if ('\\' === DIRECTORY_SEPARATOR && strlen($directory) > 234) { + throw new InvalidArgumentException(sprintf('Cache folder is too long (%s)', $directory)); + } + $this->directory = $directory; + } + + /** + * @param string $file + * @param string $data + * @param int|null $expiresAt + * @return bool + */ + private function write($file, $data, $expiresAt = null) + { + set_error_handler(__CLASS__.'::throwError'); + + try { + if ($this->tmp === null) { + $this->tmp = $this->directory . uniqid('', true); + } + + file_put_contents($this->tmp, $data); + + if ($expiresAt !== null) { + touch($this->tmp, $expiresAt); + } + + return rename($this->tmp, $file); + } finally { + restore_error_handler(); + } + } + + /** + * @internal + * @throws \ErrorException + */ + public static function throwError($type, $message, $file, $line) + { + throw new \ErrorException($message, 0, $type, $file, $line); + } + + public function __destruct() + { + if ($this->tmp !== null && file_exists($this->tmp)) { + unlink($this->tmp); + } + } +} diff --git a/system/src/Grav/Framework/Cache/Adapter/MemoryCache.php b/system/src/Grav/Framework/Cache/Adapter/MemoryCache.php new file mode 100644 index 0000000..84911fb --- /dev/null +++ b/system/src/Grav/Framework/Cache/Adapter/MemoryCache.php @@ -0,0 +1,61 @@ +cache)) { + return $miss; + } + + return $this->cache[$key]; + } + + public function doSet($key, $value, $ttl) + { + $this->cache[$key] = $value; + + return true; + } + + public function doDelete($key) + { + unset($this->cache[$key]); + + return true; + } + + public function doClear() + { + $this->cache = []; + + return true; + } + + public function doHas($key) + { + return array_key_exists($key, $this->cache); + } +} diff --git a/system/src/Grav/Framework/Cache/Adapter/SessionCache.php b/system/src/Grav/Framework/Cache/Adapter/SessionCache.php new file mode 100644 index 0000000..b1e9e9e --- /dev/null +++ b/system/src/Grav/Framework/Cache/Adapter/SessionCache.php @@ -0,0 +1,78 @@ +doGetStored($key); + + return $stored ? $stored[self::VALUE] : $miss; + } + + public function doSet($key, $value, $ttl) + { + $stored = [self::VALUE => $value]; + if (null !== $ttl) { + $stored[self::LIFETIME] = time() + $ttl; + + } + + $_SESSION[$this->getNamespace()][$key] = $stored; + + return true; + } + + public function doDelete($key) + { + unset($_SESSION[$this->getNamespace()][$key]); + + return true; + } + + public function doClear() + { + unset($_SESSION[$this->getNamespace()]); + + return true; + } + + public function doHas($key) + { + return $this->doGetStored($key) !== null; + } + + public function getNamespace() + { + return 'cache-' . parent::getNamespace(); + } + + protected function doGetStored($key) + { + $stored = isset($_SESSION[$this->getNamespace()][$key]) ? $_SESSION[$this->getNamespace()][$key] : null; + + if (isset($stored[self::LIFETIME]) && $stored[self::LIFETIME] < time()) { + unset($_SESSION[$this->getNamespace()][$key]); + $stored = null; + } + + return $stored ?: null; + } +} diff --git a/system/src/Grav/Framework/Cache/CacheInterface.php b/system/src/Grav/Framework/Cache/CacheInterface.php new file mode 100644 index 0000000..54af40c --- /dev/null +++ b/system/src/Grav/Framework/Cache/CacheInterface.php @@ -0,0 +1,27 @@ +namespace = (string) $namespace; + $this->defaultLifetime = $this->convertTtl($defaultLifetime); + $this->miss = new \stdClass; + } + + /** + * @return string + */ + protected function getNamespace() + { + return $this->namespace; + } + + /** + * @return int|null + */ + protected function getDefaultLifetime() + { + return $this->defaultLifetime; + } + + /** + * @inheritdoc + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function get($key, $default = null) + { + $this->validateKey($key); + + $value = $this->doGet($key, $this->miss); + + return $value !== $this->miss ? $value : $default; + } + + /** + * @inheritdoc + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function set($key, $value, $ttl = null) + { + $this->validateKey($key); + + $ttl = $this->convertTtl($ttl); + + // If a negative or zero TTL is provided, the item MUST be deleted from the cache. + return null !== $ttl && $ttl <= 0 ? $this->doDelete($key) : $this->doSet($key, $value, $ttl); + } + + /** + * @inheritdoc + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function delete($key) + { + $this->validateKey($key); + + return $this->doDelete($key); + } + + /** + * @inheritdoc + */ + public function clear() + { + return $this->doClear(); + } + + /** + * @inheritdoc + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function getMultiple($keys, $default = null) + { + if ($keys instanceof \Traversable) { + $keys = iterator_to_array($keys, false); + } elseif (!is_array($keys)) { + throw new InvalidArgumentException( + sprintf( + 'Cache keys must be array or Traversable, "%s" given', + is_object($keys) ? get_class($keys) : gettype($keys) + ) + ); + } + + if (empty($keys)) { + return []; + } + + $this->validateKeys($keys); + $keys = array_unique($keys); + $keys = array_combine($keys, $keys); + + $list = $this->doGetMultiple($keys, $this->miss); + + // Make sure that values are returned in the same order as the keys were given. + $values = []; + foreach ($keys as $key) { + if (!array_key_exists($key, $list) || $list[$key] === $this->miss) { + $values[$key] = $default; + } else { + $values[$key] = $list[$key]; + } + } + + return $values; + } + + /** + * @inheritdoc + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function setMultiple($values, $ttl = null) + { + if ($values instanceof \Traversable) { + $values = iterator_to_array($values, true); + } elseif (!is_array($values)) { + throw new InvalidArgumentException( + sprintf( + 'Cache values must be array or Traversable, "%s" given', + is_object($values) ? get_class($values) : gettype($values) + ) + ); + } + + $keys = array_keys($values); + + if (empty($keys)) { + return true; + } + + $this->validateKeys($keys); + + $ttl = $this->convertTtl($ttl); + + // If a negative or zero TTL is provided, the item MUST be deleted from the cache. + return null !== $ttl && $ttl <= 0 ? $this->doDeleteMultiple($keys) : $this->doSetMultiple($values, $ttl); + } + + /** + * @inheritdoc + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function deleteMultiple($keys) + { + if ($keys instanceof \Traversable) { + $keys = iterator_to_array($keys, false); + } elseif (!is_array($keys)) { + throw new InvalidArgumentException( + sprintf( + 'Cache keys must be array or Traversable, "%s" given', + is_object($keys) ? get_class($keys) : gettype($keys) + ) + ); + } + + if (empty($keys)) { + return true; + } + + $this->validateKeys($keys); + + return $this->doDeleteMultiple($keys); + } + + /** + * @inheritdoc + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function has($key) + { + $this->validateKey($key); + + return $this->doHas($key); + } + + abstract public function doGet($key, $miss); + abstract public function doSet($key, $value, $ttl); + abstract public function doDelete($key); + abstract public function doClear(); + + /** + * @param array $keys + * @param mixed $miss + * @return array + */ + public function doGetMultiple($keys, $miss) + { + $results = []; + + foreach ($keys as $key) { + $value = $this->doGet($key, $miss); + if ($value !== $miss) { + $results[$key] = $value; + } + } + + return $results; + } + + /** + * @param array $values + * @param int $ttl + * @return bool + */ + public function doSetMultiple($values, $ttl) + { + $success = true; + + foreach ($values as $key => $value) { + $success = $this->doSet($key, $value, $ttl) && $success; + } + + return $success; + } + + /** + * @param array $keys + * @return bool + */ + public function doDeleteMultiple($keys) + { + $success = true; + + foreach ($keys as $key) { + $success = $this->doDelete($key) && $success; + } + + return $success; + } + + abstract public function doHas($key); + + /** + * @param string $key + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + protected function validateKey($key) + { + if (!is_string($key)) { + throw new InvalidArgumentException( + sprintf( + 'Cache key must be string, "%s" given', + is_object($key) ? get_class($key) : gettype($key) + ) + ); + } + if (!isset($key[0])) { + throw new InvalidArgumentException('Cache key length must be greater than zero'); + } + if (strlen($key) > 64) { + throw new InvalidArgumentException( + sprintf('Cache key length must be less than 65 characters, key had %s characters', strlen($key)) + ); + } + if (strpbrk($key, '{}()/\@:') !== false) { + throw new InvalidArgumentException( + sprintf('Cache key "%s" contains reserved characters {}()/\@:', $key) + ); + } + } + + /** + * @param array $keys + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + protected function validateKeys($keys) + { + foreach ($keys as $key) { + $this->validateKey($key); + } + } + + /** + * @param null|int|\DateInterval $ttl + * @return int|null + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + protected function convertTtl($ttl) + { + if ($ttl === null) { + return $this->getDefaultLifetime(); + } + + if (is_int($ttl)) { + return $ttl; + } + + if ($ttl instanceof \DateInterval) { + $ttl = (int) \DateTime::createFromFormat('U', 0)->add($ttl)->format('U'); + } + + throw new InvalidArgumentException( + sprintf( + 'Expiration date must be an integer, a DateInterval or null, "%s" given', + is_object($ttl) ? get_class($ttl) : gettype($ttl) + ) + ); + } +} diff --git a/system/src/Grav/Framework/Cache/Exception/CacheException.php b/system/src/Grav/Framework/Cache/Exception/CacheException.php new file mode 100644 index 0000000..71caff7 --- /dev/null +++ b/system/src/Grav/Framework/Cache/Exception/CacheException.php @@ -0,0 +1,19 @@ +path = $path; + $this->flags = self::INCLUDE_FILES | self::INCLUDE_FOLDERS; + $this->nestingLimit = 0; + $this->createObjectFunction = [$this, 'createObject']; + + $this->setIterator(); + } + + /** + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * @param Criteria $criteria + * @return ArrayCollection + * @todo Implement lazy matching + */ + public function matching(Criteria $criteria) + { + $expr = $criteria->getWhereExpression(); + + $oldFilter = $this->filterFunction; + if ($expr) { + $visitor = new ClosureExpressionVisitor(); + $filter = $visitor->dispatch($expr); + $this->addFilter($filter); + } + + $filtered = $this->doInitializeByIterator($this->iterator, $this->nestingLimit); + $this->filterFunction = $oldFilter; + + if ($orderings = $criteria->getOrderings()) { + $next = null; + foreach (array_reverse($orderings) as $field => $ordering) { + $next = ClosureExpressionVisitor::sortByField($field, $ordering == Criteria::DESC ? -1 : 1, $next); + } + + uasort($filtered, $next); + } else { + ksort($filtered); + } + + $offset = $criteria->getFirstResult(); + $length = $criteria->getMaxResults(); + + if ($offset || $length) { + $filtered = array_slice($filtered, (int)$offset, $length); + } + + return new ArrayCollection($filtered); + } + + protected function setIterator() + { + $iteratorFlags = \RecursiveDirectoryIterator::SKIP_DOTS + \FilesystemIterator::UNIX_PATHS + + \FilesystemIterator::CURRENT_AS_SELF + \FilesystemIterator::FOLLOW_SYMLINKS; + + if (strpos($this->path, '://')) { + /** @var UniformResourceLocator $locator */ + $locator = Grav::instance()['locator']; + $this->iterator = $locator->getRecursiveIterator($this->path, $iteratorFlags); + } else { + $this->iterator = new \RecursiveDirectoryIterator($this->path, $iteratorFlags); + } + } + + /** + * @param callable $filterFunction + * @return $this + */ + protected function addFilter(callable $filterFunction) + { + if ($this->filterFunction) { + $oldFilterFunction = $this->filterFunction; + $this->filterFunction = function ($expr) use ($oldFilterFunction, $filterFunction) { + return $oldFilterFunction($expr) && $filterFunction($expr); + }; + } else { + $this->filterFunction = $filterFunction; + } + + return $this; + } + + /** + * {@inheritDoc} + */ + protected function doInitialize() + { + $filtered = $this->doInitializeByIterator($this->iterator, $this->nestingLimit); + ksort($filtered); + + $this->collection = new ArrayCollection($filtered); + } + + protected function doInitializeByIterator(\SeekableIterator $iterator, $nestingLimit) + { + $children = []; + $objects = []; + $filter = $this->filterFunction; + $objectFunction = $this->createObjectFunction; + + /** @var \RecursiveDirectoryIterator $file */ + foreach ($iterator as $file) { + // Skip files if they shouldn't be included. + if (!($this->flags & static::INCLUDE_FILES) && $file->isFile()) { + continue; + } + + // Apply main filter. + if ($filter && !$filter($file)) { + continue; + } + + // Include children if the recursive flag is set. + if (($this->flags & static::RECURSIVE) && $nestingLimit > 0 && $file->hasChildren()) { + $children[] = $file->getChildren(); + } + + // Skip folders if they shouldn't be included. + if (!($this->flags & static::INCLUDE_FOLDERS) && $file->isDir()) { + continue; + } + + $object = $objectFunction($file); + $objects[$object->key] = $object; + } + + if ($children) { + $objects += $this->doInitializeChildren($children, $nestingLimit - 1); + } + + return $objects; + } + + /** + * @param \RecursiveDirectoryIterator[] $children + * @return array + */ + protected function doInitializeChildren(array $children, $nestingLimit) + { + $objects = []; + + foreach ($children as $iterator) { + $objects += $this->doInitializeByIterator($iterator, $nestingLimit); + } + + return $objects; + } + + /** + * @param \RecursiveDirectoryIterator $file + * @return object + */ + protected function createObject($file) + { + return (object) [ + 'key' => $file->getSubPathname(), + 'type' => $file->isDir() ? 'folder' : 'file:' . $file->getExtension(), + 'url' => method_exists($file, 'getUrl') ? $file->getUrl() : null, + 'pathname' => $file->getPathname(), + 'mtime' => $file->getMTime() + ]; + } +} diff --git a/system/src/Grav/Framework/Collection/AbstractLazyCollection.php b/system/src/Grav/Framework/Collection/AbstractLazyCollection.php new file mode 100644 index 0000000..af2f696 --- /dev/null +++ b/system/src/Grav/Framework/Collection/AbstractLazyCollection.php @@ -0,0 +1,62 @@ +initialize(); + return $this->collection->reverse(); + } + + /** + * {@inheritDoc} + */ + public function shuffle() + { + $this->initialize(); + return $this->collection->shuffle(); + } + + /** + * {@inheritDoc} + */ + public function chunk($size) + { + $this->initialize(); + return $this->collection->chunk($size); + } + + /** + * {@inheritDoc} + */ + public function jsonSerialize() + { + $this->initialize(); + return $this->collection->jsonSerialize(); + } +} diff --git a/system/src/Grav/Framework/Collection/ArrayCollection.php b/system/src/Grav/Framework/Collection/ArrayCollection.php new file mode 100644 index 0000000..bf6dda0 --- /dev/null +++ b/system/src/Grav/Framework/Collection/ArrayCollection.php @@ -0,0 +1,73 @@ +toArray())); + } + + return $this->createFrom(array_reverse($this->toArray())); + } + + /** + * Shuffle items. + * + * @return static + */ + public function shuffle() + { + $keys = $this->getKeys(); + shuffle($keys); + + // TODO: remove when PHP 5.6 is minimum (with doctrine/collections v1.4). + if (!method_exists($this, 'createFrom')) { + return new static(array_replace(array_flip($keys), $this->toArray())); + } + + return $this->createFrom(array_replace(array_flip($keys), $this->toArray())); + } + + /** + * Split collection into chunks. + * + * @param int $size Size of each chunk. + * @return array + */ + public function chunk($size) + { + return array_chunk($this->toArray(), $size, true); + } + + /** + * Implementes JsonSerializable interface. + * + * @return array + */ + public function jsonSerialize() + { + return $this->toArray(); + } +} diff --git a/system/src/Grav/Framework/Collection/CollectionInterface.php b/system/src/Grav/Framework/Collection/CollectionInterface.php new file mode 100644 index 0000000..5f5e1fc --- /dev/null +++ b/system/src/Grav/Framework/Collection/CollectionInterface.php @@ -0,0 +1,41 @@ +flags = (int)($flags ?: self::INCLUDE_FILES | self::INCLUDE_FOLDERS | self::RECURSIVE); + + $this->setIterator(); + $this->setFilter(); + $this->setObjectBuilder(); + $this->setNestingLimit(); + } + + /** + * @return int + */ + public function getFlags() + { + return $this->flags; + } + + /** + * @return int + */ + public function getNestingLimit() + { + return $this->nestingLimit; + } + + /** + * @param int $limit + * @return $this + */ + public function setNestingLimit($limit = 99) + { + $this->nestingLimit = (int) $limit; + + return $this; + } + + /** + * @param callable|null $filterFunction + * @return $this + */ + public function setFilter(callable $filterFunction = null) + { + $this->filterFunction = $filterFunction; + + return $this; + } + + /** + * @param callable $filterFunction + * @return $this + */ + public function addFilter(callable $filterFunction) + { + parent::addFilter($filterFunction); + + return $this; + } + + /** + * @param callable|null $objectFunction + * @return $this + */ + public function setObjectBuilder(callable $objectFunction = null) + { + $this->createObjectFunction = $objectFunction ?: [$this, 'createObject']; + + return $this; + } +} diff --git a/system/src/Grav/Framework/Collection/FileCollectionInterface.php b/system/src/Grav/Framework/Collection/FileCollectionInterface.php new file mode 100644 index 0000000..37f63d2 --- /dev/null +++ b/system/src/Grav/Framework/Collection/FileCollectionInterface.php @@ -0,0 +1,28 @@ +setContent('my inner content'); + * $outerBlock = ContentBlock::create(); + * $outerBlock->setContent(sprintf('Inside my outer block I have %s.', $innerBlock->getToken())); + * $outerBlock->addBlock($innerBlock); + * echo $outerBlock; + * + * @package Grav\Framework\ContentBlock + */ +class ContentBlock implements ContentBlockInterface +{ + protected $version = 1; + protected $id; + protected $tokenTemplate = '@@BLOCK-%s@@'; + protected $content = ''; + protected $blocks = []; + + /** + * @param string $id + * @return static + */ + public static function create($id = null) + { + return new static($id); + } + + /** + * @param array $serialized + * @return ContentBlockInterface + */ + public static function fromArray(array $serialized) + { + try { + $type = isset($serialized['_type']) ? $serialized['_type'] : null; + $id = isset($serialized['id']) ? $serialized['id'] : null; + + if (!$type || !$id || !is_a($type, 'Grav\Framework\ContentBlock\ContentBlockInterface', true)) { + throw new \RuntimeException('Bad data'); + } + + /** @var ContentBlockInterface $instance */ + $instance = new $type($id); + $instance->build($serialized); + } catch (\Exception $e) { + throw new \RuntimeException(sprintf('Cannot unserialize Block: %s', $e->getMessage()), $e->getCode(), $e); + } + + return $instance; + } + + /** + * Block constructor. + * + * @param string $id + */ + public function __construct($id = null) + { + $this->id = $id ? (string) $id : $this->generateId(); + } + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @return string + */ + public function getToken() + { + return sprintf($this->tokenTemplate, $this->getId()); + } + + /** + * @return array + */ + public function toArray() + { + $blocks = []; + /** + * @var string $id + * @var ContentBlockInterface $block + */ + foreach ($this->blocks as $block) { + $blocks[$block->getId()] = $block->toArray(); + } + + $array = [ + '_type' => get_class($this), + '_version' => $this->version, + 'id' => $this->id, + ]; + + if ($this->content) { + $array['content'] = $this->content; + } + + if ($blocks) { + $array['blocks'] = $blocks; + } + + return $array; + } + + /** + * @return string + */ + public function toString() + { + if (!$this->blocks) { + return (string) $this->content; + } + + $tokens = []; + $replacements = []; + foreach ($this->blocks as $block) { + $tokens[] = $block->getToken(); + $replacements[] = $block->toString(); + } + + return str_replace($tokens, $replacements, (string) $this->content); + } + + /** + * @return string + */ + public function __toString() + { + try { + return $this->toString(); + } catch (\Exception $e) { + return sprintf('Error while rendering block: %s', $e->getMessage()); + } + } + + /** + * @param array $serialized + * @throws \RuntimeException + */ + public function build(array $serialized) + { + $this->checkVersion($serialized); + + $this->id = isset($serialized['id']) ? $serialized['id'] : $this->generateId(); + + if (isset($serialized['content'])) { + $this->setContent($serialized['content']); + } + + $blocks = isset($serialized['blocks']) ? (array) $serialized['blocks'] : []; + foreach ($blocks as $block) { + $this->addBlock(self::fromArray($block)); + } + } + + /** + * @param string $content + * @return $this + */ + public function setContent($content) + { + $this->content = $content; + + return $this; + } + + /** + * @param ContentBlockInterface $block + * @return $this + */ + public function addBlock(ContentBlockInterface $block) + { + $this->blocks[$block->getId()] = $block; + + return $this; + } + + /** + * @return string + */ + public function serialize() + { + return serialize($this->toArray()); + } + + /** + * @param string $serialized + */ + public function unserialize($serialized) + { + $array = unserialize($serialized); + $this->build($array); + } + + /** + * @return string + */ + protected function generateId() + { + return uniqid('', true); + } + + /** + * @param array $serialized + * @throws \RuntimeException + */ + protected function checkVersion(array $serialized) + { + $version = isset($serialized['_version']) ? (string) $serialized['_version'] : '1'; + if ($version !== $this->version) { + throw new \RuntimeException(sprintf('Unsupported version %s', $version)); + } + } +} diff --git a/system/src/Grav/Framework/ContentBlock/ContentBlockInterface.php b/system/src/Grav/Framework/ContentBlock/ContentBlockInterface.php new file mode 100644 index 0000000..4f2434c --- /dev/null +++ b/system/src/Grav/Framework/ContentBlock/ContentBlockInterface.php @@ -0,0 +1,75 @@ +getAssetsFast(); + + $this->sortAssets($assets['styles']); + $this->sortAssets($assets['scripts']); + $this->sortAssets($assets['html']); + + return $assets; + } + + /** + * @return array + */ + public function getFrameworks() + { + $assets = $this->getAssetsFast(); + + return array_keys($assets['frameworks']); + } + + /** + * @param string $location + * @return array + */ + public function getStyles($location = 'head') + { + return $this->getAssetsInLocation('styles', $location); + } + + /** + * @param string $location + * @return array + */ + public function getScripts($location = 'head') + { + return $this->getAssetsInLocation('scripts', $location); + } + + /** + * @param string $location + * @return array + */ + public function getHtml($location = 'bottom') + { + return $this->getAssetsInLocation('html', $location); + } + + /** + * @return array[] + */ + public function toArray() + { + $array = parent::toArray(); + + if ($this->frameworks) { + $array['frameworks'] = $this->frameworks; + } + if ($this->styles) { + $array['styles'] = $this->styles; + } + if ($this->scripts) { + $array['scripts'] = $this->scripts; + } + if ($this->html) { + $array['html'] = $this->html; + } + + return $array; + } + + /** + * @param array $serialized + * @throws \RuntimeException + */ + public function build(array $serialized) + { + parent::build($serialized); + + $this->frameworks = isset($serialized['frameworks']) ? (array) $serialized['frameworks'] : []; + $this->styles = isset($serialized['styles']) ? (array) $serialized['styles'] : []; + $this->scripts = isset($serialized['scripts']) ? (array) $serialized['scripts'] : []; + $this->html = isset($serialized['html']) ? (array) $serialized['html'] : []; + } + + /** + * @param string $framework + * @return $this + */ + public function addFramework($framework) + { + $this->frameworks[$framework] = 1; + + return $this; + } + + /** + * @param string|array $element + * @param int $priority + * @param string $location + * @return bool + * + * @example $block->addStyle('assets/js/my.js'); + * @example $block->addStyle(['href' => 'assets/js/my.js', 'media' => 'screen']); + */ + public function addStyle($element, $priority = 0, $location = 'head') + { + if (!is_array($element)) { + $element = ['href' => (string) $element]; + } + if (empty($element['href'])) { + return false; + } + if (!isset($this->styles[$location])) { + $this->styles[$location] = []; + } + + $id = !empty($element['id']) ? ['id' => (string) $element['id']] : []; + $href = $element['href']; + $type = !empty($element['type']) ? (string) $element['type'] : 'text/css'; + $media = !empty($element['media']) ? (string) $element['media'] : null; + unset( + $element['tag'], + $element['id'], + $element['rel'], + $element['content'], + $element['href'], + $element['type'], + $element['media'] + ); + + $this->styles[$location][md5($href) . sha1($href)] = [ + ':type' => 'file', + ':priority' => (int) $priority, + 'href' => $href, + 'type' => $type, + 'media' => $media, + 'element' => $element + ] + $id; + + return true; + } + + /** + * @param string|array $element + * @param int $priority + * @param string $location + * @return bool + */ + public function addInlineStyle($element, $priority = 0, $location = 'head') + { + if (!is_array($element)) { + $element = ['content' => (string) $element]; + } + if (empty($element['content'])) { + return false; + } + if (!isset($this->styles[$location])) { + $this->styles[$location] = []; + } + + $content = (string) $element['content']; + $type = !empty($element['type']) ? (string) $element['type'] : 'text/css'; + + $this->styles[$location][md5($content) . sha1($content)] = [ + ':type' => 'inline', + ':priority' => (int) $priority, + 'content' => $content, + 'type' => $type + ]; + + return true; + } + + /** + * @param string|array $element + * @param int $priority + * @param string $location + * @return bool + */ + public function addScript($element, $priority = 0, $location = 'head') + { + if (!is_array($element)) { + $element = ['src' => (string) $element]; + } + if (empty($element['src'])) { + return false; + } + if (!isset($this->scripts[$location])) { + $this->scripts[$location] = []; + } + + $src = $element['src']; + $type = !empty($element['type']) ? (string) $element['type'] : 'text/javascript'; + $defer = isset($element['defer']) ? true : false; + $async = isset($element['async']) ? true : false; + $handle = !empty($element['handle']) ? (string) $element['handle'] : ''; + + $this->scripts[$location][md5($src) . sha1($src)] = [ + ':type' => 'file', + ':priority' => (int) $priority, + 'src' => $src, + 'type' => $type, + 'defer' => $defer, + 'async' => $async, + 'handle' => $handle + ]; + + return true; + } + + /** + * @param string|array $element + * @param int $priority + * @param string $location + * @return bool + */ + public function addInlineScript($element, $priority = 0, $location = 'head') + { + if (!is_array($element)) { + $element = ['content' => (string) $element]; + } + if (empty($element['content'])) { + return false; + } + if (!isset($this->scripts[$location])) { + $this->scripts[$location] = []; + } + + $content = (string) $element['content']; + $type = !empty($element['type']) ? (string) $element['type'] : 'text/javascript'; + + $this->scripts[$location][md5($content) . sha1($content)] = [ + ':type' => 'inline', + ':priority' => (int) $priority, + 'content' => $content, + 'type' => $type + ]; + + return true; + } + + /** + * @param string $html + * @param int $priority + * @param string $location + * @return bool + */ + public function addHtml($html, $priority = 0, $location = 'bottom') + { + if (empty($html) || !is_string($html)) { + return false; + } + if (!isset($this->html[$location])) { + $this->html[$location] = []; + } + + $this->html[$location][md5($html) . sha1($html)] = [ + ':priority' => (int) $priority, + 'html' => $html + ]; + + return true; + } + + /** + * @return array + */ + protected function getAssetsFast() + { + $assets = [ + 'frameworks' => $this->frameworks, + 'styles' => $this->styles, + 'scripts' => $this->scripts, + 'html' => $this->html + ]; + + foreach ($this->blocks as $block) { + if ($block instanceof HtmlBlock) { + $blockAssets = $block->getAssetsFast(); + $assets['frameworks'] += $blockAssets['frameworks']; + + foreach ($blockAssets['styles'] as $location => $styles) { + if (!isset($assets['styles'][$location])) { + $assets['styles'][$location] = $styles; + } elseif ($styles) { + $assets['styles'][$location] += $styles; + } + } + + foreach ($blockAssets['scripts'] as $location => $scripts) { + if (!isset($assets['scripts'][$location])) { + $assets['scripts'][$location] = $scripts; + } elseif ($scripts) { + $assets['scripts'][$location] += $scripts; + } + } + + foreach ($blockAssets['html'] as $location => $htmls) { + if (!isset($assets['html'][$location])) { + $assets['html'][$location] = $htmls; + } elseif ($htmls) { + $assets['html'][$location] += $htmls; + } + } + } + } + + return $assets; + } + + /** + * @param string $type + * @param string $location + * @return array + */ + protected function getAssetsInLocation($type, $location) + { + $assets = $this->getAssetsFast(); + + if (empty($assets[$type][$location])) { + return []; + } + + $styles = $assets[$type][$location]; + $this->sortAssetsInLocation($styles); + + return $styles; + } + + /** + * @param array $items + */ + protected function sortAssetsInLocation(array &$items) + { + $count = 0; + foreach ($items as &$item) { + $item[':order'] = ++$count; + } + unset($item); + + uasort( + $items, + function ($a, $b) { + return ($a[':priority'] === $b[':priority']) + ? $a[':order'] - $b[':order'] : $a[':priority'] - $b[':priority']; + } + ); + } + + /** + * @param array $array + */ + protected function sortAssets(array &$array) + { + foreach ($array as $location => &$items) { + $this->sortAssetsInLocation($items); + } + } +} diff --git a/system/src/Grav/Framework/ContentBlock/HtmlBlockInterface.php b/system/src/Grav/Framework/ContentBlock/HtmlBlockInterface.php new file mode 100644 index 0000000..204e199 --- /dev/null +++ b/system/src/Grav/Framework/ContentBlock/HtmlBlockInterface.php @@ -0,0 +1,94 @@ +addStyle('assets/js/my.js'); + * @example $block->addStyle(['href' => 'assets/js/my.js', 'media' => 'screen']); + */ + public function addStyle($element, $priority = 0, $location = 'head'); + + /** + * @param string|array $element + * @param int $priority + * @param string $location + * @return bool + */ + public function addInlineStyle($element, $priority = 0, $location = 'head'); + + /** + * @param string|array $element + * @param int $priority + * @param string $location + * @return bool + */ + public function addScript($element, $priority = 0, $location = 'head'); + + + /** + * @param string|array $element + * @param int $priority + * @param string $location + * @return bool + */ + public function addInlineScript($element, $priority = 0, $location = 'head'); + + /** + * @param string $html + * @param int $priority + * @param string $location + * @return bool + */ + public function addHtml($html, $priority = 0, $location = 'bottom'); +} diff --git a/system/src/Grav/Framework/Object/Access/ArrayAccessTrait.php b/system/src/Grav/Framework/Object/Access/ArrayAccessTrait.php new file mode 100644 index 0000000..37e7328 --- /dev/null +++ b/system/src/Grav/Framework/Object/Access/ArrayAccessTrait.php @@ -0,0 +1,64 @@ +hasProperty($offset); + } + + /** + * Returns the value at specified offset. + * + * @param mixed $offset The offset to retrieve. + * @return mixed Can return all value types. + */ + public function offsetGet($offset) + { + return $this->getProperty($offset); + } + + /** + * Assigns a value to the specified offset. + * + * @param mixed $offset The offset to assign the value to. + * @param mixed $value The value to set. + */ + public function offsetSet($offset, $value) + { + $this->setProperty($offset, $value); + } + + /** + * Unsets an offset. + * + * @param mixed $offset The offset to unset. + */ + public function offsetUnset($offset) + { + $this->unsetProperty($offset); + } + + abstract public function hasProperty($property); + abstract public function getProperty($property, $default = null); + abstract public function setProperty($property, $value); + abstract public function unsetProperty($property); +} diff --git a/system/src/Grav/Framework/Object/Access/NestedArrayAccessTrait.php b/system/src/Grav/Framework/Object/Access/NestedArrayAccessTrait.php new file mode 100644 index 0000000..256a1ce --- /dev/null +++ b/system/src/Grav/Framework/Object/Access/NestedArrayAccessTrait.php @@ -0,0 +1,64 @@ +hasNestedProperty($offset); + } + + /** + * Returns the value at specified offset. + * + * @param mixed $offset The offset to retrieve. + * @return mixed Can return all value types. + */ + public function offsetGet($offset) + { + return $this->getNestedProperty($offset); + } + + /** + * Assigns a value to the specified offset. + * + * @param mixed $offset The offset to assign the value to. + * @param mixed $value The value to set. + */ + public function offsetSet($offset, $value) + { + $this->setNestedProperty($offset, $value); + } + + /** + * Unsets an offset. + * + * @param mixed $offset The offset to unset. + */ + public function offsetUnset($offset) + { + $this->unsetNestedProperty($offset); + } + + abstract public function hasNestedProperty($property, $separator = null); + abstract public function getNestedProperty($property, $default = null, $separator = null); + abstract public function setNestedProperty($property, $value, $separator = null); + abstract public function unsetNestedProperty($property, $separator = null); +} diff --git a/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php b/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php new file mode 100644 index 0000000..65b155d --- /dev/null +++ b/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php @@ -0,0 +1,124 @@ +getIterator() as $id => $element) { + $list[$id] = $element->hasNestedProperty($property, $separator); + } + + return $list; + } + + /** + * @param string $property Object property to be fetched. + * @param mixed $default Default value if not set. + * @param string $separator Separator, defaults to '.' + * @return array Key/Value pairs of the properties. + */ + public function getNestedProperty($property, $default = null, $separator = null) + { + $list = []; + + /** @var NestedObjectInterface $element */ + foreach ($this->getIterator() as $id => $element) { + $list[$id] = $element->getNestedProperty($property, $default, $separator); + } + + return $list; + } + + /** + * @param string $property Object property to be updated. + * @param string $value New value. + * @param string $separator Separator, defaults to '.' + * @return $this + */ + public function setNestedProperty($property, $value, $separator = null) + { + /** @var NestedObjectInterface $element */ + foreach ($this->getIterator() as $element) { + $element->setNestedProperty($property, $value, $separator); + } + + return $this; + } + + /** + * @param string $property Object property to be updated. + * @param string $separator Separator, defaults to '.' + * @return $this + */ + public function unsetNestedProperty($property, $separator = null) + { + /** @var NestedObjectInterface $element */ + foreach ($this->getIterator() as $element) { + $element->unsetNestedProperty($property, $separator); + } + + return $this; + } + + /** + * @param string $property Object property to be updated. + * @param string $default Default value. + * @param string $separator Separator, defaults to '.' + * @return $this + */ + public function defNestedProperty($property, $default, $separator = null) + { + /** @var NestedObjectInterface $element */ + foreach ($this->getIterator() as $element) { + $element->defNestedProperty($property, $default, $separator); + } + + return $this; + } + + /** + * Group items in the collection by a field. + * + * @param string $property Object property to be used to make groups. + * @param string $separator Separator, defaults to '.' + * @return array + */ + public function group($property, $separator = null) + { + $list = []; + + /** @var NestedObjectInterface $element */ + foreach ($this->getIterator() as $element) { + $list[(string) $element->getNestedProperty($property, null, $separator)][] = $element; + } + + return $list; + } + + /** + * @return \Traversable + */ + abstract public function getIterator(); +} diff --git a/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php b/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php new file mode 100644 index 0000000..e01f425 --- /dev/null +++ b/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php @@ -0,0 +1,182 @@ +getNestedProperty($property, $test, $separator) !== $test; + } + + /** + * @param string $property Object property to be fetched. + * @param mixed $default Default value if property has not been set. + * @param string $separator Separator, defaults to '.' + * @return mixed Property value. + */ + public function getNestedProperty($property, $default = null, $separator = null) + { + $separator = $separator ?: '.'; + $path = explode($separator, $property); + $offset = array_shift($path); + + if (!$this->hasProperty($offset)) { + return $default; + } + + $current = $this->getProperty($offset); + + while ($path) { + // Get property of nested Object. + if ($current instanceof ObjectInterface) { + if (method_exists($current, 'getNestedProperty')) { + return $current->getNestedProperty(implode($separator, $path), $default, $separator); + } + return $current->getProperty(implode($separator, $path), $default); + } + + $offset = array_shift($path); + + if ((is_array($current) || is_a($current, 'ArrayAccess')) && isset($current[$offset])) { + $current = $current[$offset]; + } elseif (is_object($current) && isset($current->{$offset})) { + $current = $current->{$offset}; + } else { + return $default; + } + }; + + return $current; + } + + + /** + * @param string $property Object property to be updated. + * @param string $value New value. + * @param string $separator Separator, defaults to '.' + * @return $this + * @throws \RuntimeException + */ + public function setNestedProperty($property, $value, $separator = null) + { + $separator = $separator ?: '.'; + $path = explode($separator, $property); + $offset = array_shift($path); + + if (!$path) { + $this->setProperty($offset, $value); + + return $this; + } + + $current = &$this->doGetProperty($offset, null, true); + + while ($path) { + $offset = array_shift($path); + + // Handle arrays and scalars. + if ($current === null) { + $current = [$offset => []]; + } elseif (is_array($current)) { + if (!isset($current[$offset])) { + $current[$offset] = []; + } + } else { + throw new \RuntimeException('Cannot set nested property on non-array value'); + } + + $current = &$current[$offset]; + }; + + $current = $value; + + return $this; + } + + /** + * @param string $property Object property to be updated. + * @param string $separator Separator, defaults to '.' + * @return $this + * @throws \RuntimeException + */ + public function unsetNestedProperty($property, $separator = null) + { + $separator = $separator ?: '.'; + $path = explode($separator, $property); + $offset = array_shift($path); + + if (!$path) { + $this->unsetProperty($offset); + + return $this; + } + + $last = array_pop($path); + $current = &$this->doGetProperty($offset, null, true); + + while ($path) { + $offset = array_shift($path); + + // Handle arrays and scalars. + if ($current === null) { + return $this; + } + if (is_array($current)) { + if (!isset($current[$offset])) { + return $this; + } + } else { + throw new \RuntimeException('Cannot set nested property on non-array value'); + } + + $current = &$current[$offset]; + }; + + unset($current[$last]); + + return $this; + } + + /** + * @param string $property Object property to be updated. + * @param string $default Default value. + * @param string $separator Separator, defaults to '.' + * @return $this + * @throws \RuntimeException + */ + public function defNestedProperty($property, $default, $separator = null) + { + if (!$this->hasNestedProperty($property, $separator)) { + $this->setNestedProperty($property, $default, $separator); + } + + return $this; + } + + + abstract public function hasProperty($property); + abstract public function getProperty($property, $default = null); + abstract public function setProperty($property, $value); + abstract public function unsetProperty($property); + abstract protected function &doGetProperty($property, $default = null, $doCreate = false); +} diff --git a/system/src/Grav/Framework/Object/Access/OverloadedPropertyTrait.php b/system/src/Grav/Framework/Object/Access/OverloadedPropertyTrait.php new file mode 100644 index 0000000..1524bd6 --- /dev/null +++ b/system/src/Grav/Framework/Object/Access/OverloadedPropertyTrait.php @@ -0,0 +1,64 @@ +hasProperty($offset); + } + + /** + * Returns the value at specified offset. + * + * @param mixed $offset The offset to retrieve. + * @return mixed Can return all value types. + */ + public function __get($offset) + { + return $this->getProperty($offset); + } + + /** + * Assigns a value to the specified offset. + * + * @param mixed $offset The offset to assign the value to. + * @param mixed $value The value to set. + */ + public function __set($offset, $value) + { + $this->setProperty($offset, $value); + } + + /** + * Magic method to unset the attribute + * + * @param mixed $offset The name value to unset + */ + public function __unset($offset) + { + $this->unsetProperty($offset); + } + + abstract public function hasProperty($property); + abstract public function getProperty($property, $default = null); + abstract public function setProperty($property, $value); + abstract public function unsetProperty($property); +} diff --git a/system/src/Grav/Framework/Object/ArrayObject.php b/system/src/Grav/Framework/Object/ArrayObject.php new file mode 100644 index 0000000..0804133 --- /dev/null +++ b/system/src/Grav/Framework/Object/ArrayObject.php @@ -0,0 +1,26 @@ +getIterator() as $key => $value) { + $list[$key] = is_object($value) ? clone $value : $value; + } + + // TODO: remove when PHP 5.6 is minimum (with doctrine/collections v1.4). + if (!method_exists($this, 'createFrom')) { + return new static($list); + } + + return $this->createFrom($list); + } + + /** + * @return array + */ + public function getObjectKeys() + { + return $this->call('getKey'); + } + + /** + * @param string $property Object property to be matched. + * @return array Key/Value pairs of the properties. + */ + public function doHasProperty($property) + { + $list = []; + + /** @var ObjectInterface $element */ + foreach ($this->getIterator() as $id => $element) { + $list[$id] = $element->hasProperty($property); + } + + return $list; + } + + /** + * @param string $property Object property to be fetched. + * @param mixed $default Default value if not set. + * @return array Key/Value pairs of the properties. + */ + public function doGetProperty($property, $default = null) + { + $list = []; + + /** @var ObjectInterface $element */ + foreach ($this->getIterator() as $id => $element) { + $list[$id] = $element->getProperty($property, $default); + } + + return $list; + } + + /** + * @param string $property Object property to be updated. + * @param string $value New value. + * @return $this + */ + public function doSetProperty($property, $value) + { + /** @var ObjectInterface $element */ + foreach ($this->getIterator() as $element) { + $element->setProperty($property, $value); + } + + return $this; + } + + /** + * @param string $property Object property to be updated. + * @return $this + */ + public function doUnsetProperty($property) + { + /** @var ObjectInterface $element */ + foreach ($this->getIterator() as $element) { + $element->unsetProperty($property); + } + + return $this; + } + + /** + * @param string $property Object property to be updated. + * @param string $default Default value. + * @return $this + */ + public function doDefProperty($property, $default) + { + /** @var ObjectInterface $element */ + foreach ($this->getIterator() as $element) { + $element->defProperty($property, $default); + } + + return $this; + } + + /** + * @param string $method Method name. + * @param array $arguments List of arguments passed to the function. + * @return array Return values. + */ + public function call($method, array $arguments = []) + { + $list = []; + + foreach ($this->getIterator() as $id => $element) { + $list[$id] = method_exists($element, $method) + ? call_user_func_array([$element, $method], $arguments) : null; + } + + return $list; + } + + /** + * Group items in the collection by a field and return them as associated array. + * + * @param string $property + * @return array + */ + public function group($property) + { + $list = []; + + /** @var ObjectInterface $element */ + foreach ($this->getIterator() as $element) { + $list[(string) $element->getProperty($property)][] = $element; + } + + return $list; + } + + /** + * Group items in the collection by a field and return them as associated array of collections. + * + * @param string $property + * @return static[] + */ + public function collectionGroup($property) + { + $collections = []; + foreach ($this->group($property) as $id => $elements) { + // TODO: remove when PHP 5.6 is minimum (with doctrine/collections v1.4). + if (!method_exists($this, 'createFrom')) { + $collection = new static($elements); + } else { + $collection = $this->createFrom($elements); + } + + $collections[$id] = $collection; + } + + return $collections; + } + + /** + * @return \Traversable + */ + abstract public function getIterator(); +} diff --git a/system/src/Grav/Framework/Object/Base/ObjectTrait.php b/system/src/Grav/Framework/Object/Base/ObjectTrait.php new file mode 100644 index 0000000..6522e8e --- /dev/null +++ b/system/src/Grav/Framework/Object/Base/ObjectTrait.php @@ -0,0 +1,174 @@ +_key ?: $this->getType() . '@' . spl_object_hash($this); + } + + /** + * @param string $property Object property name. + * @return bool True if property has been defined (can be null). + */ + public function hasProperty($property) + { + return $this->doHasProperty($property); + } + + /** + * @param string $property Object property to be fetched. + * @param mixed $default Default value if property has not been set. + * @return mixed Property value. + */ + public function getProperty($property, $default = null) + { + return $this->doGetProperty($property, $default); + } + + /** + * @param string $property Object property to be updated. + * @param string $value New value. + * @return $this + */ + public function setProperty($property, $value) + { + $this->doSetProperty($property, $value); + + return $this; + } + + /** + * @param string $property Object property to be unset. + * @return $this + */ + public function unsetProperty($property) + { + $this->doUnsetProperty($property); + + return $this; + } + + /** + * @param string $property Object property to be defined. + * @param mixed $default Default value. + * @return $this + */ + public function defProperty($property, $default) + { + if (!$this->hasProperty($property)) { + $this->setProperty($property, $default); + } + + return $this; + } + + /** + * Implements Serializable interface. + * + * @return string + */ + public function serialize() + { + return serialize($this->jsonSerialize()); + } + + /** + * @param string $serialized + */ + public function unserialize($serialized) + { + $data = unserialize($serialized); + + if (method_exists($this, 'initObjectProperties')) { + $this->initObjectProperties(); + } + $this->doUnserialize($data); + } + + /** + * @param array $serialized + */ + protected function doUnserialize(array $serialized) + { + if (!isset($serialized['key'], $serialized['type'], $serialized['elements']) || $serialized['type'] !== $this->getType()) { + throw new \InvalidArgumentException("Cannot unserialize '{$this->getType()}': Bad data"); + } + + $this->setKey($serialized['key']); + $this->setElements($serialized['elements']); + } + + /** + * Implements JsonSerializable interface. + * + * @return array + */ + public function jsonSerialize() + { + return ['key' => $this->getKey(), 'type' => $this->getType(), 'elements' => $this->getElements()]; + } + + /** + * Returns a string representation of this object. + * + * @return string + */ + public function __toString() + { + return $this->getKey(); + } + + /** + * @param string $key + */ + protected function setKey($key) + { + $this->_key = (string) $key; + } + + abstract protected function doHasProperty($property); + abstract protected function &doGetProperty($property, $default = null, $doCreate = false); + abstract protected function doSetProperty($property, $value); + abstract protected function doUnsetProperty($property); + abstract protected function getElements(); + abstract protected function setElements(array $elements); +} diff --git a/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php b/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php new file mode 100644 index 0000000..3f8d784 --- /dev/null +++ b/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php @@ -0,0 +1,57 @@ +setElements($elements)); + + $this->setKey($key); + } + + protected function getElements() + { + return $this->toArray(); + } + + protected function setElements(array $elements) + { + return $elements; + } +} diff --git a/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php b/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php new file mode 100644 index 0000000..400b163 --- /dev/null +++ b/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php @@ -0,0 +1,109 @@ +setElements($elements); + $this->setKey($key); + } + + /** + * @param string $property Object property name. + * @return bool True if property has been defined (can be null). + */ + protected function doHasProperty($property) + { + return array_key_exists($property, $this->_elements); + } + + /** + * @param string $property Object property to be fetched. + * @param mixed $default Default value if property has not been set. + * @param bool $doCreate Set true to create variable. + * @return mixed Property value. + */ + protected function &doGetProperty($property, $default = null, $doCreate = false) + { + if (!array_key_exists($property, $this->_elements)) { + if ($doCreate) { + $this->_elements[$property] = null; + } else { + return $default; + } + } + + return $this->_elements[$property]; + } + + /** + * @param string $property Object property to be updated. + * @param mixed $value New value. + */ + protected function doSetProperty($property, $value) + { + $this->_elements[$property] = $value; + } + + /** + * @param string $property Object property to be unset. + */ + protected function doUnsetProperty($property) + { + unset($this->_elements[$property]); + } + + /** + * @param string $property + * @param mixed|null $default + * @return mixed|null + */ + protected function getElement($property, $default = null) + { + return array_key_exists($property, $this->_elements) ? $this->_elements[$property] : $default; + } + + /** + * @return array + */ + protected function getElements() + { + return $this->_elements; + } + + /** + * @param array $elements + */ + protected function setElements(array $elements) + { + $this->_elements = $elements; + } + + abstract protected function setKey($key); +} diff --git a/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php b/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php new file mode 100644 index 0000000..28b9432 --- /dev/null +++ b/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php @@ -0,0 +1,117 @@ +offsetLoad($offset, $value)` called first time object property gets accessed + * - `$this->offsetPrepare($offset, $value)` called on every object property set + * - `$this->offsetSerialize($offset, $value)` called when the raw or serialized object property value is needed + * + * @package Grav\Framework\Object\Property + */ +trait LazyPropertyTrait +{ + use ArrayPropertyTrait, ObjectPropertyTrait { + ObjectPropertyTrait::__construct insteadof ArrayPropertyTrait; + ArrayPropertyTrait::doHasProperty as hasArrayProperty; + ArrayPropertyTrait::doGetProperty as getArrayProperty; + ArrayPropertyTrait::doSetProperty as setArrayProperty; + ArrayPropertyTrait::doUnsetProperty as unsetArrayProperty; + ArrayPropertyTrait::getElement as getArrayElement; + ArrayPropertyTrait::getElements as getArrayElements; + ArrayPropertyTrait::setElements insteadof ObjectPropertyTrait; + ObjectPropertyTrait::doHasProperty as hasObjectProperty; + ObjectPropertyTrait::doGetProperty as getObjectProperty; + ObjectPropertyTrait::doSetProperty as setObjectProperty; + ObjectPropertyTrait::doUnsetProperty as unsetObjectProperty; + ObjectPropertyTrait::getElement as getObjectElement; + ObjectPropertyTrait::getElements as getObjectElements; + } + + /** + * @param string $property Object property name. + * @return bool True if property has been defined (can be null). + */ + protected function doHasProperty($property) + { + return $this->hasArrayProperty($property) || $this->hasObjectProperty($property); + } + + /** + * @param string $property Object property to be fetched. + * @param mixed $default Default value if property has not been set. + * @return mixed Property value. + */ + protected function &doGetProperty($property, $default = null, $doCreate = false) + { + if ($this->hasObjectProperty($property)) { + return $this->getObjectProperty($property, $default, function ($default = null) use ($property) { + return $this->getArrayProperty($property, $default); + }); + } + + return $this->getArrayProperty($property, $default, $doCreate); + } + + /** + * @param string $property Object property to be updated. + * @param mixed $value New value. + * @return $this + */ + protected function doSetProperty($property, $value) + { + if ($this->hasObjectProperty($property)) { + $this->setObjectProperty($property, $value); + } else { + $this->setArrayProperty($property, $value); + } + + return $this; + } + + /** + * @param string $property Object property to be unset. + * @return $this + */ + protected function doUnsetProperty($property) + { + $this->hasObjectProperty($property) ? + $this->unsetObjectProperty($property) : $this->unsetArrayProperty($property); + + return $this; + } + + /** + * @param string $property + * @param mixed|null $default + * @return mixed|null + */ + protected function getElement($property, $default = null) + { + if ($this->isPropertyLoaded($property)) { + return $this->getObjectElement($property, $default); + } + + return $this->getArrayElement($property, $default); + } + + /** + * @return array + */ + protected function getElements() + { + return $this->getObjectElements() + $this->getArrayElements(); + } +} diff --git a/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php b/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php new file mode 100644 index 0000000..2c86376 --- /dev/null +++ b/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php @@ -0,0 +1,122 @@ +offsetLoad($offset, $value)` called first time object property gets accessed + * - `$this->offsetPrepare($offset, $value)` called on every object property set + * - `$this->offsetSerialize($offset, $value)` called when the raw or serialized object property value is needed + + * + * @package Grav\Framework\Object\Property + */ +trait MixedPropertyTrait +{ + use ArrayPropertyTrait, ObjectPropertyTrait { + ObjectPropertyTrait::__construct insteadof ArrayPropertyTrait; + ArrayPropertyTrait::doHasProperty as hasArrayProperty; + ArrayPropertyTrait::doGetProperty as getArrayProperty; + ArrayPropertyTrait::doSetProperty as setArrayProperty; + ArrayPropertyTrait::doUnsetProperty as unsetArrayProperty; + ArrayPropertyTrait::getElement as getArrayElement; + ArrayPropertyTrait::getElements as getArrayElements; + ArrayPropertyTrait::setElements as setArrayElements; + ObjectPropertyTrait::doHasProperty as hasObjectProperty; + ObjectPropertyTrait::doGetProperty as getObjectProperty; + ObjectPropertyTrait::doSetProperty as setObjectProperty; + ObjectPropertyTrait::doUnsetProperty as unsetObjectProperty; + ObjectPropertyTrait::getElement as getObjectElement; + ObjectPropertyTrait::getElements as getObjectElements; + ObjectPropertyTrait::setElements as setObjectElements; + } + + /** + * @param string $property Object property name. + * @return bool True if property has been defined (can be null). + */ + protected function doHasProperty($property) + { + return $this->hasArrayProperty($property) || $this->hasObjectProperty($property); + } + + /** + * @param string $property Object property to be fetched. + * @param mixed $default Default value if property has not been set. + * @return mixed Property value. + */ + protected function &doGetProperty($property, $default = null, $doCreate = false) + { + if ($this->hasObjectProperty($property)) { + return $this->getObjectProperty($property); + } + + return $this->getArrayProperty($property, $default, $doCreate); + } + + /** + * @param string $property Object property to be updated. + * @param mixed $value New value. + * @return $this + */ + protected function doSetProperty($property, $value) + { + $this->hasObjectProperty($property) + ? $this->setObjectProperty($property, $value) : $this->setArrayProperty($property, $value); + + return $this; + } + + /** + * @param string $property Object property to be unset. + * @return $this + */ + protected function doUnsetProperty($property) + { + $this->hasObjectProperty($property) ? + $this->unsetObjectProperty($property) : $this->unsetArrayProperty($property); + + return $this; + } + + /** + * @param string $property + * @param mixed|null $default + * @return mixed|null + */ + protected function getElement($property, $default = null) + { + if ($this->hasObjectProperty($property)) { + return $this->getObjectElement($property, $default); + } + + return $this->getArrayElement($property, $default); + } + + /** + * @return array + */ + protected function getElements() + { + return $this->getObjectElements() + $this->getArrayElements(); + } + + /** + * @param array $elements + */ + protected function setElements(array $elements) + { + $this->setObjectElements(array_intersect_key($elements, $this->_definedProperties)); + $this->setArrayElements(array_diff_key($elements, $this->_definedProperties)); + } +} diff --git a/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php b/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php new file mode 100644 index 0000000..c26903f --- /dev/null +++ b/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php @@ -0,0 +1,203 @@ +offsetLoad($offset, $value)` called first time object property gets accessed + * - `$this->offsetPrepare($offset, $value)` called on every object property set + * - `$this->offsetSerialize($offset, $value)` called when the raw or serialized object property value is needed + * + * @package Grav\Framework\Object\Property + */ +trait ObjectPropertyTrait +{ + /** + * @var array + */ + private $_definedProperties; + + /** + * @param array $elements + * @param string $key + * @throws \InvalidArgumentException + */ + public function __construct(array $elements = [], $key = null) + { + $this->initObjectProperties(); + $this->setElements($elements); + $this->setKey($key); + } + + /** + * @param string $property Object property name. + * @return bool True if property has been loaded. + */ + protected function isPropertyLoaded($property) + { + return !empty($this->_definedProperties[$property]); + } + + /** + * @param string $offset + * @param mixed $value + * @return mixed + */ + protected function offsetLoad($offset, $value) + { + $methodName = "offsetLoad_{$offset}"; + + return method_exists($this, $methodName)? $this->{$methodName}($value) : $value; + } + + /** + * @param string $offset + * @param mixed $value + * @return mixed + */ + protected function offsetPrepare($offset, $value) + { + $methodName = "offsetPrepare_{$offset}"; + + return method_exists($this, $methodName) ? $this->{$methodName}($value) : $value; + } + + /** + * @param string $offset + * @param mixed $value + * @return mixed + */ + protected function offsetSerialize($offset, $value) + { + $methodName = "offsetSerialize_{$offset}"; + + return method_exists($this, $methodName) ? $this->{$methodName}($value) : $value; + } + + /** + * @param string $property Object property name. + * @return bool True if property has been defined (can be null). + */ + protected function doHasProperty($property) + { + return array_key_exists($property, $this->_definedProperties); + } + + /** + * @param string $property Object property to be fetched. + * @param mixed $default Default value if property has not been set. + * @param bool $doCreate Set true to create variable. + * @return mixed Property value. + */ + protected function &doGetProperty($property, $default = null, $doCreate = false) + { + if (!array_key_exists($property, $this->_definedProperties)) { + throw new \InvalidArgumentException("Property '{$property}' does not exist in the object!"); + } + + if (empty($this->_definedProperties[$property])) { + if ($doCreate === true) { + $this->_definedProperties[$property] = true; + $this->{$property} = null; + } elseif (is_callable($doCreate)) { + $this->_definedProperties[$property] = true; + $this->{$property} = $this->offsetLoad($property, $doCreate()); + } else { + return $default; + } + } + + return $this->{$property}; + } + + /** + * @param string $property Object property to be updated. + * @param mixed $value New value. + * @throws \InvalidArgumentException + */ + protected function doSetProperty($property, $value) + { + if (!array_key_exists($property, $this->_definedProperties)) { + throw new \InvalidArgumentException("Property '{$property}' does not exist in the object!"); + } + + $this->_definedProperties[$property] = true; + $this->{$property} = $this->offsetPrepare($property, $value); + } + + /** + * @param string $property Object property to be unset. + */ + protected function doUnsetProperty($property) + { + if (!array_key_exists($property, $this->_definedProperties)) { + return; + } + + $this->_definedProperties[$property] = false; + unset($this->{$property}); + } + + protected function initObjectProperties() + { + $this->_definedProperties = []; + foreach (get_object_vars($this) as $property => $value) { + if ($property[0] !== '_') { + $this->_definedProperties[$property] = ($value !== null); + } + } + } + + /** + * @param string $property + * @param mixed|null $default + * @return mixed|null + */ + protected function getElement($property, $default = null) + { + if (empty($this->_definedProperties[$property])) { + return $default; + } + + return $this->offsetSerialize($property, $this->{$property}); + } + + /** + * @return array + */ + protected function getElements() + { + $properties = array_intersect_key(get_object_vars($this), array_filter($this->_definedProperties)); + + $elements = []; + foreach ($properties as $offset => $value) { + $elements[$offset] = $this->offsetSerialize($offset, $value); + } + + return $elements; + } + + /** + * @param array $elements + */ + protected function setElements(array $elements) + { + foreach ($elements as $property => $value) { + $this->setProperty($property, $value); + } + } + + abstract public function setProperty($property, $value); + abstract protected function setKey($key); +} diff --git a/system/src/Grav/Framework/Object/PropertyObject.php b/system/src/Grav/Framework/Object/PropertyObject.php new file mode 100644 index 0000000..99f7e7f --- /dev/null +++ b/system/src/Grav/Framework/Object/PropertyObject.php @@ -0,0 +1,26 @@ + 80, + 'https' => 443 + ]; + + /** @var string Uri scheme. */ + private $scheme = ''; + + /** @var string Uri user. */ + private $user = ''; + + /** @var string Uri password. */ + private $password = ''; + + /** @var string Uri host. */ + private $host = ''; + + /** @var int|null Uri port. */ + private $port; + + /** @var string Uri path. */ + private $path = ''; + + /** @var string Uri query string (without ?). */ + private $query = ''; + + /** @var string Uri fragment (without #). */ + private $fragment = ''; + + /** + * Please define constructor which calls $this->init(). + */ + abstract public function __construct(); + + /** + * @inheritdoc + */ + public function getScheme() + { + return $this->scheme; + } + + /** + * @inheritdoc + */ + public function getAuthority() + { + $authority = $this->host; + + $userInfo = $this->getUserInfo(); + if ($userInfo !== '') { + $authority = $userInfo . '@' . $authority; + } + + if ($this->port !== null) { + $authority .= ':' . $this->port; + } + + return $authority; + } + + /** + * @inheritdoc + */ + public function getUserInfo() + { + $userInfo = $this->user; + + if ($this->password !== '') { + $userInfo .= ':' . $this->password; + } + + return $userInfo; + } + + /** + * @inheritdoc + */ + public function getHost() + { + return $this->host; + } + + /** + * @inheritdoc + */ + public function getPort() + { + return $this->port; + } + + /** + * @inheritdoc + */ + public function getPath() + { + return $this->path; + } + + /** + * @inheritdoc + */ + public function getQuery() + { + return $this->query; + } + + /** + * @inheritdoc + */ + public function getFragment() + { + return $this->fragment; + } + + /** + * @inheritdoc + */ + public function withScheme($scheme) + { + $scheme = UriPartsFilter::filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->unsetDefaultPort(); + $new->validate(); + + return $new; + } + + /** + * @inheritdoc + * @throws \InvalidArgumentException + */ + public function withUserInfo($user, $password = '') + { + $user = UriPartsFilter::filterUserInfo($user); + $password = UriPartsFilter::filterUserInfo($password); + + if ($this->user === $user && $this->password === $password) { + return $this; + } + + $new = clone $this; + $new->user = $user; + $new->password = $user !== '' ? $password : ''; + $new->validate(); + + return $new; + } + + /** + * @inheritdoc + */ + public function withHost($host) + { + $host = UriPartsFilter::filterHost($host); + + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + $new->validate(); + + return $new; + } + + /** + * @inheritdoc + */ + public function withPort($port) + { + $port = UriPartsFilter::filterPort($port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + $new->unsetDefaultPort(); + $new->validate(); + + return $new; + } + + /** + * @inheritdoc + */ + public function withPath($path) + { + $path = UriPartsFilter::filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + $new->validate(); + + return $new; + } + + /** + * @inheritdoc + */ + public function withQuery($query) + { + $query = UriPartsFilter::filterQueryOrFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + + return $new; + } + + /** + * @inheritdoc + * @throws \InvalidArgumentException + */ + public function withFragment($fragment) + { + $fragment = UriPartsFilter::filterQueryOrFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + + return $new; + } + + /** + * @return string + */ + public function __toString() + { + return $this->getUrl(); + } + + /** + * @return array + */ + protected function getParts() + { + return [ + 'scheme' => $this->scheme, + 'host' => $this->host, + 'port' => $this->port, + 'user' => $this->user, + 'pass' => $this->password, + 'path' => $this->path, + 'query' => $this->query, + 'fragment' => $this->fragment + ]; + } + + /** + * Return the fully qualified base URL ( like http://getgrav.org ). + * + * Note that this method never includes a trailing / + * + * @return string + */ + protected function getBaseUrl() + { + $uri = ''; + + $scheme = $this->getScheme(); + if ($scheme !== '') { + $uri .= $scheme . ':'; + } + + $authority = $this->getAuthority(); + if ($authority !== '' || $scheme === 'file') { + $uri .= '//' . $authority; + } + + return $uri; + } + + /** + * @return string + */ + protected function getUrl() + { + $uri = $this->getBaseUrl() . $this->getPath(); + + $query = $this->getQuery(); + if ($query !== '') { + $uri .= '?' . $query; + } + + $fragment = $this->getFragment(); + if ($fragment !== '') { + $uri .= '#' . $fragment; + } + + return $uri; + } + + /** + * @return string + */ + protected function getUser() + { + return $this->user; + } + + /** + * @return string + */ + protected function getPassword() + { + return $this->password; + } + + /** + * @param array $parts + * @throws \InvalidArgumentException + */ + protected function initParts(array $parts) + { + $this->scheme = isset($parts['scheme']) ? UriPartsFilter::filterScheme($parts['scheme']) : ''; + $this->user = isset($parts['user']) ? UriPartsFilter::filterUserInfo($parts['user']) : ''; + $this->password = isset($parts['pass']) ? UriPartsFilter::filterUserInfo($parts['pass']) : ''; + $this->host = isset($parts['host']) ? UriPartsFilter::filterHost($parts['host']) : ''; + $this->port = isset($parts['port']) ? UriPartsFilter::filterPort((int)$parts['port']) : null; + $this->path = isset($parts['path']) ? UriPartsFilter::filterPath($parts['path']) : ''; + $this->query = isset($parts['query']) ? UriPartsFilter::filterQueryOrFragment($parts['query']) : ''; + $this->fragment = isset($parts['fragment']) ? UriPartsFilter::filterQueryOrFragment($parts['fragment']) : ''; + + $this->unsetDefaultPort(); + $this->validate(); + } + + /** + * @throws \InvalidArgumentException + */ + private function validate() + { + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { + throw new \InvalidArgumentException('Uri with a scheme must have a host'); + } + + if ($this->getAuthority() === '') { + if (0 === strpos($this->path, '//')) { + throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes \'//\''); + } + if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { + throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon'); + } + } elseif (isset($this->path[0]) && $this->path[0] !== '/') { + throw new \InvalidArgumentException('The path of a URI with an authority must start with a slash \'/\' or be empty'); + } + } + + protected function isDefaultPort() + { + $scheme = $this->scheme; + $port = $this->port; + + return $this->port === null + || (isset(static::$defaultPorts[$scheme]) && $port === static::$defaultPorts[$scheme]); + } + + private function unsetDefaultPort() + { + if ($this->isDefaultPort()) { + $this->port = null; + } + } +} diff --git a/system/src/Grav/Framework/Route/Route.php b/system/src/Grav/Framework/Route/Route.php new file mode 100644 index 0000000..503d2a8 --- /dev/null +++ b/system/src/Grav/Framework/Route/Route.php @@ -0,0 +1,301 @@ +initParts($parts); + } + + /** + * @return array + */ + public function getParts() + { + return [ + 'path' => $this->getUriPath(), + 'query' => $this->getUriQuery(), + 'grav' => [ + 'root' => $this->root, + 'language' => $this->language, + 'route' => $this->route, + 'grav_params' => $this->gravParams, + 'query_params' => $this->queryParams, + ], + ]; + } + + /** + * @return string + */ + public function getRootPrefix() + { + return $this->root; + } + + /** + * @return string + */ + public function getLanguagePrefix() + { + return $this->language !== '' ? '/' . $this->language : ''; + } + + /** + * @param int $offset + * @param int|null $length + * @return string + */ + public function getRoute($offset = 0, $length = null) + { + if ($offset !== 0 || $length !== null) { + return ($offset === 0 ? '/' : '') . implode('/', $this->getRouteParts($offset, $length)); + } + + return '/' . $this->route; + } + + /** + * @param int $offset + * @param int|null $length + * @return array + */ + public function getRouteParts($offset = 0, $length = null) + { + $parts = explode('/', $this->route); + + if ($offset !== 0 || $length !== null) { + $parts = array_slice($parts, $offset, $length); + } + + return $parts; + } + + /** + * Return array of both query and Grav parameters. + * + * If a parameter exists in both, prefer Grav parameter. + * + * @return array + */ + public function getParams() + { + return $this->gravParams + $this->queryParams; + } + + /** + * @return array + */ + public function getGravParams() + { + return $this->gravParams; + } + + /** + * @return array + */ + public function getQueryParams() + { + return $this->queryParams; + } + + /** + * Return value of the parameter, looking into both Grav parameters and query parameters. + * + * If the parameter exists in both, return Grav parameter. + * + * @param string $param + * @return string|null + */ + public function getParam($param) + { + $value = $this->getGravParam($param); + if ($value === null) { + $value = $this->getQueryParam($param); + } + + return $value; + } + + /** + * @param string $param + * @return string|null + */ + public function getGravParam($param) + { + return isset($this->gravParams[$param]) ? $this->gravParams[$param] : null; + } + + /** + * @param string $param + * @return string|null + */ + public function getQueryParam($param) + { + return isset($this->queryParams[$param]) ? $this->queryParams[$param] : null; + } + + /** + * @param string $param + * @param mixed $value + * @return Route + */ + public function withGravParam($param, $value) + { + return $this->withParam('gravParams', $param, $value); + } + + /** + * @param string $param + * @param mixed $value + * @return Route + */ + public function withQueryParam($param, $value) + { + return $this->withParam('queryParams', $param, $value); + } + + /** + * @return \Grav\Framework\Uri\Uri + */ + public function getUri() + { + return UriFactory::createFromParts($this->getParts()); + } + + /** + * @return string + */ + public function __toString() + { + $url = $this->getUriPath(); + + if ($this->queryParams) { + $url .= '?' . $this->getUriQuery(); + } + + return $url; + } + + /** + * @param string $type + * @param string $param + * @param mixed $value + * @return static + */ + protected function withParam($type, $param, $value) + { + $oldValue = isset($this->{$type}[$param]) ? $this->{$type}[$param] : null; + $newValue = null !== $value ? (string)$value : null; + + if ($oldValue === $newValue) { + return $this; + } + + $new = clone $this; + if ($newValue === null) { + unset($new->{$type}[$param]); + } else { + $new->{$type}[$param] = $newValue; + } + + return $new; + } + + /** + * @return string + */ + protected function getUriPath() + { + $parts = [$this->root]; + + if ($this->language !== '') { + $parts[] = $this->language; + } + + if ($this->route !== '') { + $parts[] = $this->route; + } + + if ($this->gravParams) { + $parts[] = RouteFactory::buildParams($this->gravParams); + } + + return implode('/', $parts); + } + + /** + * @return string + */ + protected function getUriQuery() + { + return UriFactory::buildQuery($this->queryParams); + } + + /** + * @param array $parts + */ + protected function initParts(array $parts) + { + if (isset($parts['grav'])) { + $gravParts = $parts['grav']; + $this->root = $gravParts['root']; + $this->language = $gravParts['language']; + $this->route = $gravParts['route']; + $this->gravParams = $gravParts['params']; + $this->queryParams = $parts['query_params']; + + } else { + $this->root = RouteFactory::getRoot(); + $this->language = RouteFactory::getLanguage(); + + $path = isset($parts['path']) ? $parts['path'] : '/'; + if (isset($parts['params'])) { + $this->route = trim(rawurldecode($path), '/'); + $this->gravParams = $parts['params']; + } else { + $this->route = trim(RouteFactory::stripParams($path, true), '/'); + $this->gravParams = RouteFactory::getParams($path); + } + if (isset($parts['query'])) { + $this->queryParams = UriFactory::parseQuery($parts['query']); + } + } + } +} diff --git a/system/src/Grav/Framework/Route/RouteFactory.php b/system/src/Grav/Framework/Route/RouteFactory.php new file mode 100644 index 0000000..a406926 --- /dev/null +++ b/system/src/Grav/Framework/Route/RouteFactory.php @@ -0,0 +1,131 @@ + $value) { + $output[] = "{$key}{$delimiter}{$value}"; + } + + return implode('/', $output); + } + + /** + * @param string $path + * @param bool $decode + * @return string + */ + public static function stripParams($path, $decode = false) + { + $pos = strpos($path, self::$delimiter); + + if ($pos === false) { + return $path; + } + + $path = dirname(substr($path, 0, $pos)); + if ($path === '.') { + return ''; + } + + return $decode ? rawurldecode($path) : $path; + } + + /** + * @param string $path + * @return array + */ + public static function getParams($path) + { + $params = ltrim(substr($path, strlen(static::stripParams($path))), '/'); + + return $params !== '' ? static::parseParams($params) : []; + } + + /** + * @param string $str + * @return array + */ + public static function parseParams($str) + { + $delimiter = self::$delimiter; + + $params = explode('/', $str); + foreach ($params as &$param) { + $parts = explode($delimiter, $param, 2); + if (isset($parts[1])) { + $param[rawurldecode($parts[0])] = rawurldecode($parts[1]); + } + } + + return $params; + } +} diff --git a/system/src/Grav/Framework/Uri/Uri.php b/system/src/Grav/Framework/Uri/Uri.php new file mode 100644 index 0000000..2821360 --- /dev/null +++ b/system/src/Grav/Framework/Uri/Uri.php @@ -0,0 +1,213 @@ +initParts($parts); + } + + /** + * @return string + */ + public function getUser() + { + return parent::getUser(); + } + + /** + * @return string + */ + public function getPassword() + { + return parent::getPassword(); + } + + /** + * @return array + */ + public function getParts() + { + return parent::getParts(); + } + + /** + * @return string + */ + public function getUrl() + { + return parent::getUrl(); + } + + /** + * @return string + */ + public function getBaseUrl() + { + return parent::getBaseUrl(); + } + + /** + * @param string $key + * @return string|null + */ + public function getQueryParam($key) + { + $queryParams = $this->getQueryParams(); + + return isset($queryParams[$key]) ? $queryParams[$key] : null; + } + + /** + * @param string $key + * @return UriInterface + */ + public function withoutQueryParam($key) + { + return GuzzleUri::withoutQueryValue($this, $key); + } + + /** + * @param string $key + * @param string|null $value + * @return UriInterface + */ + public function withQueryParam($key, $value) + { + return GuzzleUri::withQueryValue($this, $key, $value); + } + + /** + * @return array + */ + public function getQueryParams() + { + if ($this->queryParams === null) { + $this->queryParams = UriFactory::parseQuery($this->getQuery()); + } + + return $this->queryParams; + } + + /** + * @param array $params + * @return UriInterface + */ + public function withQueryParams(array $params) + { + $query = UriFactory::buildQuery($params); + + return $this->withQuery($query); + } + + /** + * Whether the URI has the default port of the current scheme. + * + * `$uri->getPort()` may return the standard port. This method can be used for some non-http/https Uri. + * + * @return bool + */ + public function isDefaultPort() + { + return $this->getPort() === null || GuzzleUri::isDefaultPort($this); + } + + /** + * Whether the URI is absolute, i.e. it has a scheme. + * + * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true + * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative + * to another URI, the base URI. Relative references can be divided into several forms: + * - network-path references, e.g. '//example.com/path' + * - absolute-path references, e.g. '/path' + * - relative-path references, e.g. 'subpath' + * + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-4 + */ + public function isAbsolute() + { + return GuzzleUri::isAbsolute($this); + } + + /** + * Whether the URI is a network-path reference. + * + * A relative reference that begins with two slash characters is termed an network-path reference. + * + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public function isNetworkPathReference() + { + return GuzzleUri::isNetworkPathReference($this); + } + + /** + * Whether the URI is a absolute-path reference. + * + * A relative reference that begins with a single slash character is termed an absolute-path reference. + * + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public function isAbsolutePathReference() + { + return GuzzleUri::isAbsolutePathReference($this); + } + + /** + * Whether the URI is a relative-path reference. + * + * A relative reference that does not begin with a slash character is termed a relative-path reference. + * + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public function isRelativePathReference() + { + return GuzzleUri::isRelativePathReference($this); + } + + /** + * Whether the URI is a same-document reference. + * + * A same-document reference refers to a URI that is, aside from its fragment + * component, identical to the base URI. When no base URI is given, only an empty + * URI reference (apart from its fragment) is considered a same-document reference. + * + * @param UriInterface|null $base An optional base URI to compare against + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-4.4 + */ + public function isSameDocumentReference(UriInterface $base = null) + { + return GuzzleUri::isSameDocumentReference($this, $base); + } +} diff --git a/system/src/Grav/Framework/Uri/UriFactory.php b/system/src/Grav/Framework/Uri/UriFactory.php new file mode 100644 index 0000000..c6bd428 --- /dev/null +++ b/system/src/Grav/Framework/Uri/UriFactory.php @@ -0,0 +1,159 @@ + $scheme, + 'user' => $user, + 'pass' => $pass, + 'host' => $host, + 'port' => $port, + 'path' => $path, + 'query' => $query + ]; + } + + /** + * UTF-8 aware parse_url() implementation. + * + * @param string $url + * @return array + * @throws \InvalidArgumentException + */ + public static function parseUrl($url) + { + if (!is_string($url)) { + throw new \InvalidArgumentException('URL must be a string'); + } + + $encodedUrl = preg_replace_callback( + '%[^:/@?&=#]+%u', + function ($matches) { return rawurlencode($matches[0]); }, + $url + ); + + $parts = parse_url($encodedUrl); + if ($parts === false) { + throw new \InvalidArgumentException('Malformed URL: ' . $encodedUrl); + } + + return $parts; + } + + /** + * Parse query string and return it as an array. + * + * @param string $query + * @return mixed + */ + public static function parseQuery($query) + { + parse_str($query, $params); + + return $params; + } + + /** + * Build query string from variables. + * + * @param array $params + * @return string + */ + public static function buildQuery(array $params) + { + return $params ? http_build_query($params, null, ini_get('arg_separator.output'), PHP_QUERY_RFC3986) : ''; + } +} diff --git a/system/src/Grav/Framework/Uri/UriPartsFilter.php b/system/src/Grav/Framework/Uri/UriPartsFilter.php new file mode 100644 index 0000000..36efa16 --- /dev/null +++ b/system/src/Grav/Framework/Uri/UriPartsFilter.php @@ -0,0 +1,140 @@ += 1 && $port <= 65535))) { + return $port; + } + + throw new \InvalidArgumentException('Uri port must be null or an integer between 1 and 65535'); + } + + /** + * Filter Uri path. + * + * This method percent-encodes all reserved characters in the provided path string. This method + * will NOT double-encode characters that are already percent-encoded. + * + * @param string $path The raw uri path. + * @return string The RFC 3986 percent-encoded uri path. + * @throws \InvalidArgumentException If the path is invalid. + * @link http://www.faqs.org/rfcs/rfc3986.html + */ + public static function filterPath($path) + { + if (!is_string($path)) { + throw new \InvalidArgumentException('Uri path must be a string'); + } + + return preg_replace_callback( + '/(?:[^a-zA-Z0-9_\-\.~:@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/u', + function ($match) { + return rawurlencode($match[0]); + }, + $path + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @param string $query The raw uri query string. + * @return string The percent-encoded query string. + * @throws \InvalidArgumentException If the query is invalid. + */ + public static function filterQueryOrFragment($query) + { + if (!is_string($query)) { + throw new \InvalidArgumentException('Uri query string and fragment must be a string'); + } + + return preg_replace_callback( + '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/u', + function ($match) { + return rawurlencode($match[0]); + }, + $query + ); + } +} diff --git a/system/templates/partials/messages.html.twig b/system/templates/partials/messages.html.twig new file mode 100644 index 0000000..261b3fc --- /dev/null +++ b/system/templates/partials/messages.html.twig @@ -0,0 +1,14 @@ +{% set status_mapping = {'info':'green', 'error': 'red', 'warning': 'yellow'} %} + +{% if grav.messages.all %} +
    + {% for message in grav.messages.fetch %} + + {% set scope = message.scope|e %} + {% set color = status_mapping[scope] %} + +

    {{ message.message|raw }}

    + + {% endfor %} +
    +{% endif %} diff --git a/system/templates/partials/metadata.html.twig b/system/templates/partials/metadata.html.twig new file mode 100644 index 0000000..bf323e7 --- /dev/null +++ b/system/templates/partials/metadata.html.twig @@ -0,0 +1,3 @@ +{% for meta in page.metadata %} + +{% endfor %} \ No newline at end of file diff --git a/tmp/.gitkeep b/tmp/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/user/accounts/.gitkeep b/user/accounts/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/user/accounts/admin.yaml b/user/accounts/admin.yaml new file mode 100644 index 0000000..3acea44 --- /dev/null +++ b/user/accounts/admin.yaml @@ -0,0 +1,11 @@ +email: kevin@figureslibres.io +fullname: 'Kevin Tessier' +title: Administrator +state: enabled +access: + admin: + login: true + super: true + site: + login: true +hashed_password: $2y$10$RCP2WDnZ7pI7kmo8dy5mKu6jTiKoaCNGdvupC1lLqo6WVCuna4WxC diff --git a/user/config/media.yaml b/user/config/media.yaml new file mode 100644 index 0000000..e69de29 diff --git a/user/config/plugins/youtube.yaml b/user/config/plugins/youtube.yaml new file mode 100644 index 0000000..5acb889 --- /dev/null +++ b/user/config/plugins/youtube.yaml @@ -0,0 +1,19 @@ +enabled: true +built_in_css: true +add_editor_button: true +player_parameters: + autoplay: 0 + cc_load_policy: 0 + color: red + controls: 1 + disablekb: 0 + enablejsapi: 0 + fs: 1 + iv_load_policy: 1 + loop: 0 + modestbranding: 0 + playsinline: 0 + rel: 1 + showinfo: 0 + vq: default +privacy_enhanced_mode: false diff --git a/user/config/security.yaml b/user/config/security.yaml new file mode 100644 index 0000000..5b9d72d --- /dev/null +++ b/user/config/security.yaml @@ -0,0 +1 @@ +salt: ADSNJIzFp15uoc diff --git a/user/config/site.yaml b/user/config/site.yaml new file mode 100644 index 0000000..839318a --- /dev/null +++ b/user/config/site.yaml @@ -0,0 +1,17 @@ +title: 'Anissa bensalah' +default_lang: fr +author: + name: 'Kevin Tessier' + email: kevin@figureslibres.io +taxonomies: + - category + - tag +metadata: + description: 'Le site anissabensalah.net est développé avec le CMS Grav par Kévin Tessier (FiguresLibres)' +summary: + enabled: false + format: long + size: 200 + delimiter: '===' +blog: + route: /blog diff --git a/user/config/streams.yaml b/user/config/streams.yaml new file mode 100644 index 0000000..e69de29 diff --git a/user/config/system.yaml b/user/config/system.yaml new file mode 100644 index 0000000..3df9c6f --- /dev/null +++ b/user/config/system.yaml @@ -0,0 +1,141 @@ +absolute_urls: false +param_sep: ':' +wrapped_site: false +reverse_proxy_setup: false +force_ssl: false +force_lowercase_urls: true +username_regex: '^[a-z0-9_-]{3,16}$' +pwd_regex: '(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}' +intl_enabled: true +languages: + supported: + - fr + - en + - pt + include_default_lang: true + translations: true + translations_fallback: true + session_store_active: true + http_accept_language: true + override_locale: true +home: + alias: /home + hide_in_urls: false +pages: + theme: quark + order: + by: default + dir: asc + list: + count: 20 + dateformat: + short: 'jS M Y' + long: 'F jS \a\t g:ia' + publish_dates: true + process: + markdown: true + twig: false + twig_first: false + never_cache_twig: false + events: + page: true + twig: true + markdown: + extra: false + auto_line_breaks: true + auto_url_links: false + escape_markup: false + special_chars: + '>': gt + '<': lt + types: + - txt + - xml + - html + - htm + - json + - rss + - atom + expires: 604800 + last_modified: false + etag: false + vary_accept_encoding: false + redirect_default_route: false + redirect_default_code: '302' + redirect_trailing_slash: true + ignore_files: + - .DS_Store + ignore_folders: + - .git + - .idea + ignore_hidden: true + url_taxonomy_filters: true + frontmatter: + process_twig: false + ignore_fields: + - form + - forms +cache: + enabled: false + check: + method: file + driver: auto + prefix: g + clear_images_by_default: true + cli_compatibility: false + lifetime: 604800 + gzip: false + allow_webserver_gzip: false +twig: + cache: false + debug: true + auto_reload: true + autoescape: false + undefined_functions: true + undefined_filters: true + umask_fix: false +assets: + css_pipeline: false + css_pipeline_include_externals: true + css_pipeline_before_excludes: true + css_minify: true + css_minify_windows: false + css_rewrite: true + js_pipeline: false + js_pipeline_include_externals: true + js_pipeline_before_excludes: true + js_minify: true + enable_asset_timestamp: false + collections: + jquery: 'system://assets/jquery/jquery-2.x.min.js' +errors: + display: '1' + log: true +debugger: + enabled: false + shutdown: + close_connection: true + twig: true +images: + default_image_quality: 85 + cache_all: false + cache_perms: '0755' + debug: false + auto_fix_orientation: false +media: + enable_media_timestamp: false + auto_metadata_exif: false + upload_limit: 2097152 +session: + enabled: true + initialize: true + timeout: 1800 + name: grav-site + secure: false + httponly: true + split: true +gpm: + releases: stable + method: auto + verify_peer: true + official_gpm_only: true diff --git a/user/data/.gitkeep b/user/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/user/data/licenses.yaml b/user/data/licenses.yaml new file mode 100644 index 0000000..e69de29 diff --git a/user/pages/01.home/01.fullvideo/text.fr.md b/user/pages/01.home/01.fullvideo/text.fr.md new file mode 100644 index 0000000..43eec89 --- /dev/null +++ b/user/pages/01.home/01.fullvideo/text.fr.md @@ -0,0 +1,6 @@ +--- +title: fullvideo +visible: false +--- + +[plugin:youtube](https://www.youtube.com/watch?v=atTcasPy3JY) diff --git a/user/pages/01.home/02._videos/_sovaj-2/text.fr.md b/user/pages/01.home/02._videos/_sovaj-2/text.fr.md new file mode 100644 index 0000000..c8dd384 --- /dev/null +++ b/user/pages/01.home/02._videos/_sovaj-2/text.fr.md @@ -0,0 +1,6 @@ +--- +title: matriz +image_align: left +--- + +[plugin:youtube](https://www.youtube.com/watch?v=atTcasPy3JY) diff --git a/user/pages/01.home/02._videos/_sovaj/text.fr.md b/user/pages/01.home/02._videos/_sovaj/text.fr.md new file mode 100644 index 0000000..f47234a --- /dev/null +++ b/user/pages/01.home/02._videos/_sovaj/text.fr.md @@ -0,0 +1,6 @@ +--- +title: sovaj +image_align: left +--- + +[plugin:youtube](https://www.youtube.com/watch?v=atTcasPy3JY) diff --git a/user/pages/01.home/02._videos/text.fr.md b/user/pages/01.home/02._videos/text.fr.md new file mode 100644 index 0000000..5da9567 --- /dev/null +++ b/user/pages/01.home/02._videos/text.fr.md @@ -0,0 +1,8 @@ +--- +title: Vidéos +image_align: left +summary: + enabled: true + format: 'short | long' + size: int +--- diff --git a/user/pages/01.home/03._photographies/text.fr.md b/user/pages/01.home/03._photographies/text.fr.md new file mode 100644 index 0000000..6340d8d --- /dev/null +++ b/user/pages/01.home/03._photographies/text.fr.md @@ -0,0 +1,6 @@ +--- +title: Photographies +image_align: left +--- + +Page Photographies diff --git a/user/pages/01.home/04._biographie/edlp-color.png b/user/pages/01.home/04._biographie/edlp-color.png new file mode 100644 index 0000000..ad7be8b Binary files /dev/null and b/user/pages/01.home/04._biographie/edlp-color.png differ diff --git a/user/pages/01.home/04._biographie/text.fr.md b/user/pages/01.home/04._biographie/text.fr.md new file mode 100644 index 0000000..6967293 --- /dev/null +++ b/user/pages/01.home/04._biographie/text.fr.md @@ -0,0 +1,21 @@ +--- +title: Biographie +media_order: edlp-color.png +image_align: left +--- + +Artiste franco-algéro-brésilienne, Anissá Bensalah chante sur scène depuis l'âge de 15 ans : Salle Gaveau, New Morning, festival Solidays, Institut du Monde Arabe, Théâtre des Gémeaux, Centre Culturel Goulbenkian, Maroquinerie, Sunside-Sunset, Petit Bain, Studio de l'Ermitage, Salle Gustave Eiffel (Paris)... Dock 40 (Lyon), Théâtre de la Mer (Sainte Maxime), festival Jazz au Château (Cagnes sur Mer), festival La Rue des Artistes (Saint Chamont),... Sesc, Itamaratí, Palacio de Cristal, Candelária (Rio de Janeiro), Salle Villa Lobos du Teatro Nacional (Brasilia), Salle Ibn Zeydoun (Alger) ... + +Née en Haïti, Anissá Bensalah part à 5 ans, avec ses parents, vivre à Dakar (Sénégal) où elle s'imprègne de la culture locale. À ses 11 ans, elle s'installe à Beyrouth (Liban) où elle découvre les dégâts de la guerre. Période particulièrement marquante. + +Ce n'est qu'à ses 14 ans qu'elle arrive à Paris. Parallèlement à un cursus de musicologie à l'Université Paris VIII, elle y suit dix ans de formation en École Nationale de Musique auprès d'Odile Pietti, Florence Katz et Mercedes Proteau (classique), ainsi que Laurent Coq, Mônica Passos, Diana Goulart et Amélia Rabello (jazz et musiques brésiliennes). + +Elle a travaillé et collaboré avec des noms de la musique brésilienne : João Donato qui lui a confié une composition inédite Enquanto a gente namora, Nelson Faria, Rodrigo Zaidan, Josias Pedrosa et Lucio Vieira avec qui elle a enregistré un EP 4 titres auto-produit Eu sei e você sabe. + +En octobre 2013, elle sort son premier album Matriz, sous le label Ovastand et distribué par Musicast. Elle y est entourée de musiciens variées comme Automne Lajeat (violoncelle), Frédéric Antetomaso (guitare), Julien Matrot (trompette), Guillaume Duvignau (contrebasse) et Nils Wekstein (batterie-percussions). + +En avril 2014, elle fait une rencontre professionnelle marquante : Rémy Kolpa Kopoul (surnommé RKK), journaliste-"connexionneur" incontrounable dans le milieu musical en France. Il lui accordera sa confiance et son écoute, et lui ouvrira plusieurs portes. + +Fin 2015, elle enregistre un EP 4 titres, intitulé Nejma, avec Amina Mezaache (flûtes), Frédéric Antetomaso (guitares), Ricardo Feijão (basse acoustique), Nils Wekstein et Jonathan Edo (batterie-percussions). + +Actuellement, Anissá Bensalah présente sur scène son deuxième album Sovaj (signé chez Ovastand), en France et à l'étranger. Elle est accompagnée par Tim Campanella (batterie), Philippe Monge (synthé basse et claviers) et Frédéric Antetomaso (guitares). \ No newline at end of file diff --git a/user/pages/01.home/05._presse/150px-montecarlodoualiya_2013.svg_0_0.png b/user/pages/01.home/05._presse/150px-montecarlodoualiya_2013.svg_0_0.png new file mode 100644 index 0000000..cfd583f Binary files /dev/null and b/user/pages/01.home/05._presse/150px-montecarlodoualiya_2013.svg_0_0.png differ diff --git a/user/pages/01.home/05._presse/fr2.jpg b/user/pages/01.home/05._presse/fr2.jpg new file mode 100644 index 0000000..aba3907 Binary files /dev/null and b/user/pages/01.home/05._presse/fr2.jpg differ diff --git a/user/pages/01.home/05._presse/frinter.jpg b/user/pages/01.home/05._presse/frinter.jpg new file mode 100644 index 0000000..fe2587d Binary files /dev/null and b/user/pages/01.home/05._presse/frinter.jpg differ diff --git a/user/pages/01.home/05._presse/jazzradio-logo-copie_0_0_0.jpg b/user/pages/01.home/05._presse/jazzradio-logo-copie_0_0_0.jpg new file mode 100644 index 0000000..a319d1d Binary files /dev/null and b/user/pages/01.home/05._presse/jazzradio-logo-copie_0_0_0.jpg differ diff --git a/user/pages/01.home/05._presse/logo-lesinrocks_0.jpg b/user/pages/01.home/05._presse/logo-lesinrocks_0.jpg new file mode 100644 index 0000000..7c17369 Binary files /dev/null and b/user/pages/01.home/05._presse/logo-lesinrocks_0.jpg differ diff --git a/user/pages/01.home/05._presse/logo_france_info_1_0.png b/user/pages/01.home/05._presse/logo_france_info_1_0.png new file mode 100644 index 0000000..956e7ea Binary files /dev/null and b/user/pages/01.home/05._presse/logo_france_info_1_0.png differ diff --git a/user/pages/01.home/05._presse/photohome.JPG b/user/pages/01.home/05._presse/photohome.JPG new file mode 100644 index 0000000..c18f34a Binary files /dev/null and b/user/pages/01.home/05._presse/photohome.JPG differ diff --git a/user/pages/01.home/05._presse/text.fr.md b/user/pages/01.home/05._presse/text.fr.md new file mode 100644 index 0000000..f66ff8f --- /dev/null +++ b/user/pages/01.home/05._presse/text.fr.md @@ -0,0 +1,20 @@ +--- +title: Presse +media_order: 'jazzradio-logo-copie_0_0_0.jpg,150px-montecarlodoualiya_2013.svg_0_0.png,fr2.jpg,frinter.jpg,logo_france_info_1_0.png,logo-lesinrocks_0.jpg,photohome.JPG' +image_align: left +--- + +![](photohome.JPG) + +![](jazzradio-logo-copie_0_0_0.jpg) +live + +![](150px-montecarlodoualiya_2013.svg_0_0.png) + +![](fr2.jpg) + +![](frinter.jpg) + +![](logo_france_info_1_0.png) + +![](logo-lesinrocks_0.jpg) \ No newline at end of file diff --git a/user/pages/01.home/06._prochaines-dates/text.fr.md b/user/pages/01.home/06._prochaines-dates/text.fr.md new file mode 100644 index 0000000..65f54d5 --- /dev/null +++ b/user/pages/01.home/06._prochaines-dates/text.fr.md @@ -0,0 +1,17 @@ +--- +title: 'Prochaines dates' +image_align: left +--- + +### Date de l'album sovaj + +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) +date(j/m/a) - nom de la salle - ville/pays - [billets](billets) \ No newline at end of file diff --git a/user/pages/01.home/07._contact/text.fr.md b/user/pages/01.home/07._contact/text.fr.md new file mode 100644 index 0000000..7796542 --- /dev/null +++ b/user/pages/01.home/07._contact/text.fr.md @@ -0,0 +1,6 @@ +--- +title: Contact +image_align: left +--- + +Page Contact diff --git a/user/pages/01.home/modular.fr.md b/user/pages/01.home/modular.fr.md new file mode 100644 index 0000000..810af40 --- /dev/null +++ b/user/pages/01.home/modular.fr.md @@ -0,0 +1,17 @@ +--- +title: Home +media_order: photohome.JPG +content: + items: + - '@self.modular' + +body_classes: 'title-center title-h1h2' +--- + +![](photohome.JPG) + +#sovaj + +album sovaj est disponible sur : +[itune](itune) - [fnac](fnac) - [amazon](fnac) +[deezer](fnac) - [spotify](fnac) diff --git a/user/pages/01.home/photohome.JPG b/user/pages/01.home/photohome.JPG new file mode 100644 index 0000000..c18f34a Binary files /dev/null and b/user/pages/01.home/photohome.JPG differ diff --git a/user/plugins/.gitkeep b/user/plugins/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/user/plugins/admin/.gitattributes b/user/plugins/admin/.gitattributes new file mode 100644 index 0000000..e3cf70c --- /dev/null +++ b/user/plugins/admin/.gitattributes @@ -0,0 +1,8 @@ +# Linguist Normalizer +*.yaml linguistic-language=PHP +*.twig linguistic-language=PHP +**/gulpfile.js linguist-vendored +**/webpack.conf.js linguist-vendored +**/js/*.js linguist-vendored +**/js/*.json linguist-vendored +**/css-compiled/*.css linguist-vendored diff --git a/user/plugins/admin/CHANGELOG.md b/user/plugins/admin/CHANGELOG.md new file mode 100644 index 0000000..c9a29fe --- /dev/null +++ b/user/plugins/admin/CHANGELOG.md @@ -0,0 +1,1376 @@ +# v1.8.1 +## 05/15/2018 + +1. [](#improved) + * use SHA1 hashing of IP addressed to support GDPR rules [#1436](https://github.com/getgrav/grav-plugin-admin/pull/1436) +1. [](#bugfix) + * Fixed 2FA form showing up even if user has not turned on the feature [#1442](https://github.com/getgrav/grav-plugin-admin/issues/1442) + * Fixed previews of images in Pagemedia field not properly URI encoded [#1438](https://github.com/getgrav/grav-plugin-admin/issues/1438) + +# v1.8.0 +## 05/11/2018 + +1. [](#new) + * Moved 2FA authentication to login plugin + * Admin login now uses login plugin events + * Added new decoupled `pagemedia` field that is no longer tied to just pages + * Updated plugin dependencies (Grav >= 1.4.4, Form >=2.14.0, Login >=2.7.0, Email >=2.7.0) +1. [](#improved) + * Added support for JavaScript `bottom` block [#1425](https://github.com/getgrav/grav-plugin-admin/pull/1425) + * Added better typography styling for blockquote and markdown in `display` field + * Vendor updates +1. [](#bugfix) + * Added missing MarkdownExtra strings [#1385](https://github.com/getgrav/grav-plugin-admin/pull/1385) + * Updated `blueprints.yaml` with missing `step` attribute [#1415](https://github.com/getgrav/grav-plugin-admin/pull/1415) + * Fixed preview target setting [#1430](https://github.com/getgrav/grav-plugin-admin/pull/1430) + * Added new modular string [#1433](https://github.com/getgrav/grav-plugin-admin/pull/1433) + * Fixed Firefox issue with the Regenerate button for 2FA. Forcing the page to reload + * Fixed jumpiness behavior for Regenerate button when on active state. + * Prevent the prompt for unsaved state when Regenerating a 2FA code and trying to reload/leave the page. + +# v1.7.4 +## 04/02/2018 + +1. [](#bugfix) + * Fixed a bug for page copy caused by last release [#1409](https://github.com/getgrav/grav-plugin-admin/pull/1409) + * Fixed collapsible `list` option [#1410](https://github.com/getgrav/grav-plugin-admin/pull/1410) + * Fixed a minor typo in a label [#1397](https://github.com/getgrav/grav-plugin-admin/pull/1397) + +# v1.7.3 +## 04/01/2018 + +1. [](#new) + * Implemented Resize Media and Resolution ('resizeWidth', 'resizeHeight', 'resizeQuality', 'resolution') + * Updated Dropzone to latest +1. [](#bugfix) + * Implemented workaround for required text fields [#1390](https://github.com/getgrav/grav-plugin-admin/issues/1390) + * Fixed highlight color in Firefox [getgrav/grav#1949](https://github.com/getgrav/grav/issues/1949) + * Fix for bad redirect on saving simplesearch (possibly others) + +# v1.7.2 +## 03/21/2018 + +1. [](#improved) + * Table CSS improvements for use in 3rd party plugins + * Translatable `add_modals` button labels [#1388](https://github.com/getgrav/grav-plugin-admin/issues/1388) + * Check for `SHIFT` key on editor save shortcut [#1383](https://github.com/getgrav/grav-plugin-admin/issues/1383) + * Fixed User permissions responsive UI [#1379](https://github.com/getgrav/grav-plugin-admin/issues/1379) + * Optimization to stop admin for looking for pages in disabled plugins + * Added configuration option to choose if you want to use new 'inline' preview or `new tab' +1. [](#bugfix) + * Fix redirect bug when changing admin route to `admin-*` + * Changed Twig `|count` to `|length` filter [#1391](https://github.com/getgrav/grav-plugin-admin/issues/1391) + * Fix for page preview when `HTTP_REFERRER` is not set [grav#1930](https://github.com/getgrav/grav/issues/1930) + +# v1.7.1 +## 03/11/2018 + +1. [](#new) + * New built-in page preview system +1. [](#improved) + * Added `CTRL+K` / `CMD+K` shortcuts for editor links [#1279](https://github.com/getgrav/grav-plugin-admin/issues/1279) +1. [](#bugfix) + * Automatically redirect to new `admin_route` after changing it [#1371](https://github.com/getgrav/grav-plugin-admin/issues/1371) + * Remove bad-shadows on alerts + * Fixed notifications titles not html escaped [#1272](https://github.com/getgrav/grav-plugin-admin/issues/1272) + * Fixed extra horizontal scrollbar with `Editor` field + * Fixed `mediapicker` field in lists [#1369](https://github.com/getgrav/grav-plugin-admin/issues/1369) + +# v1.7.0 +## 03/09/2018 + +1. [](#new) + * Added styling and lang for **Route Overrides** in the default page blueprint + * Added clear cache permanently to quick-tray [#1353](https://github.com/getgrav/grav-plugin-admin/issues/1353) +1. [](#improved) + * Added option to toggle between `line-awesome` and `font-awesome` icon sets [#1334](https://github.com/getgrav/grav-plugin-admin/issues/1334) + * Added preview from page list view [#1250](https://github.com/getgrav/grav-plugin-admin/pull/1250) + * Added `Add` plugins button to plugins details page [#1352](https://github.com/getgrav/grav-plugin-admin/pull/1352) + * Added support for `default` and `options` fields in taxonomy field [#1364](https://github.com/getgrav/grav-plugin-admin/issues/1364) + * Added support to limit parent field levels [#1298](https://github.com/getgrav/grav-plugin-admin/issues/1298) +1. [](#bugfix) + * Fixed issue with custom logo text overlapping the sidebar toggle [#1334](https://github.com/getgrav/grav-plugin-admin/issues/1334) + * Fixed issues with minimum PHP versions in resource upgrades + * Fixed issue with default lang translation in admin [#1361](https://github.com/getgrav/grav-plugin-admin/issues/1361) + * Typos in `Tools` -> `Direct Install` page [#1345](https://github.com/getgrav/grav-plugin-admin/issues/1345) + * Fixed bug with frontmatter being killed when in `Expert Mode` [#1354](https://github.com/getgrav/grav-plugin-admin/issues/1354) + +# v1.7.0-rc.3 +## 02/15/2018 + +1. [](#improved) + * Tab optimization with fixes for 'onpage' tabs + * Stopped Chrome from auto-completing admin user profile form [grav#1847](https://github.com/getgrav/grav/issues/1847) + * Added a fixed `ga-theme-17x` body class to help styling compatibility + * Outputs an iterable field as a string if `yaml: true` or `validate: type: yaml` set in blueprint +1. [](#bugfix) + * Rolled back JS to known working versions [#1323](https://github.com/getgrav/grav-plugin-admin/issues/1323) + * Fixed missing translation in order field [#1324](https://github.com/getgrav/grav-plugin-admin/issues/1324) + * Fixed UI issue with last drop-down in button group [1325](https://github.com/getgrav/grav-plugin-admin/issues/1325) + * Fixed fieldset field outdated rendering [#1313](https://github.com/getgrav/grav-plugin-admin/issues/1313) + +# v1.7.0-rc.2 +## 01/24/2018 + +1. [](#new) + * Moved to LineAwesome icons rather than FontAwesome (still compatible w/FA 4.7.0) +1. [](#improved) + * Simplified open/close nav button + * Tidied Tools panel and added translations + * Tooltip and new icon for site preview + * Updated JS library dependencies + * Changed CodeMirror editor to use sans-serif font for readability +1. [](#bugfix) + * Fixed z-index issue in fullscreen mode [#1317](https://github.com/getgrav/grav-plugin-admin/issues/1317) + +# v1.7.0-rc.1 +## 01/22/2018 + +1. [](#new) + * Added support for markdown in all form fields for `label`, `help`, and `description` when `markdown: true` is set on field + * Changed "made by" to Trilby Media from RocketTheme +1. [](#improved) + * Lightened tabs in new theme + * Sort languages by key [#1303](https://github.com/getgrav/grav-plugin-admin/issues/1303) + * Add limit to Parent Levels [#1298](https://github.com/getgrav/grav-plugin-admin/pull/1298) +1. [](#bugfix) + * Fixed alignment issue with language drop-down + * Fixed a z-index issue with fullscreen editor [#1302](https://github.com/getgrav/grav-plugin-admin/issues/1302) + * Fixed missing background on register [#1307](https://github.com/getgrav/grav-plugin-admin/issues/1307) + * Fixed some style issues with field descriptions + * Fixed an issue with `File` field losing download size setting + * Fixed distorted thumbnails in `File` field by using `object-fit: cover` + +# v1.7.0-beta.1 +## 12/29/2017 + +1. [](#new) + * New lighter-and-tighter admin theme developed +1. [](#improved) + * Added simple value support for list field type + * Added checks to automatically hide collapse buttons when there's only single value in list type + +# v1.6.7 +## 12/05/2017 + +1. [](#new) + * Logout of admin goes straight to login form with a message (that then fades out) + * Added `sl`, `id`, `he`, `eu`, `et` languages +1. [](#improved) + * Added code to use new `GPM::loadRemoteGrav` if it exists in Gav [grav#1746](https://github.com/getgrav/grav/pull/1746) + * Add vertical style for order field [#1253](https://github.com/getgrav/grav-plugin-admin/pull/1253) + * Added classes to pagemedia field [#1274](https://github.com/getgrav/grav-plugin-admin/issues/1274) + * Fixed selectize field not properly updating value when `option` is provided [#1236](https://github.com/getgrav/grav-plugin-admin/pull/1236) + * Tab layout tweaks + * Updated all language files with latest from [Crowdin](https://crowdin.com/project/grav-admin) +1. [](#bugfix) + * Manual image metadata can now display in pagemedia when auto-generation is disabled [#1275](https://github.com/getgrav/grav-plugin-admin/issues/1275) + * Removed broken `home.hide_in_urls` code in `AdminBaseController::save()` that was throwing move errors + * Security fix to ensure file uploads are not manipulated mid-post - thnx @FLH! + +# v1.6.6 +## 10/27/2017 + +1. [](#new) + * Fixed issue where sortable media in expert mode would reset frontmatter [#1252](https://github.com/getgrav/grav-plugin-admin/issues/1252) + +# v1.6.5 +## 10/26/2017 + +1. [](#new) + * Added ability to **order** page media (requires latest Grav update) + +# v1.6.4 +## 10/11/2017 + +1. [](#improved) + * Use system PHP size for upload limit rather than `system.media.upload_limit` or `file.filesize` plugin options +1. [](#bugfix) + * Fixed Dropzone timeout to address slow internet connections [#1239](https://github.com/getgrav/grav-plugin-admin/pull/1239) + +# v1.6.3 +## 10/02/2017 + +1. [](#bugfix) + * Fixed chart labels not parsing HTML [#1234](https://github.com/getgrav/grav-plugin-admin/issues/1234) + +# v1.6.2 +## 09/29/2017 + +1. [](#improved) + * Removed extraneous files in vendor folder for smaller download package + +# v1.6.1 +## 09/29/2017 + +1. [](#improved) + * Added support for Latin Extended fonts [#1211](https://github.com/getgrav/grav-plugin-admin/pull/1221) + * Added collapsible attribute to lists [#1231](https://github.com/getgrav/grav-plugin-admin/pull/1231) +1. [](#bugfix) + * Fix editor not clickable in list field [#1224](https://github.com/getgrav/grav-plugin-admin/pull/1124) + * Updated Google Font URLs to always connect over HTTPS. [#1106](https://github.com/getgrav/grav-plugin-admin/pull/1106) + * Fixed fieldset field not allowing to properly save when contained within a list [#1225](https://github.com/getgrav/grav-plugin-admin/issues/1225) + * Fixed Video markdown syntax when drag & dropping in the content editor [#1160](https://github.com/getgrav/grav-plugin-admin/issues/1160) + * Fixed headers drop-down in editor to properly align + * Fixed fields not working in Microsoft Edge with Selectize.js [#1222](https://github.com/getgrav/grav-plugin-admin/pull/1222) + * Replaced a left-over "is empty" check [#1232](https://github.com/getgrav/grav-plugin-admin/pull/1232) + * Fixed headers drop-down in editor to align properly + + +# v1.6.0 +## 09/07/2017 + +1. [](#new) + * **Added 2-Factor Authentication support to the admin!** + * **Added rate-limiting for "failed login attempts" and "forgot password"** +1. [](#improved) + * Revamped the toggle switch CSS so it's more flexible and works better [#1198](https://github.com/getgrav/grav-plugin-admin/issues/1198) + * Improved toggle/button alignment on Page edit view +1. [](#bugfix) + * Fixed an issue where icon-picker style was hiding field elements [#1199](https://github.com/getgrav/grav-plugin-admin/issues/1199) + * Fixed https -> http redirect issue [#1195](https://github.com/getgrav/grav-plugin-admin/issues/1195) + * Also check `/.` for home route [#1191](https://github.com/getgrav/grav-plugin-admin/issues/1191) + * Fixed administration being broken in multi-site environments with plugin overrides + * Fixed lang-switcher broken in MS Edge browser [#1213](https://github.com/getgrav/grav-plugin-admin/pull/1213) + * Added custom `form_id` attribute for modal forms [#1216](https://github.com/getgrav/grav-plugin-admin/issues/1216) + * Fixed partially cropped line in Markdown editor for MS Edge/Firefox [#1219](https://github.com/getgrav/grav-plugin-admin/pull/1219) + * Downgraded Babel libraries to v6.x for compatibility with webpack [#1218](https://github.com/getgrav/grav-plugin-admin/pull/1218) + +# v1.5.2 +## 08/16/2017 + +1. [](#new) + * Added a new icon quick-tray in side navigation that plugins can utilize + * Added ability to set and retrieve temporary admin messages +1. [](#improved) + * Allow different field to be used as page label in list of pages [#1122](https://github.com/getgrav/grav-plugin-admin/pull/1122) + * Updated `en` language for `cache-control` + `clear_images_by_default` system settings + * Allow sorting of page based on custom ordering [#1182](https://github.com/getgrav/grav-plugin-admin/pull/1182) + * Search for pages by slug and folder name [#1183](https://github.com/getgrav/grav-plugin-admin/pull/1183) + * Allow all page data to be used during `onAdminCreatePageFrontmatter()` event [#1175](https://github.com/getgrav/grav-plugin-admin/pull/1175) + * Remove single quotes when slugifying title [#1178](https://github.com/getgrav/grav-plugin-admin/pull/1178) +1. [](#bugfix) + * Ignore missing Twig files [#1169](https://github.com/getgrav/grav-plugin-admin/issues/1169) + * If from is already defined, don't override it [#1129](https://github.com/getgrav/grav-plugin-admin/issues/1129) + * Fixed SelectUnique field not working with files with spaces + +# v1.5.1 +## 07/19/2017 + +1. [](#bugfix) + * Fixes issue when saving pages without a `folder` element [#1163](https://github.com/getgrav/grav-plugin-admin/issues/1163) + * Fixed mediapicker field inside lists not properly updating the value on the target input [#1157](https://github.com/getgrav/grav-plugin-admin/issues/1157) + +# v1.5.0 +## 07/16/2017 + +1. [](#new) + * Implemented Offline mode. Notifies in the admin when disconnected. +1. [](#bugfix) + * Fixed fetch issue throwing error when request not completed and while unloading the page [#1301](https://github.com/getgrav/grav-plugin-admin/issues/1301) + * Fixed ordering when > 100 pages [grav#1564](https://github.com/getgrav/grav/pull/1564) + * Fixed Lists issue when reindexing, causing Radio fields to potentially lose their `checked` status ([#1154](https://github.com/getgrav/grav-plugin-admin/issues/1154) | related: [1d55ffc](https://github.com/getgrav/grav-plugin-admin/commit/1d55ffc616125047f245efe9f2180ef2c16b4949)) + +# v1.5.0-rc.4 +## 07/05/2017 + +1. [](#new) + * New `multilevel` field, useful for defining collections definitions, metadata and other complex YAML data [#1135](https://github.com/getgrav/grav-plugin-admin/pull/1135) - (EXPERIMENTAL) + * Fix plugins hooked nav authorize not working with array of permissions [#1148](https://github.com/getgrav/grav-plugin-admin/pull/1148) +1. [](#improved) + * Add badge to plugins hooked into nav [#1147](https://github.com/getgrav/grav-plugin-admin/pull/1147) + * Added `field.outerclasses` to default form field [#1124](https://github.com/getgrav/grav-plugin-admin/pull/1124) + * Reverted back to textarea/YAML for `media.yaml` image options + * Fixed color of textarea fields in admin +1. [](#bugfix) + * Fix for bad referenced to `shouldLoadAdditionalFilesInBackground()` [#1145](https://github.com/getgrav/grav-plugin-admin/pull/1145) + * Expose Page Media instance to Grav Admin JS API + * Fixed mediapicker issue where newly added list items would not work + * Fixed issue with min/max setting of list collections. Removing a list item would not refresh properly the count + * If folder is empty/not sent, fallback to page slug [#1146](https://github.com/getgrav/grav-plugin-admin/issues/1146) + * Escape the URI basename before using it in Twig + * Ignore missing Twig file in the Tools page + +# v1.5.0-rc.3 +## 06/22/2017 + +1. [](#new) + * New `Admin::getPageMedia()` static method that can be used in blueprints + * Added a new `mediapicker` form field which allows to select a media from any page [#1125](https://github.com/getgrav/grav-plugin-admin/pull/1125) + * Added info metadata button for images to view EXIF and other useful details about an image +1. [](#improved) + * Pass original image filename via the `AdminController::taskListedia()` task + * Various form styling improvements + * Provided an option to control how parent select field displays +1. [](#bugfix) + * Fix referencing DI element when not initialized [#1141](https://github.com/getgrav/grav-plugin-admin/pull/1141) + +# v1.5.0-rc.2 +## 05/22/2017 + +1. [](#improved) + * Remove save button and save location notification on Config Info tab [#1116](https://github.com/getgrav/grav-plugin-admin/pull/1116) + * Allow taxonomy field to just list one or more specific taxonomies if the `taxonomies` field is filled in the blueprint + * `File` field now renders thumbnail previews of the selected value on load + * Use new unified `Utils::getPagePathFromToken()` method rather +1. [](#bugfix) + * Fix for undefined `include_metadata` error + + +# v1.5.0-rc.1 +## 05/16/2017 + +1. [](#new) + * Add support for a single array field in forms + * Added Prev/Next support on page editing view [#1112](https://github.com/getgrav/grav-plugin-admin/pull/1112) +1. [](#improved) + * Improved full-screen editor for better browser compatibility [#1093](https://github.com/getgrav/grav-plugin-admin/pull/1093) + * Added ability to choose how you want the preview button to open [#1096](https://github.com/getgrav/grav-plugin-admin/pull/1096) + * `base.html.twig` now extends a `base-root.html.twig` file + * Add month+date indication to the stats graph to avoid confusion when there are days without visits + * Added `min` and `max` options for `list` form field [#1113](https://github.com/getgrav/grav-plugin-admin/pull/1113) + * Remove page metadata file on deletion of media + * Improved layout on pages list for pages with long titles [#1102](https://github.com/getgrav/grav-plugin-admin/pull/1102) + * Added option to make custom "Add page" dropdown entries [#1104](https://github.com/getgrav/grav-plugin-admin/pull/1104) +1. [](#bugfix) + * Fixed issue with tab widths on Pages overlapping non-english toggle switch [#1089](https://github.com/getgrav/grav-plugin-admin/issues/1089) + * Added `vendor` to ignores for direct install of Grav + * Translated `field.default` for `editor` form field + * Fixed an quote error in `en.yaml` + * Resolved z-index issues with mobile nav and pages form elements + * Fixed issue with file picker where the selected file preview would not show + * Refresh page media on media upload + * Default to config file slug if translation is missing, otherwise use translation also in the tab title, not just in the page heading [#1039](https://github.com/getgrav/grav-plugin-admin/issues/1039) + * Fix language toggle button in admin top bar visible also in fullscreen mode [#1110](https://github.com/getgrav/grav-plugin-admin/issues/1110) + * Fix for editor padding [#1111](https://github.com/getgrav/grav-plugin-admin/issues/1111) + * Fix tabs inside blueprint overlapping above content [#1115](https://github.com/getgrav/grav-plugin-admin/pull/1115) + +# v1.4.2 +## 04/24/2017 + +1. [](#new) + * Added a new `Content Padding` option to tighten up UI padding space (default `true`) +1. [](#bugfix) + * Added back `Admin::initTheme()` relying on Grav fix [#1069](https://github.com/getgrav/grav-plugin-admin/pull/1069) as it conflicts ith Gantry5 + * Fix for missing scrollbar when in full-size editor for Firefox [#1077](https://github.com/getgrav/grav-plugin-admin/issues/1077) + * Fix for overlay of Add-Page button in full-size editor [#1077](https://github.com/getgrav/grav-plugin-admin/issues/1077) + * Better fix for session-based parent overriding root page parents [#1078](https://github.com/getgrav/grav-plugin-admin/issues/1078) + * Allow support for `Pages::getList()` with `show_modular` option [#1080](https://github.com/getgrav/grav-plugin-admin/issues/1080) + * Added `[tmp,user]` ignores for direct install of Grav [grav#1447](https://github.com/getgrav/grav/issues/1447) + +# v1.4.1 +## 04/19/2017 + +1. [](#bugfix) + * Reverted [#1069](https://github.com/getgrav/grav-plugin-admin/pull/1069) as it conflicts ith Gantry5 + +# v1.4.0 +## 04/19/2017 + +1. [](#new) + * Added ability to add new pages/folders while editing existing page +1. [](#improved) + * Initialize theme in Admin Plugin [#1069](https://github.com/getgrav/grav-plugin-admin/pull/1069) + * Use new system configuration entries for username and password format + * Reworked Page parent field to use `Pages::getList()` rather than logic in Twig field itself + * More robust styling of admin themes page [#1067](https://github.com/getgrav/grav-plugin-admin/pull/1067) + * Fix fullscreen editor height [#1065](https://github.com/getgrav/grav-plugin-admin/pull/1065) + * Fix small UI issue in the editor with `codemirror.lineNumbers` && `codemirror.styleActiveLine` enabled + * Fix UI performance issue in the dashboard [#1064](https://github.com/getgrav/grav-plugin-admin/issues/1064) +1. [](#bugfix) + * Fixed issue with parent not working with custom slug [#1068](https://github.com/getgrav/grav-plugin-admin/issues/1068) + * Fixed issue with new page modal not remembering last choice [#1072](https://github.com/getgrav/grav-plugin-admin/issues/1072) + +# v1.3.3 +## 04/12/2017 + +1. [](#bugfix) + * Fix for regression introduced in the automatic page template switch when changing page parent [#1059](https://github.com/getgrav/grav-plugin-admin/issues/1059) [grav#1403](https://github.com/getgrav/grav/issues/1403) [#1062](https://github.com/getgrav/grav-plugin-admin/issues/1062) + * Fix issue with editor field in lists [#1037](https://github.com/getgrav/grav-plugin-admin/issues/1037) + +# v1.3.2 +## 04/10/2017 + +1. [](#improved) + * Added new 'parents' field and switched Page blueprints to use this +1. [](#bugfix) + * Fix for regression in h3 style in the Spacer field [#267](https://github.com/getgrav/grav-plugin-admin/issues/267) + * Fix missing preview in page media for SVG images [#1051](https://github.com/getgrav/grav-plugin-admin/issues/1051) + * Fix missing check when reordering [#1053](https://github.com/getgrav/grav-plugin-admin/issues/1053) + * Fix for editors not getting refreshed when changing tab [#1052](https://github.com/getgrav/grav-plugin-admin/issues/1052) + * Fix for mobile tabs in page editing [#1057](https://github.com/getgrav/grav-plugin-admin/issues/1057) + +# v1.3.1 +## 03/31/2017 + +1. [](#bugfix) + * Fix for `Undefined index: file_path` error with Direct Install [#1043](https://github.com/getgrav/grav-plugin-admin/issues/1043) + +# v1.3.0 +## 03/31/2017 + +1. [](#new) + * User uploadable avatar (still falls back to Gravatar if not provided) +1. [](#improved) + * Improved tabs CSS to handle long titles [#1036](https://github.com/getgrav/grav-plugin-admin/issues/1036) + * Fixed `step` in range field [Form#136](https://github.com/getgrav/grav-plugin-form/issues/136) +1. [](#bugfix) + * Fixed issue with exception thrown when `copying` and `moving` a page [#1042](https://github.com/getgrav/grav-plugin-admin/issues/1042) + * Automatically calculate the *next* numeric folder prefix [Core#1386](https://github.com/getgrav/grav/issues/1386) + +# v1.3.0-rc.3 +## 03/22/2017 + +1. [](#new) + * All new `Page Ordering` implementation. Completely revamped and will only reorder with folder-prefix enabled. You can now reorder all siblings at the same time. + * Added a new `Advanced - Override` to allow option to display pages by folder name (default) or Collection definition + * Improved `range` form field with touch and counter support [#1016](https://github.com/getgrav/grav-plugin-admin/pull/1016) +1. [](#bugfix) + * Cleanup package files via GPM install to make them more windows-friendly [#1361](https://github.com/getgrav/grav/pull/1361) + +# v1.3.0-rc.2 +## 03/17/2017 + +1. [](#improved) + * Do not attempt to fetch any notification if settings are disabled [#942](https://github.com/getgrav/grav-plugin-admin/issues/942) + +# v1.3.0-rc.1 +## 03/13/2017 + +1. [](#new) + * New flex-based/js Tabs system for better flexibility and improved UX. + * Added new **toolbox** with `Direct-Install` option via ZIP or URL. + * Added an option to reinstall a plugin/theme already installed [#984](https://github.com/getgrav/grav-plugin-admin/issues/984) + * Added a new **range field** [#995](https://github.com/getgrav/grav-plugin-admin/issues/995) + * When creating a new page, automatically select the Page Template based on Parent Page Child Type [#1008](https://github.com/getgrav/grav-plugin-admin/issues/1008) +1. [](#improved) + * Page Media field now is available when folder is created, not just markdown file [#1000](https://github.com/getgrav/grav-plugin-admin/issues/1000) + * Separated user details and avatar in separate twig to allow more granular overriding in plugins [#989](https://github.com/getgrav/grav-plugin-admin/issues/989) + * Nicer layout of themes list on wider screen + * Editor full-screen option displays title/save options [#948](https://github.com/getgrav/grav-plugin-admin/issues/948) + * Use native OS highlight colors for the editor [#977](https://github.com/getgrav/grav-plugin-admin/issues/977) + * Force admin pages to set `Page::expires(0)` so it's not cached [#1009](https://github.com/getgrav/grav-plugin-admin/issues/1009) + * Added support for up to 15 tabs (was 10) [#954](https://github.com/getgrav/grav-plugin-admin/issues/954) + * Only reorder pages in the admin if collection uses `@self` and `order.by` + * Improved configuration tab sizes when you have lots of tabs + * Modified default media select size from 150px x 100px to 200px x 150px +1. [](#bugfix) + * Fixed rendering issue with Chrome and sortables collections [#1002](https://github.com/getgrav/grav-plugin-admin/issues/1002) + * Fixed issue with removal of file that has been just uploaded and stored in the session + + +# v1.2.14 +## 02/17/2017 + +1. [](#bugfix) + * Fixed bad bug with `GPM::install()` from a change in Admin v1.2.13 + +# v1.2.13 +## 02/17/2017 + +1. [](#bugfix) + * Fix issue with validating page when switching language [#963](https://github.com/getgrav/grav-plugin-admin/issues/963) + * Fix issue with quotes in Admin strings used in JS [#965](https://github.com/getgrav/grav-plugin-admin/issues/965) + * Refactored `AdminController::taskGetUpdates` to use standard task/response [#980](https://github.com/getgrav/grav-plugin-admin/issues/980) + * Sync Admin pages blueprints with core [core#212d35221a9bbcc242508ba49a551b3f6e62af8e](https://github.com/getgrav/grav/commit/212d35221a9bbcc242508ba49a551b3f6e62af8e) + +# v1.2.12 +## 02/12/2017 + +1. [](#bugfix) + * Rebuilt the JS bundle to address various JS-related issues that cropped up in `v1.2.11` + * Fixed Firefox Network Error issue when updating multiple plugins/themes at concurrently [#1301](https://github.com/getgrav/grav/issues/1301) + +# v1.2.11 +## 02/10/2017 + +1. [](#new) + * Added lang strings for `CLI_COMPATIBILITY` which is new in Grav v1.1.16 +1. [](#improved) + * Allow plugin to set custom 'authorize' and 'location' in `onAdminMenu()` event + * Updated all language files with latest from [Crowdin](https://crowdin.com/project/grav-admin) +1. [](#bugfix) + * Fixed issue `admin.super` or `admin.users` users changing the account when saving another user [#713](https://github.com/getgrav/grav-plugin-admin/issues/713) + * Fix issue where non `admin.super`/`admin.users` users could see other users profiles [#713](https://github.com/getgrav/grav-plugin-admin/issues/713) + * Fix removing responsive image from page media [#111](https://github.com/getgrav/grav-plugin-admin/issues/111) [#952](https://github.com/getgrav/grav-plugin-admin/issues/952) + * Use @2x & @3x fallback images in the filepicker. [#952](https://github.com/getgrav/grav-plugin-admin/issues/952) + +# v1.2.10 +## 1/30/2017 + +1. [](#improved) + * It is now possible to manually specify a format for the `datetime` field [#1261](https://github.com/getgrav/grav/issues/1261) + * Allow to see plugins and themes list without internet connection. Also add a more helpful message in the "add" view [grav#1008](https://github.com/getgrav/grav/issues/1008) +1. [](#bugfix) + * Fixed issue with downloaded package when installing a testing release + * Allow non admin.super users to change their account information. Allow `admin.super` and `admin.users` to change other users information. [#943](https://github.com/getgrav/grav/issues/943) + * Handle removing a media file also if it's not a json request. Was not working after https://github.com/getgrav/grav-plugin-admin/commit/6b343365996ce838759d80fa3917d4d994f1aeb4 + +# v1.2.9 +## 01/18/2017 + +1. [](#improved) + * Added lang strings for `ALLOW_WEBSERVER_GZIP` in System configuration + +# v1.2.8 +## 01/17/2017 + +1. [](#improved) + * Allow the ability to clear the cache if `admin.maintenance`, as stated in the docs [#908](https://github.com/getgrav/grav-plugin-admin/issues/908) + * Added lang strings for `DEFAULT_LANG` in Site configuration + * Added lang strings for `NEVER_CACHE_TWIG` in System and Page configuration +1. [](#bugfix) + * Fixed saving the configuration if not `admin.super` + * Show the clear cache buttons if the user has `admin.cache` permissions [#908](https://github.com/getgrav/grav-plugin-admin/issues/908#issuecomment-270748616) + * Fix colorpicker validation when transparency is set to 1.00 [#921](https://github.com/getgrav/grav-plugin-admin/issues/921) + * Fix html markup in section twig [#922](https://github.com/getgrav/grav-plugin-admin/pull/922) + * Fix bug in deleting a file uploaded with the `file` field [#920](github.com/getgrav/grav-plugin-admin/issues/920) + * Fix for plugin throwing event-based errors when plugin is removed and no longer available to process said event + +# v1.2.7 +## 12/22/2016 + +1. [](#improved) + * Fixed an issue with non `.html` extensions not setting application type properly when fallback template not found. +1. [](#bugfix) + * Fix plugins and themes json calls after the introduction of [HTML fallback for templates not found](https://github.com/getgrav/grav/commit/364209a27da0f5dfba5fde9c4b07b6d5844cda47) + + +# v1.2.6 +## 12/21/2016 + +1. [](#improved) + * Added a delay before reloading the page when a plugin or theme get installed + * Fix prompting to remove Grav itself when removing a package that requires a specific Grav version + * Remove cli-server exception since we now have compatibility with a custom router in Grav [#1219](https://github.com/getgrav/grav/pull/1219) +1. [](#bugfix) + * Fix issue with array field and `value_only: true` + +# v1.2.5 +## 12/13/2016 + +1. [](#new) + * RC released as stable +1. [](#bugfix) + * YAML syntax fixes + +# v1.2.5-rc.4 +## 12/07/2016 + +1. [](#new) + * Added a new `permissions` form field, used in the user profile to simplify editing permissions + * Added several new `onAdminAfter...()` events to allow for more 3rd party plugin interaction +1. [](#bugfix) + * Updated admin-user-details to allow longer user names in the sidebar [#879](https://github.com/getgrav/grav-plugin-admin/issues/879) + * Redirect to a 404 page when accessing nonexistent plugins and themes [#880](https://github.com/getgrav/grav-plugin-admin/issues/880) + +# v1.2.5-rc.3 +## 11/26/2016 + +1. [](#bugfix) + * Update class namespace for Admin class [#874](https://github.com/getgrav/grav-plugin-admin/issues/874) + * Fix updating/installing packages from admin + +# v1.2.5-rc.2 +## 11/19/2016 + +1. [](#bugfix) + * Make default value work for filepicker [#859](https://github.com/getgrav/grav-plugin-admin/issues/859) + +# v1.2.5-rc.1 +## 11/09/2016 + +1. [](#new) + * Updated to FontAwesome 4.7.0 with [Grav icon](http://fontawesome.io/icon/grav/) +1. [](#improved) + * Always delete image alternatives in AdminController#taskDelmedia [#814](https://github.com/getgrav/grav-plugin-admin/issues/814) + * Use Media class to retrieve files in AdminController#taskGetFilesInFolder [#842](https://github.com/getgrav/grav-plugin-admin/issues/842) + * Increased specificity for Colorpicker field to prevent 3rd party conflicts +1. [](#bugfix) + * Editor link button doesn't prefix links with `http://` anymore [#813](https://github.com/getgrav/grav-plugin-admin/issues/813) + * Dashboard Charts now always refresh no matter what [#753](https://github.com/getgrav/grav-plugin-admin/issues/753) + * Use rawRoute for parent too when saving [#843](https://github.com/getgrav/grav-plugin-admin/issues/843) + * Avoid different output when users exist or not in password recovery [#849](https://github.com/getgrav/grav/issues/849) + * Fix login to admin with permission inherited from group [#857](https://github.com/getgrav/grav-plugin-admin/issues/857) + + +# v1.2.4 +## 10/22/2016 + +1. [](#bugfix) + * Fix for accented media files [#833](https://github.com/getgrav/grav-plugin-admin/issues/833) + * Fix for `CTRL + s` not saving in editor [#832](https://github.com/getgrav/grav-plugin-admin/pull/832) + * Fix for missing REDIS translations in admin [#1123](https://github.com/getgrav/grav/issues/1123) + +# v1.2.3 +## 10/19/2016 + +1. [](#new) + * Added new `onAdminCreatePageFrontmatter()` event to support plugins such as `auto-date` by allowing frontmatter to be modified by plugins. + * Added a new independent `cache_enabled` option for admin plugin (default is `false`). Should fix various sync issues. + * Add an `onAdminData` event to allow plugins to add additional blueprints data +1. [](#improved) + * Handle errors when a resource fails to install + * Page media and File field images thumbnail are now properly proportionate and 150x100 + * Added the Codeception testing suite with an initial test +1. [](#bugfix) + * Fix [#1034](https://github.com/getgrav/grav/issues/1034) redirect of page creation procedure when system.home.hide_in_urls is enabled + * Media (Page): Do not extend parent metehod for sending files since Safari and IE API for FormData don’t implement `delete` ([#772](https://github.com/getgrav/grav-plugin-admin/issues/772)) + * Clean up POST keys containing square brackets, allows for regex ranges in routes ([#776](https://github.com/getgrav/grav-plugin-admin/issues/776)) + * Fix [#773](https://github.com/getgrav/grav-plugin-admin/issues/773) allow filepicker work inside lists, respond to mutation event + * Better error handling for Feed when unable to connect + * Fixed UI for Pagemedia note when files cannot yet be uploaded ([#798](https://github.com/getgrav/grav-plugin-admin/issues/798)) + * Fixed Submit buttons getting disabled in case of form invalidity disallowing to submit again ([#802](https://github.com/getgrav/grav-plugin-admin/issues/802)) + * Fixed issue when reading the file size setting if set to `0` (in Pagemedia and File fields) + * Fixed issue with `file` field in collections that caused unexpected duplication of items ([#775](https://github.com/getgrav/grav-plugin-admin/issues/775)) + * Dramatically improved `filepicker` performance. Data is only ever loaded when the drop-down is on focus, as it was supposed to be. Image preview of a selected item won't be rendered unless the field gains focus to avoid wasting resources. ([#788](https://github.com/getgrav/grav-plugin-admin/issues/788)) + * Allow `filepicker` field to peak at the pending uploaded files and optimistically select them ([#792](https://github.com/getgrav/grav-plugin-admin/issues/792)) + * Fix [#821](https://github.com/getgrav/grav-plugin-admin/issues/821) issue in saving a page to a new language when the filename does not contain the filename yet. + +# v1.2.2 +## 09/08/2016 + +1. [](#bugfix) + * Fix [#767](https://github.com/getgrav/grav-plugin-admin/issues/767) Add styling for new HTML5 input field types + * Fix issue with checking the package dependencies when more than one package is being inspected + +# v1.2.1 +## 09/07/2016 + +1. [](#bugfix) + * Fixed `tmp://` stream issue with Admin updated to 1.2 before Grav updated 1.1.4 + +# v1.2.0 +## 09/07/2016 + +1. [](#new) + * All new `file` field. All files get uploaded via Ajax and are stored upon Save. This improves the Save task tremendously as now there is no longer the need of waiting for the files to finish uploading. Fully backward compatible, `file` field now includes also a `limit` and `filesize` option in the blueprints. The former determines how many files are allowed to be uploaded when in combination with `multiple: true` (default: 10), the latter determines the file size limit (in MB) allowed for each file (default: 5MB) + * Added a new `filepicker` field, which allows to pick any file from an ajax-powered select box. The `pagemediaselect` field now internally uses the `filepicker` field to live-reload the available files, and to show image previews. +1. [](#improved) + * Better error handling for 500 Internal Server Errors, when Fetch fails + * Various notifications style and other CSS fixes + * More language strings added + * Added `clear-tmp` to cache clear drop-down + * Unified JSON twig templates + * Better error handling for 500 Internal Server Errors, when Fetch fails. + * Updated vendor Libraries +1. [](#bugfix) + * Curl fix for invalid cert errors with News Feed + * Avoid requiring `admin.super` for ajax calls [#739](https://github.com/getgrav/grav-plugin-admin/issues/739) + * Fix showing HTML in notifications, in the feed + * Fixed broken page type filtering + * Fixed `beforeunload` event not prompting to offer the choice to stay on the page in case of unsaved changes + * Fixed click-away detection for preventing loss of changes, that would get ignored in some circumstances (ie, from modal confirmation) + * Fixed issue with `_json` elements where nested fields merging would get stored in an unexpected way + * Fixed composer dependencies missing error message + +# v1.1.4 +## 08/14/2016 + +1. [](#bugfix) + * Fixed Firefox News Feed dashboard widget layout + +# v1.1.3 +## 08/10/2016 + +1. [](#new) + * Admin notifications system. Admin will pull and cache notifications. This will be used to announce important updates, security vulnerabilities, and general interest news. + * Ability to disable widgets in the dashboard + * Added news feed widget to the dashboard +1. [](#improved) + * Updated FontAwesome to v4.6.3 + * Use new List functionality for Media Configuration + * Get fresh media list for `Controller::getListMedia()` rather that cache so always latest. + * Add translation strings for the new system.force_ssl option + * Reworked List UI to better handle drag & drop sort. To sort it is now required to use the left drag handle [#724](https://github.com/getgrav/grav-plugin-admin/issues/724) + * Lists now features a new YAML option `controls: [top|bottom|both]` (default: bottom) which will display the "Add Item" button at the Top and/or Bottom position relative to the list. When the Top button is pressed, a new item will be added at the beginning of the list, when the Bottom button is pressed, a new item will be appended to the list. + * Lists now features two new YAML options `sortby: [field]` (default: disabled) and `sortby_dir: [asc|desc]` (default: asc) which will display a new Sorting button in the list allowing to automatically reindex the collection based on the given sort field set. + * Lists now features a new YAML option `collapsed: [true|false]` (default: false) and a new UI/UX that allows for collapsing / expanding collection items, allowing to better managing long lists of items. It is advised to always put as first field the most significant one, so that when a list is collapsed it can be still easily browsed. + * It is now possible to sort Array fields via drag & drop [#950](https://github.com/getgrav/grav/issues/950) +1. [](#bugfix) + * Fixed issue in Admin favicon URL [#704](https://github.com/getgrav/grav-plugin-admin/issues/704) + * Fixed issue in `selfupgrade` where the package would get downloaded in the wrong destination + * Hide tab when user is not authorized to access it [#712](https://github.com/getgrav/grav-plugin-admin/issues/712) + * Fixed Lists issue when reindexing, causing Radio fields to potentially lose their `checked` status + * Avoid overwriting a file when uploaded with the same filename through the Admin blueprint `file` field type if `avoid_overwriting` is enabled on the field + * Fixed issue with Array field in `value_only` mode, improperly displaying the key when no value was set + * Translate the description of a blueprint field [#729](https://github.com/getgrav/grav-plugin-admin/issues/729) + +# v1.1.2 +## 07/16/2016 + +1. [](#improved) + * Forcing limit of upload files based on System settings +1. [](#bugfix) + * Definitive fix for multi form submission in Microsoft Edge causing the Save to not work [#694](https://github.com/getgrav/grav-plugin-admin/issues/694) + * Fix issue with calculating the `theme_url` with `open_basedir` restrictions [#699](https://github.com/getgrav/grav-plugin-admin/issues/699) + * Check for null payload before going on [#526](https://github.com/getgrav/grav-plugin-admin/issues/526) + * Redraw Dashboard Charts when collapsing/expanding the sidebar + * Fix for `cache/compiled` errors resulting from page media uploads [getgrav/grav#938](https://github.com/getgrav/grav/issues/938) + +# v1.1.1 +## 07/14/2016 + +1. [](#bugfix) + * Fixed issue with forms causing creation of new pages not to work [#698](https://github.com/getgrav/grav-plugin-admin/issues/698) and [getgrav/grav#934](https://github.com/getgrav/grav/issues/934) + +# v1.1.0 +## 07/14/2016 + +1. [](#improved) + * Added the ability to login with the email in addition to the username. [#674](https://github.com/getgrav/grav-plugin-admin/issues/674) + * It is now possible to sort the Plugins and Themes views by 'Name', 'Author', 'GravTeam', 'Release Date', 'Updates Available' and 'Testing' releases (if in Testing Channel), both Ascending and Descending. [#583](https://github.com/getgrav/grav-plugin-admin/issues/583) + * Prevent external links (like the Preview button) to trigger the "Changes Detected" notice [#689](https://github.com/getgrav/grav-plugin-admin/issues/689) + * Added a filter field in Plugins and Themes list views, to allow for quick search of a particular resource + * Added new `Enabled` sorting option for Plugins list view +1. [](#bugfix) + * Fixed an issue that prevented removing more than one page, in the pages listng [#672](https://github.com/getgrav/grav-plugin-admin/issues/672) + * Fixed toggleables in lists that were always loading as checked even when not stored [#688](https://github.com/getgrav/grav-plugin-admin/issues/688) + * Fixed Fullscreen tooltip in Editor displaying off screen (when in fullscreen mode) [#677](https://github.com/getgrav/grav-plugin-admin/issues/677) + * Fixed inconsistency in the way selectized fields would be rendered [#692](https://github.com/getgrav/grav-plugin-admin/issues/692) + * Fixed issue with Save in Microsoft Edge [#694](https://github.com/getgrav/grav-plugin-admin/issues/694) + +# v1.1.0-rc.4 +## 06/21/2016 + +1. [](#bugfix) + * Fix for 'front-end' shortcut showing in mobile sidebar incorrectly. + * Append progressive number to the copied page title. [#394](https://github.com/getgrav/grav-plugin-admin/issues/394) + * Add field description to forms [#667](https://github.com/getgrav/grav-plugin-admin/pull/667) + * Fix clearing all cache [#658](https://github.com/getgrav/grav-plugin-admin/issues/658) + * Assign the correct ordering when saving a page that didn't have ordering set before [#628](https://github.com/getgrav/grav-plugin-admin/issues/628) + * Fix issue when saving a modular child folder as 05.somethin and being reset to 01.something upon save [#628](https://github.com/getgrav/grav-plugin-admin/issues/628) + +# v1.1.0-rc.3 +## 06/14/2016 + +1. [](#bugfix) + * Fix for Gemini Scrollbar CSS breaking layout in IE 9+ [#644](https://github.com/getgrav/grav-plugin-admin/issues/644) + * Fall back to english for UI language if admin's language is not set [#641](https://github.com/getgrav/grav-plugin-admin/issues/641) + * List field has the wrong label/field width. Switched to "1/3 | 2/3" like all other fields. + * Correctly set the page slug on page copy. Avoids having two pages with the same slug [#394](https://github.com/getgrav/grav-plugin-admin/issues/394) + * When copying a page, if there's a page prefix (used for ordering), update the value to avoid having two pages with the same order number [#429](https://github.com/getgrav/grav-plugin-admin/issues/429) + * Fixed size of dropdown text in responsive views to be readable [#647](https://github.com/getgrav/grav-plugin-admin/issues/647) + * Fixed issue with checkbox in toggleables getting submitted with the form even when disabled (fixes #646) + +# v1.1.0-rc.2 +## 06/02/2016 + +1. [](#improved) + * Cleaned up the Page Preview CSS to make it more 'standard' [#634](https://github.com/getgrav/grav-plugin-admin/issues/634) + * Added a legend with the Page colors explained [#637](https://github.com/getgrav/grav-plugin-admin/issues/637) + * Hide email output when sending forgot password instructions [#571](https://github.com/getgrav/grav-plugin-admin/issues/571) +1. [](#bugfix) + * Fixed "Data type `System` doesn't exist!" error when activating a theme [#635](https://github.com/getgrav/grav-plugin-admin/issues/635) + * Fixed issue with custom media types not deleting on save [#633](https://github.com/getgrav/grav-plugin-admin/issues/633) + * Fixed issue when saving `List` field type in plugins + pages + * Fixed JS error on login/logout page due to jQuery not being loaded + + +# v1.1.0-rc.1 +## 06/01/2016 + +1. [](#new) + * Major improvements with the **File Upload** (`file`) field type. Now fully supports themes, plugins, configuration + pages +1. [](#improved) + * Updated with latest languages via [Crowdin](https://crowdin.com/project/grav-admin/) + * Provide security options for single tabs [#615](https://github.com/getgrav/grav-plugin-admin/issues/615) + * Disable double clicking on Save/Delete/Copy page actions [#611](https://github.com/getgrav/grav-plugin-admin/issues/611) + * Tweaked the avatar alignment in sidebar [#592](https://github.com/getgrav/grav-plugin-admin/issues/592) + * Added page name to delete dialog [#511](https://github.com/getgrav/grav-plugin-admin/issues/511) + * Enabling / Disabling a Plugin doesn't trigger the expand / collapse details anymore [#614](https://github.com/getgrav/grav-plugin-admin/issues/614) + * Added hover on plugins list rows to match pages [#619](https://github.com/getgrav/grav-plugin-admin/issues/619) + * Translate media configuration [#608](https://github.com/getgrav/grav-plugin-admin/issues/608) + * Use raw routes in blueprints to better support multi-language [#798](https://github.com/getgrav/grav-plugin-admin/issues/798) + * Updated NPM modules dependencies +1. [](#bugfix) + * Fix double "Removed successfully" appearing when removing a package [#609](https://github.com/getgrav/grav-plugin-admin/issues/609) + * Prevent removing required plugins dependencies when removing a package [#613](https://github.com/getgrav/grav-plugin-admin/issues/613) + * Show page title in Delete Confirmation modal if this information is available + * Don't try to uninstall admin/form/login/email plugins + * Only check for updates if not `admin.maintenance` or `admin.super` [#557](https://github.com/getgrav/grav-plugin-admin/issues/557) + * Always submit checkboxes that are not checked and force a 0 value [#616](https://github.com/getgrav/grav-plugin-admin/issues/616) + * Fix encoding in tooltips again [#622](https://github.com/getgrav/grav-plugin-admin/issues/622) + * Do not show `move` cursor for Collections that aren't sortable [#624](https://github.com/getgrav/grav-plugin-admin/issues/624) + * Properly handle Collections that specify a custom key, rather than falling back to indexed list [#632](https://github.com/getgrav/grav-plugin-admin/issues/632) + +# v1.1.0-beta.5 +## 05/23/2016 + +1. [](#improved) + * Set sidebar navigation defaults back to "Tab Activation" and "Auto Width" + * Custom logo text is displayed as first letter in small sidebar view [#829](https://github.com/getgrav/grav/issues/829) + * Copied admin-only blueprints from Grav core to the Admin plugin + * Allow `field.label` to have HTML in it [#601](https://github.com/getgrav/grav-plugin-admin/issues/601) +1. [](#bugfix) + * Fixed Togggle field with doubled `checked="checked"` when `toggleable: true` [#579](https://github.com/getgrav/grav-plugin-admin/issues/579) + * Strip HTML tags and lowercase username from login/reset forms [#577](https://github.com/getgrav/grav-plugin-admin/issues/577) + * Fixed issue with version numbers not showing up for dependencies [#581](https://github.com/getgrav/grav-plugin-admin/issues/581) + * Fixed editor tooltips in fullscreen mode and tablet devices rendering [#566](https://github.com/getgrav/grav-plugin-admin/issues/566) + * Fixed issue with `file` form field not functioning [#838](https://github.com/getgrav/grav/issues/838) + * Fixed issue with creating pages [#595](https://github.com/getgrav/grav-plugin-admin/issues/595) + +# v1.1.0-beta.4 +## 05/09/2016 + +1. [](#new) + * Implemented Quickopen functionality to automatically open / close the Sidebar when mouseover +1. [](#improved) + * Better error handling when `obj->validate()` fails with exception [#594](https://github.com/getgrav/grav-plugin-admin/issues/564) + * Improve markup of update and add package dependencies in update modal [#560](https://github.com/getgrav/grav-plugin-admin/issues/560) +1. [](#bugfix) + * Fix for admin translation filter (`|tu`) not substituting text - [#567](https://github.com/getgrav/grav-plugin-admin/issues/567) + * Translated "Publishing" tab text [#561](https://github.com/getgrav/grav-plugin-admin/issues/561) + * Fix invalid argument supplied in foreach [#563](https://github.com/getgrav/grav-plugin-admin/issues/563) + * CSS fixes for editor button alignment + * Fix for forgot password not finding anyone + * Fix UI issue with update button on a package page in Firefox + * Fix issue with update button when automatic check for updates is disabled + * Fix issue caused by clicking "Check for updates" multiple times + * Added missing translations + * Fix for Themes with an array of keywords [#823](https://github.com/getgrav/grav/issues/823) + +# v1.1.0-beta.3 +## 05/04/2016 + +1. [](#new) + * Added a `|adminNicetime` Twig filter to show 'nicetime' in admin user's language + * Added a `prepend` and `append` field option for text input type + * Added a WIP `onAdminRegisterPermissions` event + * Added several new languages: Arabic, Danish, Greek, Farsi, Korean, Romanian, Thai. Huge thanks to the [translation teams](https://crowdin.com/project/grav-admin) +1. [](#improved) + * Fixed UI issue with Backup / Update buttons positioning + * Tweaked placeholders color in login/new user panels [#542](https://github.com/getgrav/grav-plugin-admin/issues/542) +1. [](#bugfix) + * Fixed several untranslated strings + * Fix the version information after updating Grav from Admin + * Fix a Twig autoescape issue on Plugins descriptions + * Fix for showing empty drop-down with only one supported language [#522](https://github.com/getgrav/grav-plugin-admin/issues/522) + * Fix for visibility toggle on new page not working [#551](https://github.com/getgrav/grav-plugin-admin/issues/551) + * Page tooltips usability issue [#496](https://github.com/getgrav/grav-plugin-admin/issues/496) + * Fix removed title attribute from editor toolbar buttons [#539](https://github.com/getgrav/grav-plugin-admin/issues/539) + * Allow Incognito / Private browsing to still function in Safari [#527](https://github.com/getgrav/grav-plugin-admin/issues/527) + +# v1.1.0-beta.2 +## 04/27/2016 + +1. [](#new) + * Added `grav ~1.1` to dependencies + * Added a persistent message if you try to run Admin 1.1 on Grav 1.0 +1. [](#improved) + * Used locator instead of `CACHE_DIR` + * Added a better way to get Admin version + * Show account page for users with certain ACL [#524](https://github.com/getgrav/grav-plugin-admin/pull/524) +1. [](#bugfix) + * Fixed Editor Preview using wrong parameters for the ajax call + * Fixed toggle for stable/testing channel + * Fixed blueprint JSON fields + * If not logged in redirect to base path [#445](https://github.com/getgrav/grav-plugin-admin/pull/445) + * Various autoescape fixes + * ColorPicker CSS fixes + * Fix for translation of admin login [#500](https://github.com/getgrav/grav-plugin-admin/issues/500) + * Fix list not applying `toggleable: true` and `style: vertical` [#518](https://github.com/getgrav/grav-plugin-admin/pull/518) + * Fixed issue with update for wrong plugin displaying on plugin details pages + * Fixed error with the **close sidebar** toggle in some browsers (Firefox, iOS Safari) + +# v1.1.0-beta.1 +## 04/20/2016 + +1. [](#new) + * JavaScript Rewrite. Admin is now built in ES6 + * Lists can now be nested and 'fancy fields' (such as editor, datetime picker, selectize, other lists) get automatically initialized so they are always available no matter if you add or remove items from the lists + * The Editor has been reworked to be more flexible. In fact you can now pass any CodeMirror setting via blueprints, through the codemirror: attribute. The buttons have also a new API that allow to add or ignore buttons and behaviors into the toolbar from any plugin (see grav-plugin-editor-buttons). We also added the headers buttons (H1-H6) and Undo / Redo buttons, due to popular demand + * We introduced a new colorpicker field. You can now add more colors to your admin plugins :) + * Along with the versioning support added in the Grav Core for 1.1, the admin plugin can now install dependencies with the same versioning requirements as the GPM CLI commands. + * New System configuration field for toggling GPM release version (testing/stable) + * Several new system configuration options for new functionality such as `Process frontmatter Twig` + * Ability to collapse the sidebar to a smaller icon view if you need more room. +1. [](#improved) + * The default Grav theme has been tweaked and in many places completely rewritten to ensure that it's as flexible as possible. The primary reason for this was to ensure theming and customization compatibility for the upcoming Admin Pro plugin, but a key benefit includes greatly improved mobile compatibility. + * We reworked the Datetimepicker, you will notice a new refreshed UI with a much better support for translations + * Tabs are now persistent. In views such as Page editing, when switching tab and saving or refreshing, would cause the tab to be reset to the initial one. + * When editing a page in Expert mode, the frontmatter editor is now more friendly. You will now get line numbers, undo/redo and YAML linter. + * Behind the scenes we have reworked how the form and toggleables work. This added a lot more reliability and consistency across the whole admin. + * The Pages view has more persistent states. It will now remember your expanded/collapsed states as well as filtering. + * Lists can now accept a custom button label with the 'btnLabel' property + * After login to Admin, redirect to the original URL called + * Admin now has an unique cache key compared to the 'site' so pages can be cached independently + * Improved the layout of the User Profile page. + * Set cache key uniquely for admin so cache does not colide with site +1. [](#bugfix) + * Fix for modular preview - [#254](https://github.com/getgrav/grav-plugin-admin/issues/254) + * Fix for long content and page tabs - [#441](https://github.com/getgrav/grav-plugin-admin/issues/441) + * Fix for clear cache after adding new folder - [#393](https://github.com/getgrav/grav-plugin-admin/issues/393) + +# v1.0.9 +## 02/11/2016 + +1. [](#bugfix) + * Fix language translation files + +# v1.0.8 +## 02/05/2016 + +1. [](#new) + * Added a logout button when not authorized to access a page in Admin + * Added the option to hide a tab from an extended blueprint (https://github.com/getgrav/grav/issues/620) + * Many new languages and updates to existing languages from the Translation team. +1. [](#improved) + * Check frontmatter for validity prior to saving + * Add noindex, nofollow across the entire admin theme if no other robots headers are set on a page + * Allow to hide a configuration blueprint section / tab and still save its values + * Allow to show user defined blueprints in configuration + * Updated FontAwesome to latest 4.5.0 version +1. [](#bugfix) + * Fixed an issue with user registration on Linux caused by `glob()` possibly returning false. + * Fixed an issue preventing Admin to work correctly in a multisite configuration + * Fixed preview and insertion of images with non-lowercase extension + * Fixed an incorrect number of pages being displayed in the sidebar in some cases + * [Security] Don't reveal Grav filesystem path when trying to delete non-existing images + * [Security] Fix PHP error happening when uploading file without extension if the JS dropzone uploader is configured to allow empty file extensions + * [Security] Ensure correct escaping in various Twig files + +# v1.0.7 +## 01/15/2016 + +1. [](#new) + * Added onAdminDashboard event + * Added onAdminSave event + * New lang strings for reverse proxy toggle +1. [](#improved) + * More robust YAML file checking in config folders + * Removed deprecated menu event + * Removed old logs code + * Used new onAdminDashboard event for current dashboard widgets +1. [](#bugfix) + * Fix for missing access checks on config pages #397 + * Fix parent not loaded on admin form save #587 + * When no route field is added to a page blueprint, add it as page root + * Fix for wrong page count (will show dynamic added pages in count too - Need to fix this) + * Fix for IE/Edge saving forms #391 + +# v1.0.6 +## 01/07/2016 + +1. [](#bugfix) + * Fix for forms appending `_json` fields on every save + +# v1.0.5 +## 01/07/2016 + +1. [](#new) + * Added a pointer to Grav's contributing guide + * Handle the optional logic to strip home from Page routes and urls + * The Configuration page now shows any blueprint found in the user/blueprints/config/ folder, thus allowing to add custom configurations +1. [](#improved) + * Allow the nonce for a POST action to be set in the query url + * Add a fallback twig template to use in case Twig cannot find a template file + * Modified update Theme and Plugin buttons to use more reliably markup +1. [](#bugfix) + * Fix additional `on` parameter when saving plugins configs that contain tabs in their blueprint + * Fixes for the `pagemediaselect` form field + * Fix an untranslated message in the logout form when `system.languages.translations` is disabled + * Fixed a hardcoded `http://` reference throwing warnings under HTTPS + * Ensure download package has `.zip` extension, just in case + +# v1.0.4 +## 12/22/2015 + +1. [](#improved) + * Improved File input field for admin + * Restore file inputs functionality and process form via JS if no inputs found +1. [](#bugfix) + * Fix for the image preview in the file field on multi-lang sites + * Fix problem in form code introduced by fix to allow file uploads + * Fix redirect in deleting page media + +# v1.0.3 +## 12/20/2015 + +1. [](#new) + * Added `pagemediaselect` field for use in pages +1. [](#improved) + * Updated various languages + * Check for method `meetsRequirements()` prior to using + * Enable `file` form field to be used in plugins and theme blueprints + +# v1.0.2 +## 12/18/2015 + +1. [](#bugfix) + * Fixed issue with user edit page causing error due to individual language files + +# v1.0.1 +## 12/18/2015 + +1. [](#new) + * Moved languages into individual files under `languages/` folder + * Added a check for PHP version + * Dutch translation added +1. [](#improved) + * Let forms work with file inputs + * Various file input improvements + * Language updates + * Better checks for existence of Popularity JSON data + * Add file processing to admin forms + * More Admin Pro integration fixes +1. [](#bugfix) + * Set form to multipart if it contains a file field + * `cleanFilesData()` now returns just the filename + +# v1.0.0 +## 12/11/2015 + +1. [](#new) + * New built-in admin registration process + * Added security check to `section` form field + * Added new RocketTheme font with various icons + * Add `onAdminThemeInitialized()` event to admin `Themes::init()` + * Force timestamp on CSS/JS assets based on `GRAV_VERSION` + * Additions for Gantry5 support +1. [](#improved) + * Force lowercase `username` when logging in + * Hide markdown preview except for pages + * Added a notice if you don't have permission to see dashboard + * Updated admin login page logic + * Return "Invalid Security Token" instead of "Unauthorized" + * Throw exception if you used with built-in PHP web server + * Updated languages + * Removed `noreply@getgrav.org` default email address + * Use new methods to disable CSS/JS pipeline if available + * Various code cleanups +1. [](#bugfix) + * Handle case when email `from` is not configured + * Fix tabs support in plugin/themes settings + * Fix param separator in page media Ajax call + * Fix favicon base URL + +# v1.0.0-rc.7 +## 12/01/2015 + +1. [](#new) + * Display error page if page does not exist in admin + * Removed Beta message option and added toggle for GitHub message + * Added functionality to support Admin Pro plugin (in development) +1. [](#improved) + * Added support for Markdown editor in lists #239 + * Better Markdown Editor API with dynamic initialization + * Various language updates + * Removed some unused variables + * Added admin check for pages existence + * Prevent the admin to cause an error when an Ajax action is in progress + * Force translations to be active even when disabled in site #299 + * Do not reinitialize `Selectize` if already available +1. [](#bugfix) + * Fixed full-screen markdown Editor + * Fix modular preview not working reliably #254 + * **Nonce fixes** (hopefully the last of them!) + * Fix broken plugin enable/disable + * Fix issue where `_redirect: /plugins` was getting stored in the plugin configuration + * Replace default them service with admin one + * Fix saving array fields #304 + * Fix missing translations when default language is not english + * Fix title variables not translated #310 + +# v1.0.0-rc.6 +## 11/21/2015 + +1. [](#improved) + * Implemented logic to detect when offline and suppress Ajax calls + * Added nonce logic to be used by JS +1. [](#bugfix) + * Nonce fix for updating themes + * Nonce fix for deleting pages + +# v1.0.0-rc.5 +## 11/20/2015 + +1. [](#new) + * Use **Nonce** mechanism for form security + * Added Hungarian translation + * Add support for Markdown labels #271 + * Added support for Markdown Editor in all the things + * Implemented save keyboard shortcut (Ctrl + S / CMD + S) +1. [](#improved) + * Better error for "Internal Server Error" when accessing GPM + * Updated French translation + * Updated Russian translation + * Load Gravatar image with protocol-less `//:` syntax + * Improved header UI in mobile browsers #265 + * Dropped unused version of JQuery + * More visible Preview link icon + * Hide **Latest pages** if there are none + * Improved toggle to better support different length strings +1. [](#bugfix) + * Force rescanning fields when submitting a form #243 + * Set default lang for pages on fresh session + * Escaped values in `array.html.twig` + * Fix saving in IE Edge + * Fixed various typos + * Fixed JS button issues #370 + * Fixed JS error in private browsing #272 + * Fixed date field border + * Fixed multiple instance of Markdown Editor #285 + * Fixed Spacer CSS #267 + +# v1.0.0-rc.4 +## 10/29/2015 + +1. [](#improved) + * Changed admin menu event hook to `onAdminMenu()` + * Minor improvements for admin page location + * Additional lang strings for Grav 1.0.0-rc.3 + +# v1.0.0-rc.3 +## 10/27/2015 + +1. [](#improved) + * Rely on context-language for active language + * Improved some Russian translations + * Only show login if not already logged in +1. [](#bugfix) + * Disable asset pipeline in admin only + * Fix Editor cursor insertion point when text is selected in some actions + +# v1.0.0-rc.2 +## 10/23/2015 + +1. [](#bugfix) + * Reverted lang redirect code. Needs to be reworked to be more reliable + +# v1.0.0-rc.1 +## 10/23/2015 + +1. [](#new) + * Redirect to non-language URL except for `pages/` +1. [](#improved) + * New language strings for new `system.yaml` fields + * Improved Russian translations + * Improved compatibility with PECL Yaml parser +1. [](#bugfix) + * Redirect to correct page if you change folder/slug + * Fix issue with Asset pipeline not being disabled in admin + * Fix for HTML in text input fields + * Fixed various icons in headers + +# v0.6.2 +## 10/15/2015 + +1. [](#improved) + * Use `title` rather than `menu` in Page listing + * Wrapped language strings in double-quotes + * New language strings for new fields +1. [](#bugfix) + * Fixed issue with IE not able to save pages + +# v0.6.1 +## 10/07/2015 + +1. [](#new) + * Added the ability to render front-end templates in markdown preview + * Option to disable Google-based fonts. Useful for Cyrillic languages. + * Couple of new static helper methods used by new page blueprints + * New `fieldset` form field (thanks @Sommerregen!) +1. [](#improved) + * Hide editor buttons in preview mode + * Improved support for admin when offline + * Use relative URL in Login form + * Added some more missing lang strings + * Improved German translation + * Compressed CSS files for improved performance + * Only get last 7 days in week count calculation +1. [](#bugfix) + * Fix saving pages in local-specific languages + * Only track 'human' page hits in statistics + * Responsive fixes for 'wordy' languages + * Fixed delete issue with array field type + * Fixed some hardcoded `admin` references to allow admin path change + * Fix for issue with lang code being added twice + * Fix language name in admin buttons + +# v0.6.0 +## 09/16/2015 + +1. [](#new) + * Support for custom markdown editor buttons! + * Added Russian translations + * Added Japanese translations + * Ajax session keep-alive when editing forms +1. [](#improved) + * Added missing Italian translations + * Added additional options field into the pages form field +1. [](#bugfix) + * Fix GPM errors in offline mode + * Fix for duplicate status messages + +# v0.5.0 +## 09/11/2015 + +1. [](#new) + * Responsive layout for mobile compatibility (thanks @Vivalldi!) + * Added page type and many other new filters to Page list view + * Added granular ACL requirements to admin pages + * Ability to define page date format + * Added `onAdminTemplateNavPluginHook` to allow for plugins to hook into sidebar + * Added YAML Twig filters (to and from) + * Support for nested metadata + * Added ability to disable automatic update checks via admin plugin configuration + * Initial Spanish translation +1. [](#improved) + * Check for existence of a user account + * Various language additions + * Refactored form fields to remove duplicates from form plugin + * Improved date picker + * Improved display field + * Add page template type to page list view + * Various UI fixes + * Added some default field 'focus' to save clicking + * Only allow "Add Modular" if the theme has modular templates + * Updated `chartist.js` library + * Updated 'fontawesome' fonts to the latest v4.4 +1. [](#bugfix) + * Fix for "drag-n-drop" of non-image media + * Fix a fatal error in GPM when offline + * Fix a z-index bug with tooltips + * Fix a z-index bug in lang dropdowns + * Don't allow deleting of last empty array field + * Fix for images with parenthesis in filenames + * Fix for page title visualization when not set + * Fix for cursor position in folder/array fields + +# v0.4.3 +## 08/31/2015 + +1. [](#new) + * Added Japanese translation + * Support for independent file name and template override +1. [](#improved) + * Improved slug generation using `slugify.js` + * Allow the `title` twig variables to set the page title + * Improved Page media handling with several bugfixes + * Prevent error when there are no pages on a site + * If all updates are applied, show "Fully Updated" text in dashboard + * Better preview link (requires `rtrim` filter from Grav 0.9.40) + * Order all plugins and themes alphabetically + * Removed duplicate language entries +1. [](#bugfix) + * Fix for redirect after saving when multilang not enabled + * Fix for deleting responsive media + * Fix for HTML encoding in markdown field + +# v0.4.2 +## 08/25/2015 + +1. [](#bugfix) + * Fix for current admin lang not showing up in page lang dropdown + * Fix for incorrect NAME/CONTENT lang keys + * Fix for incorrect site link + +# v0.4.1 +## 08/24/2015 + +1. [](#bugfix) + * Fix for broken **Add Page** - Doh! + * Fix for empty site link when at root + +# v0.4.0 +## 08/24/2015 + +1. [](#new) + * Multi-language Page support!!! + * Admin languages configurable per user + * Toastr messages for `check updates` + * new `tu` filter for admin translations + * Italian and German admin translations + * Added a save location in system and site configuration + * Page metadata now uses flexible array field +1. [](#improved) + * Allow subpages of modular pages to display in pages list + * Open external pages in new tabs + * Reworked `visibility` of pages + * Use `PLUGIN_ADMIN` prefix for translations + * Added link to gravatar.com to avoid confusion on avatar + * Limit page count to 200 in ordering field + * Fixed various Safari _flex_ issues + * Use `rawRoute()` for page links + * Minor `param separator` fixes + * Various CSS fixes + * Improved CodeMirror to force spaces + * Added **Selectize** dropdowns to various forms and modals +1. [](#bugfix) + * Fix for `Call to a member function path() on non-object` error + * Fixed dropdown z-index issues + * Correctly set the filename including language if set + * Fix for empty taxonomies on page save + * Fix for page not redirecting properly on folder change + * Fix for table headers styling + * Added missing translation strings + * Unique page counting in total page counts + * Fixed JS warning with page filtering and deleting + + +# v0.3.0 +## 08/11/2015 + +1. [](#new) + * Show current date in form date format fields + * Added a new **check for updates** button to flush GPM + * Added session timeout configuration for admin + * Added `isSymlink` logic for Grav + * Added new `phpinfo` page +1. [](#improved) + * Improved toggleables + * Support `param_separator` for Apache on windows + * Logout now goes to interstitial to provide session messages + * Updated hints and improved formatting + * Encoding URI for images in editor preview + * Create user `system.yaml` and `site.yaml` if they are missing + * Open external links in new tab by default + * Set edit mode to `normal` by default + * Disable CSS/JS pipelining in the admin +1. [](#bugfix) + * Fixed form submission not working in IE + * Fix fatal error when deleting homepage + * Prevent admin plugin activating when the URL of a page contains partial route + +# v0.2.0 +## 08/06/2015 + +1. [](#new) + * Added multiple **clear cache** types + * Added back to themes link when adding new themes + * Properly handles visibility and ordering and guesses best option on new + * Added new templates field with support for custom (unsupported) template type + * Added new display field for displaying simple text value + * **Update Grav** button now works + * Added spanish translation + * Added german translation +1. [](#improved) + * Improved page order handling logic + * Implemented 2-step theme switching logic with warning + * Force `modular` page class for modular template + * Clear page cache on page delete (ghost pages still showing) + * Clears route on page save so changes such as `slug` are picked up + * Fix dashboard layout in Safari + * Added tooltips for official 'Team Grav' themes/plugins +1. [](#bugfix) + * Handle modular page templates on create + * Fixed Firefox JS error for arrays + * Ensure we don't change page type to empty and save (causing page to be deleted) + * Fixed some minor CSS issues with editor + * Fixed link to RocketTheme.com + * Disabled fields now stay properly disabled + +# v0.1.1 +## 08/04/2015 + +1. [](#bugfix) + * Fixed GitHub URLs + * Hiding toggle for disabling Admin plugin + * Removed extra text not needed + +# v0.1.0 +## 08/04/2015 + +1. [](#new) + * ChangeLog started... diff --git a/user/plugins/admin/CONTRIBUTING.md b/user/plugins/admin/CONTRIBUTING.md new file mode 100644 index 0000000..ef2bc6f --- /dev/null +++ b/user/plugins/admin/CONTRIBUTING.md @@ -0,0 +1 @@ +Please read the Contributing Guidelines of the Grav Project \ No newline at end of file diff --git a/user/plugins/admin/LICENSE b/user/plugins/admin/LICENSE new file mode 100644 index 0000000..f7d4bb6 --- /dev/null +++ b/user/plugins/admin/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Grav + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/user/plugins/admin/README.md b/user/plugins/admin/README.md new file mode 100644 index 0000000..620e821 --- /dev/null +++ b/user/plugins/admin/README.md @@ -0,0 +1,111 @@ +# Grav Standard Administration Panel Plugin + +This **admin plugin** for [Grav](http://github.com/getgrav/grav) is an HTML user interface that provides a convenient way to configure Grav and easily create and modify pages. This will remain a totally optional plugin, and is not in any way required or needed to use Grav effectively. In fact, the admin provides an intentionally limited view to ensure it remains easy to use and not overwhelming. I'm sure power users will still prefer to work with the configuration files directly. + +![](assets/admin-dashboard.png) + +# Features + +* User login with automatic password encryption +* Forgot password functionality +* Logged-in-user management +* One click Grav core updates +* Dashboard with maintenance status, site activity and latest page updates +* Notifications system for latest news, blogs, and announcements +* Ajax-powered backup capability +* Ajax-powered clear-cache capability +* System configuration management +* Site configuration management +* Normal and Expert modes which allow editing via forms or YAML +* Page listing with filtering and search +* Page creation, editing, moving, copying, and deleting +* Powerful syntax highlighting code editor with instant Grav-powered preview +* Editor features, hot keys, toolbar, and distraction-free fullscreen mode +* Drag-n-drop upload of page media files including drag-n-drop placement in the editor +* One click theme and plugin updates +* Plugin manager that allows listing and configuration of installed plugins +* Theme manager that allows listing and configuration of installed themes +* GPM-powered installation of new plugins and themes + +# Support + +#### Support + +We have tested internally, but we hope to use this public beta phase to identify, isolate, and fix issues related to the plugin to ensure it is as solid and reliable as possible. + +For **live chatting**, please use the dedicated [Slack Chat Room](https://getgrav.org/slack) for discussions directly related to Grav. + +For **bugs, features, improvements**, please ensure you [create issues in the admin plugin GitHub repository](https://github.com/getgrav/grav-plugin-admin). + +# Installation + +First ensure you are running the latest **Grav 0.9.34 or later**. This is required for the admin plugin to run properly (`-f` forces a refresh of the GPM index). + +``` +$ bin/gpm selfupgrade -f +``` + +The admin plugin actually requires the help of 3 other plugins, so to get the admin plugin to work you first need to install **admin**, **login**, **forms**, and **email** plugins. These are available via GPM, and because the plugin has dependencies you just need to proceed and install the admin plugin, and agree when prompted to install the others: + +``` +$ bin/gpm install admin +``` + +### Manual Installation + +Manual installation is not the recommended method of installation, however, it is still possible to install the admin plugin manually. Basically, you need to download each of the following plugins individually: + +* [admin](https://github.com/getgrav/grav-plugin-admin/archive/develop.zip) +* [login](https://github.com/getgrav/grav-plugin-login/archive/develop.zip) +* [form](https://github.com/getgrav/grav-plugin-form/archive/develop.zip) +* [email](https://github.com/getgrav/grav-plugin-email/archive/develop.zip) + +Extract each archive file into your `user/plugins` folder, then ensure the folders are renamed to just `admin/`, `login/`, `form/`, and `email/`. Then proceed with the **Usage instructions below**. + +# Usage + +### Create User with CLI + +After this you need to create a user account with admin privileges: + +``` +$ bin/plugin login new-user +``` + +### Create User Manually + +Alternatively, you can create a user account manually, in a file called `user/accounts/admin.yaml`. This **filename** is actually the **username** that you will use to login. The contents will contain the other information for the user. + +``` +password: 'password' +email: 'youremail@mail.com' +fullname: 'Johnny Appleseed' +title: 'Site Administrator' +access: + admin: + login: true + super: true +``` + +Of course you should edit your `email`, `password`, `fullname`, and `title` to suit your needs. + +> You can use any password when you manually put it in this `.yaml` file. However, when you change your password in the admin, it must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters. + +# Accessing the Admin + +By default, you can access the admin by pointing your browser to `http://yoursite.com/admin`. You can simply log in with the `username` and `password` set in the YAML file you configured earlier. + +> After logging in, your **plaintext password** will be removed and replaced by an **encrypted** one. + +# Standard Free & Paid Pro Versions + +If you have been following the [blog](http://getgrav.org/blog), [Twitter](https://twitter.com/getgrav), [Slack chat](https://getgrav.org/slack), etc., you probably already know now that our intention is to provide two versions of this plugin. + +The **standard free version**, is very powerful, and has more functionality than most commercial flat-file CMS systems. + +We also intend to release in the near future a more feature-rich **pro version** that will include enhanced functionality, as well as some additional nice-to-have capabilities. This pro version will be a **paid** plugin the price of which is not yet 100% finalized. + +# Running Tests + +First install the dev dependencies by running `composer update` from the Grav root. +Then `composer test` will run the Unit Tests, which should be always executed successfully on any site. diff --git a/user/plugins/admin/admin.php b/user/plugins/admin/admin.php new file mode 100644 index 0000000..5fcf2bb --- /dev/null +++ b/user/plugins/admin/admin.php @@ -0,0 +1,892 @@ + 1000, + ]; + + /** + * @var bool + */ + protected $active = false; + + /** + * @var string + */ + protected $template; + + /** + * @var string + */ + protected $theme; + + /** + * @var string + */ + protected $route; + + /** + * @var string + */ + protected $admin_route; + + /** + * @var Uri + */ + protected $uri; + + /** + * @var Admin + */ + protected $admin; + + /** + * @var Session + */ + protected $session; + + /** + * @var Popularity + */ + protected $popularity; + + /** + * @var string + */ + protected $base; + + protected $version; + + /** + * @return array + */ + public static function getSubscribedEvents() + { + + return [ + 'onPluginsInitialized' => [ + ['setup', 100000], + ['onPluginsInitialized', 1001] + ], + 'onPageInitialized' => ['onPageInitialized', 0], + 'onShutdown' => ['onShutdown', 1000], + 'onFormProcessed' => ['onFormProcessed', 0], + 'onAdminDashboard' => ['onAdminDashboard', 0], + 'onAdminTools' => ['onAdminTools', 0], + ]; + + } + + public function onPageInitialized() + { + $page = $this->grav['page']; + + $template = $this->grav['uri']->param('tmpl'); + + if ($template) { + $page->template($template); + } + } + + /** + * If the admin path matches, initialize the Login plugin configuration and set the admin + * as active. + */ + public function setup() + { + // Autoloader + spl_autoload_register(function ($class) { + if (Utils::startsWith($class, 'Grav\Plugin\Admin')) { + require_once __DIR__ .'/classes/' . strtolower(basename(str_replace("\\", '/', $class))) . '.php'; + } + }); + + $route = $this->config->get('plugins.admin.route'); + if (!$route) { + return; + } + + $this->base = '/' . trim($route, '/'); + $this->admin_route = rtrim($this->grav['pages']->base(), '/') . $this->base; + $this->uri = $this->grav['uri']; + + $users_exist = Admin::doAnyUsersExist(); + + // If no users found, go to register + if (!$users_exist) { + if (!$this->isAdminPath()) { + $this->grav->redirect($this->admin_route); + } + $this->template = 'register'; + } + + // Only activate admin if we're inside the admin path. + if ($this->isAdminPath()) { + $this->active = true; + + // Set cache based on admin_cache option + if (method_exists($this->grav['cache'], 'setEnabled')) { + $this->grav['cache']->setEnabled($this->config->get('plugins.admin.cache_enabled')); + } + } + } + + /** + * Validate a value. Currently validates + * + * - 'user' for username format and username availability. + * - 'password1' for password format + * - 'password2' for equality to password1 + * + * @param string $type The field type + * @param string $value The field value + * @param string $extra Any extra value required + * + * @return bool + */ + protected function validate($type, $value, $extra = '') + { + /** @var Login $login */ + $login = $this->grav['login']; + + return $login->validateField($type, $value, $extra); + } + + /** + * Process the admin registration form. + * + * @param Event $event + */ + public function onFormProcessed(Event $event) + { + $form = $event['form']; + $action = $event['action']; + + switch ($action) { + case 'register_admin_user': + + if (Admin::doAnyUsersExist()) { + throw new \RuntimeException('A user account already exists, please create an admin account manually.'); + } + + if (!$this->config->get('plugins.login.enabled')) { + throw new \RuntimeException($this->grav['language']->translate('PLUGIN_LOGIN.PLUGIN_LOGIN_DISABLED')); + } + + $data = []; + $username = $form->value('username'); + + if ($form->value('password1') !== $form->value('password2')) { + $this->grav->fireEvent('onFormValidationError', new Event([ + 'form' => $form, + 'message' => $this->grav['language']->translate('PLUGIN_LOGIN.PASSWORDS_DO_NOT_MATCH') + ])); + $event->stopPropagation(); + + return; + } + + $data['password'] = $form->value('password1'); + + $fields = [ + 'email', + 'fullname', + 'title' + ]; + + foreach ($fields as $field) { + // Process value of field if set in the page process.register_user + if (!isset($data[$field]) && $form->value($field)) { + $data[$field] = $form->value($field); + } + } + + // Don't store plain text password or username (part of the filename). + unset($data['password1'], $data['password2'], $data['username']); + + // Extra lowercase to ensure file is saved lowercase + $username = strtolower($username); + + $inflector = new Inflector(); + + $data['fullname'] = isset($data['fullname']) ? $data['fullname'] : $inflector->titleize($username); + $data['title'] = isset($data['title']) ? $data['title'] : 'Administrator'; + $data['state'] = 'enabled'; + $data['access'] = ['admin' => ['login' => true, 'super' => true], 'site' => ['login' => true]]; + + // Create user object and save it + $user = new User($data); + $file = CompiledYamlFile::instance($this->grav['locator']->findResource('user://accounts/' . $username . YAML_EXT, + true, true)); + $user->file($file); + $user->save(); + $user = User::load($username); + + //Login user + $this->grav['session']->user = $user; + unset($this->grav['user']); + $this->grav['user'] = $user; + $user->authenticated = true; + $user->authorized = $user->authorize('site.login'); + + $messages = $this->grav['messages']; + $messages->add($this->grav['language']->translate('PLUGIN_ADMIN.LOGIN_LOGGED_IN'), 'info'); + $this->grav->redirect($this->admin_route); + + break; + } + } + + /** + * If the admin plugin is set as active, initialize the admin + */ + public function onPluginsInitialized() + { + // Only activate admin if we're inside the admin path. + if ($this->active) { + // Store this version. + $this->version = $this->getBlueprint()->version; + + // Have a unique Admin-only Cache key + if (method_exists($this->grav['cache'], 'setKey')) { + $cache = $this->grav['cache']; + $cache_key = $cache->getKey(); + $cache->setKey($cache_key . '$'); + } + + // Turn on Twig autoescaping + if (method_exists($this->grav['twig'], 'setAutoescape') && $this->grav['uri']->param('task') !== 'processmarkdown') { + $this->grav['twig']->setAutoescape(true); + } + + $this->grav['debugger']->addMessage("Admin Basic"); + $this->initializeAdmin(); + + // Disable Asset pipelining (old method - remove this after Grav is updated) + if (!method_exists($this->grav['assets'], 'setJsPipeline')) { + $this->config->set('system.assets.css_pipeline', false); + $this->config->set('system.assets.js_pipeline', false); + } + + // Replace themes service with admin. + $this->grav['themes'] = function () { + return new Themes($this->grav); + }; + } + + // We need popularity no matter what + $this->popularity = new Popularity(); + + // Fire even to register permissions from other plugins + $this->grav->fireEvent('onAdminRegisterPermissions', new Event(['admin' => $this->admin])); + } + + protected function initializeController($task, $post) + { + $controller = new AdminController(); + $controller->initialize($this->grav, $this->template, $task, $this->route, $post); + $controller->execute(); + $controller->redirect(); + } + + /** + * Sets longer path to the home page allowing us to have list of pages when we enter to pages section. + */ + public function onPagesInitialized() + { + $this->session = $this->grav['session']; + + // Set original route for the home page. + $home = '/' . trim($this->config->get('system.home.alias'), '/'); + + // set the default if not set before + $this->session->expert = $this->session->expert ?: false; + + // set session variable if it's passed via the url + if ($this->uri->param('mode') === 'expert') { + $this->session->expert = true; + } elseif ($this->uri->param('mode') === 'normal') { + $this->session->expert = false; + } + + /** @var Pages $pages */ + $pages = $this->grav['pages']; + + $this->grav['admin']->routes = $pages->routes(); + + // Remove default route from routes. + if (isset($this->grav['admin']->routes['/'])) { + unset($this->grav['admin']->routes['/']); + } + + $page = $pages->dispatch('/', true); + + // If page is null, the default page does not exist, and we cannot route to it + if ($page) { + $page->route($home); + } + + // Make local copy of POST. + $post = !empty($_POST) ? $_POST : []; + + // Handle tasks. + $this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task'); + if ($task) { + $this->initializeController($task, $post); + } elseif ($this->template === 'logs' && $this->route) { + // Display RAW error message. + echo $this->admin->logEntry(); + exit(); + } + + $self = $this; + + // make sure page is not frozen! + unset($this->grav['page']); + + $this->admin->pagesCount(); + + // Replace page service with admin. + $this->grav['page'] = function () use ($self) { + $page = new Page; + $page->expires(0); + + // First look in the pages provided by the Admin plugin itself + if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) { + $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md")); + $page->slug(basename($self->template)); + return $page; + } + + // If not provided by Admin, lookup pages added by other plugins + $plugins = $this->grav['plugins']; + $locator = $this->grav['locator']; + + foreach ($plugins as $plugin) { + if ($this->config->get("plugins.{$plugin->name}.enabled") !== true) { + continue; + } + + $path = $locator->findResource("user://plugins/{$plugin->name}/admin/pages/{$self->template}.md"); + + if ($path) { + $page->init(new \SplFileInfo($path)); + $page->slug(basename($self->template)); + + return $page; + } + } + + return null; + }; + + if (empty($this->grav['page'])) { + if ($this->grav['user']->authenticated) { + $event = $this->grav->fireEvent('onPageNotFound'); + + if (isset($event->page)) { + unset($this->grav['page']); + $this->grav['page'] = $event->page; + } else { + throw new \RuntimeException('Page Not Found', 404); + } + } else { + $this->grav->redirect($this->admin_route); + } + } + + // Explicitly set a timestamp on assets + $this->grav['assets']->setTimestamp(substr(md5(GRAV_VERSION . $this->grav['config']->checksum()), 0, 10)); + } + + /** + * Handles initializing the assets + */ + public function onAssetsInitialized() + { + // Disable Asset pipelining + $assets = $this->grav['assets']; + $assets->setJsPipeline(false); + $assets->setCssPipeline(false); + } + + /** + * Add twig paths to plugin templates. + */ + public function onTwigTemplatePaths() + { + $twig_paths = []; + $this->grav->fireEvent('onAdminTwigTemplatePaths', new Event(['paths' => &$twig_paths])); + + $twig_paths[] = __DIR__ . '/themes/' . $this->theme . '/templates'; + + $this->grav['twig']->twig_paths = $twig_paths; + } + + /** + * Set all twig variables for generating output. + */ + public function onTwigSiteVariables() + { + $twig = $this->grav['twig']; + $page = $this->grav['page']; + + $twig->twig_vars['location'] = $this->template; + $twig->twig_vars['base_url_relative_frontend'] = $twig->twig_vars['base_url_relative'] ?: '/'; + $twig->twig_vars['admin_route'] = trim($this->admin_route, '/'); + $twig->twig_vars['base_url_relative'] = $twig->twig_vars['base_url_simple'] . '/' . $twig->twig_vars['admin_route']; + $theme_url = '/' . ltrim($this->grav['locator']->findResource('plugin://admin/themes/' . $this->theme, + false), '/'); + $twig->twig_vars['theme_url'] = $theme_url; + $twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative']; + $twig->twig_vars['base_path'] = GRAV_ROOT; + $twig->twig_vars['admin'] = $this->admin; + $twig->twig_vars['admin_version'] = $this->version; + + $fa_icons_file = CompiledYamlFile::instance($this->grav['locator']->findResource('plugin://admin/themes/grav/templates/forms/fields/iconpicker/icons' . YAML_EXT)); + $fa_icons = $fa_icons_file->content(); + $fa_icons = array_map(function ($icon) { + //only pick used values + return ['id' => $icon['id'], 'unicode' => $icon['unicode']]; + }, $fa_icons['icons']); + + $twig->twig_vars['fa_icons'] = $fa_icons; + + // add form if it exists in the page + $header = $page->header(); + + $forms = []; + if (isset($header->forms)) foreach ($header->forms as $key => $form) { + $forms[$key] = new Form($page, null, $form); + } + $twig->twig_vars['forms'] = $forms; + + // preserve form validation + if (!isset($twig->twig_vars['form'])) { + if (isset($header->form)) { + $twig->twig_vars['form'] = new Form($page); + } elseif (isset($header->forms)) { + $twig->twig_vars['form'] = new Form($page, null, reset($header->forms)); + } + } + + // Gather Plugin-hooked nav items + $this->grav->fireEvent('onAdminMenu'); + + switch ($this->template) { + case 'dashboard': + $twig->twig_vars['popularity'] = $this->popularity; + + // Gather Plugin-hooked dashboard items + $this->grav->fireEvent('onAdminDashboard'); + + break; + } + + $flashData = $this->grav['session']->getFlashCookieObject(Admin::TMP_COOKIE_NAME); + + if (isset($flashData->message)) { + $this->grav['messages']->add($flashData->message, $flashData->status); + } + } + + /** + * Handles the shutdown + */ + public function onShutdown() + { + if ($this->active) { + //only activate when Admin is active + if ($this->admin->shouldLoadAdditionalFilesInBackground()) { + $this->admin->loadAdditionalFilesInBackground(); + } + } else { + //if popularity is enabled, track non-admin hits + if ($this->config->get('plugins.admin.popularity.enabled')) { + $this->popularity->trackHit(); + } + } + } + + /** + * Get list of form field types specified in this plugin. Only special types needs to be listed. + * + * @return array + */ + public function getFormFieldTypes() + { + return [ + 'column' => [ + 'input@' => false + ], + 'columns' => [ + 'input@' => false + ], + 'fieldset' => [ + 'input@' => false + ], + 'section' => [ + 'input@' => false + ], + 'tab' => [ + 'input@' => false + ], + 'tabs' => [ + 'input@' => false + ], + 'key' => [ + 'input@' => false + ], + 'list' => [ + 'array' => true + ], + 'file' => [ + 'array' => true + ] + ]; + } + + /** + * Initialize the admin. + * + * @throws \RuntimeException + */ + protected function initializeAdmin() + { + $this->enable([ + 'onTwigExtensions' => ['onTwigExtensions', 1000], + 'onPagesInitialized' => ['onPagesInitialized', 1000], + 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 1000], + 'onTwigSiteVariables' => ['onTwigSiteVariables', 1000], + 'onAssetsInitialized' => ['onAssetsInitialized', 1000], + 'onAdminRegisterPermissions' => ['onAdminRegisterPermissions', 0], + 'onOutputGenerated' => ['onOutputGenerated', 0], + 'onAdminAfterSave' => ['onAdminAfterSave', 0], + ]); + + // Autoload classes + require_once __DIR__ . '/vendor/autoload.php'; + + + // Check for required plugins + if (!$this->grav['config']->get('plugins.login.enabled') || !$this->grav['config']->get('plugins.form.enabled') || !$this->grav['config']->get('plugins.email.enabled')) { + throw new \RuntimeException('One of the required plugins is missing or not enabled'); + } + + // Initialize Admin Language if needed + /** @var Language $language */ + $language = $this->grav['language']; + if ($language->enabled() && empty($this->grav['session']->admin_lang)) { + $this->grav['session']->admin_lang = $language->getLanguage(); + } + + // Decide admin template and route. + $path = trim(substr($this->uri->route(), strlen($this->base)), '/'); + + if (empty($this->template)) { + $this->template = 'dashboard'; + } + + // Can't access path directly... + if ($path && $path !== 'register') { + $array = explode('/', $path, 2); + $this->template = array_shift($array); + $this->route = array_shift($array); + } + + // Initialize admin class. + $this->admin = new Admin($this->grav, $this->admin_route, $this->template, $this->route); + + + // And store the class into DI container. + $this->grav['admin'] = $this->admin; + + // Double check we have system.yaml, site.yaml etc + $config_path = $this->grav['locator']->findResource('user://config'); + foreach ($this->admin->configurations() as $config_file) { + $config_file = "{$config_path}/{$config_file}.yaml"; + if (!file_exists($config_file)) { + touch($config_file); + } + } + + // Get theme for admin + $this->theme = $this->config->get('plugins.admin.theme', 'grav'); + + $assets = $this->grav['assets']; + $translations = 'this.GravAdmin = this.GravAdmin || {}; if (!this.GravAdmin.translations) this.GravAdmin.translations = {}; ' . PHP_EOL . 'this.GravAdmin.translations.PLUGIN_ADMIN = {'; + + // Enable language translations + $translations_actual_state = $this->config->get('system.languages.translations'); + $this->config->set('system.languages.translations', true); + + $strings = [ + 'EVERYTHING_UP_TO_DATE', + 'UPDATES_ARE_AVAILABLE', + 'IS_AVAILABLE_FOR_UPDATE', + 'AND', + 'IS_NOW_AVAILABLE', + 'CURRENT', + 'UPDATE_GRAV_NOW', + 'TASK_COMPLETED', + 'UPDATE', + 'UPDATING_PLEASE_WAIT', + 'GRAV_SYMBOLICALLY_LINKED', + 'OF_YOUR', + 'OF_THIS', + 'HAVE_AN_UPDATE_AVAILABLE', + 'UPDATE_AVAILABLE', + 'UPDATES_AVAILABLE', + 'FULLY_UPDATED', + 'DAYS', + 'PAGE_MODES', + 'PAGE_TYPES', + 'ACCESS_LEVELS', + 'NOTHING_TO_SAVE', + 'FILE_UNSUPPORTED', + 'FILE_ERROR_ADD', + 'FILE_ERROR_UPLOAD', + 'DROP_FILES_HERE_TO_UPLOAD', + 'DELETE', + 'UNSET', + 'INSERT', + 'METADATA', + 'VIEW', + 'UNDO', + 'REDO', + 'HEADERS', + 'BOLD', + 'ITALIC', + 'STRIKETHROUGH', + 'SUMMARY_DELIMITER', + 'LINK', + 'IMAGE', + 'BLOCKQUOTE', + 'UNORDERED_LIST', + 'ORDERED_LIST', + 'EDITOR', + 'PREVIEW', + 'FULLSCREEN', + 'MODULAR', + 'NON_MODULAR', + 'VISIBLE', + 'NON_VISIBLE', + 'ROUTABLE', + 'NON_ROUTABLE', + 'PUBLISHED', + 'NON_PUBLISHED', + 'PLUGINS', + 'THEMES', + 'ALL', + 'FROM', + 'TO', + 'DROPZONE_CANCEL_UPLOAD', + 'DROPZONE_CANCEL_UPLOAD_CONFIRMATION', + 'DROPZONE_DEFAULT_MESSAGE', + 'DROPZONE_FALLBACK_MESSAGE', + 'DROPZONE_FALLBACK_TEXT', + 'DROPZONE_FILE_TOO_BIG', + 'DROPZONE_INVALID_FILE_TYPE', + 'DROPZONE_MAX_FILES_EXCEEDED', + 'DROPZONE_REMOVE_FILE', + 'DROPZONE_RESPONSE_ERROR' + ]; + + foreach ($strings as $string) { + $separator = (end($strings) === $string) ? '' : ','; + $translations .= '"' . $string . '": "' . htmlspecialchars($this->admin->translate('PLUGIN_ADMIN.' . $string)) . '"' . $separator; + } + + $translations .= '};'; + + $translations .= 'this.GravAdmin.translations.PLUGIN_FORM = {'; + $strings = ['RESOLUTION_MIN', 'RESOLUTION_MAX']; + foreach ($strings as $string) { + $separator = (end($strings) === $string) ? '' : ','; + $translations .= '"' . $string . '": "' . $this->admin->translate('PLUGIN_FORM.' . $string) . '"' . $separator; + } + + $translations .= '};'; + + // set the actual translations state back + $this->config->set('system.languages.translations', $translations_actual_state); + + $assets->addInlineJs($translations); + } + + /** + * Add the Admin Twig Extensions + */ + public function onTwigExtensions() + { + require_once __DIR__ . '/classes/Twig/AdminTwigExtension.php'; + + $this->grav['twig']->twig->addExtension(new AdminTwigExtension); + } + + /** + * Check if the current route is under the admin path + * + * @return bool + */ + public function isAdminPath() + { + $route = $this->uri->route(); + + return $route === $this->base || 0 === strpos($route, $this->base . '/'); + } + + public function onAdminAfterSave(Event $event) + { + // Special case to redirect after changing the admin route to avoid 'breaking' + $obj = $event['object']; + if (null !== $obj) { + $blueprint = $obj->blueprints()->getFilename(); + + if ($blueprint === 'admin/blueprints' && isset($obj->route) && $this->admin_route !== $obj->route) { + $redirect = preg_replace('/^' . str_replace('/','\/',$this->admin_route) . '/',$obj->route,$this->uri->path()); + $this->grav->redirect($redirect); + } + } + } + + /** + * Provide the tools for the Tools page, currently only direct install + * + * @return Event + */ + public function onAdminTools(Event $event) + { + $event['tools'] = array_merge($event['tools'], [$this->grav['language']->translate('PLUGIN_ADMIN.DIRECT_INSTALL')]); + return $event; + } + + public function onAdminDashboard() + { + $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-maintenance']; + $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-statistics']; + $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-notifications']; + $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-feed']; + $this->grav['twig']->plugins_hooked_dashboard_widgets_main[] = ['template' => 'dashboard-pages']; + } + + public function onOutputGenerated() + { + // Clear flash objects for previously uploaded files + // whenever the user switches page / reloads + // ignoring any JSON / extension call + if ($this->admin->task !== 'save' && empty($this->uri->extension())) { + // Discard any previously uploaded files session. + // and if there were any uploaded file, remove them from the filesystem + if ($flash = $this->session->getFlashObject('files-upload')) { + $flash = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($flash)); + foreach ($flash as $key => $value) { + if ($key !== 'tmp_name') { + continue; + } + @unlink($value); + } + } + } + } + + /** + * Initial stab at registering permissions (WIP) + * + * @param Event $e + */ + public function onAdminRegisterPermissions(Event $e) + { + $admin = $e['admin']; + $permissions = [ + 'admin.super' => 'boolean', + 'admin.login' => 'boolean', + 'admin.cache' => 'boolean', + 'admin.configuration' => 'boolean', + 'admin.configuration_system' => 'boolean', + 'admin.configuration_site' => 'boolean', + 'admin.configuration_media' => 'boolean', + 'admin.configuration_info' => 'boolean', + 'admin.settings' => 'boolean', + 'admin.pages' => 'boolean', + 'admin.maintenance' => 'boolean', + 'admin.statistics' => 'boolean', + 'admin.plugins' => 'boolean', + 'admin.themes' => 'boolean', + 'admin.users' => 'boolean', + ]; + $admin->addPermissions($permissions); + } + + /** + * Helper function to replace Pages::Types() + * and to provide an event to manipulate the data + * + * Dispatches 'onAdminPageTypes' event + * with 'types' data member which is a + * reference to the data + */ + public static function pagesTypes() + { + $types = Pages::types(); + + // First filter by configuration + $hideTypes = Grav::instance()['config']->get('plugins.admin.hide_page_types', []); + foreach ((array) $hideTypes as $type) { + unset($types[$type]); + } + + // Allow manipulating of the data by event + $e = new Event(['types' => &$types]); + Grav::instance()->fireEvent('onAdminPageTypes', $e); + + return $types; + } + + /** + * Helper function to replace Pages::modularTypes() + * and to provide an event to manipulate the data + * + * Dispatches 'onAdminModularPageTypes' event + * with 'types' data member which is a + * reference to the data + */ + public static function pagesModularTypes() + { + $types = Pages::modularTypes(); + + // First filter by configuration + $hideTypes = (array) Grav::instance()['config']->get('plugins.admin.hide_modular_page_types', []); + foreach ($hideTypes as $type) { + unset($types[$type]); + } + + // Allow manipulating of the data by event + $e = new Event(['types' => &$types]); + Grav::instance()->fireEvent('onAdminModularPageTypes', $e); + + return $types; + } +} diff --git a/user/plugins/admin/admin.yaml b/user/plugins/admin/admin.yaml new file mode 100644 index 0000000..ac72823 --- /dev/null +++ b/user/plugins/admin/admin.yaml @@ -0,0 +1,45 @@ +enabled: true +route: '/admin' +cache_enabled: false +theme: grav +logo_text: '' +body_classes: '' +content_padding: true +twofa_enabled: true +sidebar: + activate: tab + hover_delay: 100 + size: auto +dashboard: + days_of_stats: 7 +widgets: + dashboard-maintenance: true + dashboard-statistics: true + dashboard-notifications: true + dashboard-feed: true + dashboard-pages: true +pages: + show_parents: both +session: + timeout: 1800 +warnings: + delete_page: true +edit_mode: normal +frontend_preview_target: inline +show_github_msg: true +pages_list_display_field: title +google_fonts: false +admin_icons: line-awesome +enable_auto_updates_check: true +notifications: + feed: true + dashboard: true + plugins: true + themes: true +popularity: + enabled: true + ignore: ['/test*','/modular'] + history: + daily: 30 + monthly: 12 + visitors: 20 diff --git a/user/plugins/admin/assets/admin-dashboard.png b/user/plugins/admin/assets/admin-dashboard.png new file mode 100644 index 0000000..599743e Binary files /dev/null and b/user/plugins/admin/assets/admin-dashboard.png differ diff --git a/user/plugins/admin/blueprints.yaml b/user/plugins/admin/blueprints.yaml new file mode 100644 index 0000000..e74fb60 --- /dev/null +++ b/user/plugins/admin/blueprints.yaml @@ -0,0 +1,501 @@ +name: Admin Panel +version: 1.8.1 +description: Adds an advanced administration panel to manage your site +icon: empire +author: + name: Team Grav + email: devs@getgrav.org + url: http://getgrav.org +homepage: https://github.com/getgrav/grav-plugin-admin +keywords: admin, plugin, manager, panel +bugs: https://github.com/getgrav/grav-plugin-admin/issues +docs: https://github.com/getgrav/grav-plugin-admin/blob/develop/README.md +license: MIT + +dependencies: + - { name: grav, version: '>=1.4.5' } + - { name: form, version: '>=2.14.0' } + - { name: login, version: '>=2.7.0' } + - { name: email, version: '>=2.7.0' } + +form: + validation: loose + fields: + Basics: + type: section + title: Basics + underline: false + + enabled: + type: hidden + label: PLUGIN_ADMIN.PLUGIN_STATUS + highlight: 1 + default: 0 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + + cache_enabled: + type: toggle + label: PLUGIN_ADMIN.ADMIN_CACHING + help: PLUGIN_ADMIN.ADMIN_CACHING_HELP + highlight: 0 + options: + 1: PLUGIN_ADMIN.YES + 0: PLUGIN_ADMIN.NO + validate: + type: bool + + twofa_enabled: + type: toggle + label: PLUGIN_ADMIN.2FA_TITLE + help: PLUGIN_ADMIN.2FA_ENABLED_HELP + default: 1 + highlight: 1 + options: + 1: PLUGIN_ADMIN.YES + 0: PLUGIN_ADMIN.NO + validate: + type: bool + + route: + type: text + label: Administrator path + size: medium + placeholder: "Default route for administrator (relative to base)" + help: If you want to change the URL for the administrator, you can provide a path here + + logo_text: + type: text + label: Logo text + size: medium + placeholder: "Grav" + help: Text to display in place of the default Grav logo + + content_padding: + type: toggle + label: PLUGIN_ADMIN.CONTENT_PADDING + help: PLUGIN_ADMIN.CONTENT_PADDING_HELP + highlight: 1 + options: + 1: PLUGIN_ADMIN.YES + 0: PLUGIN_ADMIN.NO + validate: + type: bool + + body_classes: + type: text + label: Body classes + size: medium + help: Add a space separated name of custom body classes + + sidebar.activate: + type: select + label: Sidebar Activation + help: Control how the sidebar is activated + size: small + default: tab + options: + tab: Tab + hover: Hover + + sidebar.hover_delay: + type: text + size: x-small + append: millseconds + label: Hover delay + default: 500 + validate: + type: number + min: 1 + + + sidebar.size: + type: select + label: Sidebar Size + help: Control the width of the sidebar + size: medium + default: auto + options: + auto: Automatic width + small: Small width + + theme: + type: hidden + label: Theme + default: grav + + edit_mode: + type: select + label: Edit mode + size: small + default: normal + options: + normal: Normal + expert: Expert + help: Auto will use blueprint if available, if none found, it will use "Expert" mode. + + frontend_preview_target: + type: select + label: Preview pages target + size: medium + default: inline + options: + inline: Inline in Admin + _blank: New tab + _self: Current tab + + pages.show_parents: + type: select + size: medium + label: Parent dropdown + highlight: 1 + options: + both: Show slug and folder + folder: Show folder + fullpath: Show fullpath + + pages.parents_levels: + type: text + label: Parents Levels + size: small + help: The number of levels to show in parent select list + + google_fonts: + type: toggle + label: Use Google Fonts + highlight: 0 + default: 0 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Use Google custom fonts. Disable this to use Helvetica. Useful when using Cyrillic and other languages with unsupported characters. + + admin_icons: + type: select + size: medium + label: Icon Style + default: line-awesome + options: + line-awesome: Lighter Line Icons (LineAwesome) + font-awesome: Darker Solid Icons (FontAwesome) + + show_beta_msg: + type: hidden + + show_github_msg: + type: toggle + label: Show GitHub Link + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Show the "Found an issue? Please report it on GitHub." message. + + pages_list_display_field: + type: text + size: small + label: Pages List Display Field + help: "Field of the page to use in the list of pages if present. Defaults/Fallback to title." + + enable_auto_updates_check: + type: toggle + label: Automatically check for updates + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Shows an informative message, in the admin panel, when an update is available. + + session.timeout: + type: text + size: small + label: Session Timeout + append: secs + help: "Sets the session timeout in seconds" + validate: + type: number + min: 1 + + warnings.delete_page: + type: toggle + label: Warn on page delete + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Ask the user confirmation when deleting a page + + hide_page_types: + type: array + label: Hide page types in Admin + value_only: true + + hide_modular_page_types: + type: array + label: Hide modular page types in Admin + value_only: true + + MediaResize: + type: section + title: Page Media Image Resizer + underline: true + + MediaResizeNote: + type: spacer + text: PLUGIN_ADMIN.PAGEMEDIA_RESIZER + markdown: true + + pagemedia.resize_width: + type: number + size: x-small + append: pixels + label: Resize Width + default: 0 + validate: + type: number + help: Resize wide images down to the set value + + pagemedia.resize_height: + type: number + size: x-small + append: pixels + label: Resize Height + default: 0 + validate: + type: number + help: Resize tall images down to the set value + + pagemedia.res_min_width: + type: number + size: x-small + append: pixels + label: Resolution Min Width + default: 0 + validate: + type: number + help: The minimum width allowed for an image to be added + + pagemedia.res_min_height: + type: number + size: x-small + append: pixels + label: Resolution Min Height + default: 0 + validate: + type: number + help: The minimum height allowed for an image to be added + + pagemedia.res_max_width: + type: number + size: x-small + append: pixels + label: Resolution Max Width + default: 0 + validate: + type: number + help: The maximum width allowed for an image to be added + + pagemedia.res_max_height: + type: number + size: x-small + append: pixels + label: Resolution Max Height + default: 0 + validate: + type: number + help: The maximum height allowed for an image to be added + + + pagemedia.resize_quality: + type: number + size: x-small + append: 0...1 + label: Resize Quality + default: 0.8 + validate: + type: number + step: 0.01 + help: The quality to use when resizing an image. Between 0 and 1 value. + + Dashboard: + type: section + title: Dashboard + underline: true + + widgets.dashboard-maintenance: + type: toggle + label: Maintenance Widget + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Display dashboard maintenance widget + + widgets.dashboard-statistics: + type: toggle + label: Statistics Widget + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Display dashboard statistics widget + + widgets.dashboard-notifications: + type: toggle + label: Notifications Feed Widget + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Display dashboard notifications feed widget + + widgets.dashboard-feed: + type: toggle + label: News Feed Widget + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Display dashboard news feed widget + + widgets.dashboard-pages: + type: toggle + label: Latest Pages Widget + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Display dashboard latest pages widget + + Notifications: + type: section + title: Notifications + underline: true + + notifications.feed: + type: toggle + label: Feed Notifications + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Display feed-based notifications + + notifications.dashboard: + type: toggle + label: Dashboard Notifications + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Display dashboard-based notifications + + notifications.plugins: + type: toggle + label: Plugins Notifications + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Display plugins-targeted notifications + + notifications.themes: + type: toggle + label: Themes Notifications + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Display themes-targeted notifications + + Popularity: + type: section + title: Popularity + underline: true + + popularity.enabled: + type: toggle + label: Visitor tracking + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + help: Enable the visitors stats collecting feature + + dashboard.days_of_stats: + type: text + label: Days of stats + append: days + size: x-small + default: 7 + help: Keep stats for the specified number of days, then drop them + validate: + type: int + + popularity.ignore: + type: array + label: Ignore + size: large + help: "URLs to ignore" + default: ['/test*','/modular'] + value_only: true + placeholder_value: /ignore-this-route + + popularity.history.daily: + type: hidden + label: Daily history + default: 30 + + popularity.history.monthly: + type: hidden + label: Monthly history + default: 12 + + popularity.history.visitors: + type: hidden + label: Visitors history + default: 20 diff --git a/user/plugins/admin/blueprints/admin/pages/modular_new.yaml b/user/plugins/admin/blueprints/admin/pages/modular_new.yaml new file mode 100644 index 0000000..85aa7b0 --- /dev/null +++ b/user/plugins/admin/blueprints/admin/pages/modular_new.yaml @@ -0,0 +1,52 @@ +rules: + slug: + pattern: '[a-zA-Zа-яA-Я0-9_\-]+' + min: 1 + max: 200 + +form: + validation: loose + fields: + + section: + type: section + title: PLUGIN_ADMIN.ADD_MODULAR_CONTENT + + title: + type: text + label: PLUGIN_ADMIN.PAGE_TITLE + validate: + required: true + + folder: + type: text + label: PLUGIN_ADMIN.FOLDER_NAME + validate: + rule: slug + required: true + + route: + type: parents + label: PLUGIN_ADMIN.PAGE + classes: fancy + validate: + required: true + + name: + type: select + classes: fancy + label: PLUGIN_ADMIN.MODULAR_TEMPLATE + help: PLUGIN_ADMIN.PAGE_FILE_HELP + default: default + data-options@: '\Grav\Plugin\AdminPlugin::pagesModularTypes' + validate: + required: true + + modular: + type: hidden + default: 1 + validate: + type: bool + + blueprint: + type: blueprint diff --git a/user/plugins/admin/blueprints/admin/pages/modular_raw.yaml b/user/plugins/admin/blueprints/admin/pages/modular_raw.yaml new file mode 100644 index 0000000..abd2193 --- /dev/null +++ b/user/plugins/admin/blueprints/admin/pages/modular_raw.yaml @@ -0,0 +1,101 @@ +rules: + slug: + pattern: '[a-zA-Zа-яA-Я0-9_\-]+' + min: 1 + max: 200 + +form: + validation: loose + fields: + + tabs: + type: tabs + active: 1 + + fields: + content: + type: tab + title: PLUGIN_ADMIN.CONTENT + + fields: + frontmatter: + classes: frontmatter + type: editor + label: PLUGIN_ADMIN.FRONTMATTER + autofocus: true + codemirror: + mode: 'yaml' + indentUnit: 4 + autofocus: true + indentWithTabs: false + lineNumbers: true + styleActiveLine: true + gutters: ['CodeMirror-lint-markers'] + lint: true + + content: + type: markdown + + header.media_order: + type: pagemedia + label: PLUGIN_ADMIN.PAGE_MEDIA + + options: + type: tab + title: PLUGIN_ADMIN.OPTIONS + + fields: + + columns: + type: columns + + fields: + column1: + type: column + + fields: + + ordering: + type: toggle + label: PLUGIN_ADMIN.FOLDER_NUMERIC_PREFIX + help: PLUGIN_ADMIN.FOLDER_NUMERIC_PREFIX_HELP + highlight: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + + folder: + type: text + label: PLUGIN_ADMIN.FILENAME + validate: + rule: slug + required: true + + route: + type: parents + label: PLUGIN_ADMIN.PARENT + classes: fancy + validate: + required: true + + name: + type: select + classes: fancy + label: PLUGIN_ADMIN.MODULAR_TEMPLATE + default: default + data-options@: '\Grav\Plugin\AdminPlugin::pagesModularTypes' + validate: + required: true + + column2: + type: column + + fields: + order: + type: order + label: PLUGIN_ADMIN.ORDERING + + blueprint: + type: blueprint diff --git a/user/plugins/admin/blueprints/admin/pages/move.yaml b/user/plugins/admin/blueprints/admin/pages/move.yaml new file mode 100644 index 0000000..89fa414 --- /dev/null +++ b/user/plugins/admin/blueprints/admin/pages/move.yaml @@ -0,0 +1,7 @@ +form: + validation: loose + fields: + route: + type: parents + label: PLUGIN_ADMIN.PARENT + classes: fancy diff --git a/user/plugins/admin/blueprints/admin/pages/new.yaml b/user/plugins/admin/blueprints/admin/pages/new.yaml new file mode 100644 index 0000000..d62c6ae --- /dev/null +++ b/user/plugins/admin/blueprints/admin/pages/new.yaml @@ -0,0 +1,62 @@ +rules: + slug: + pattern: '[a-zA-Zа-яA-Я0-9_\-]+' + min: 1 + max: 200 + +form: + validation: loose + fields: + + section: + type: section + title: PLUGIN_ADMIN.ADD_PAGE + + title: + type: text + label: PLUGIN_ADMIN.PAGE_TITLE + help: PLUGIN_ADMIN.PAGE_TITLE_HELP + validate: + required: true + + folder: + type: text + label: PLUGIN_ADMIN.FOLDER_NAME + help: PLUGIN_ADMIN.FOLDER_NAME_HELP + validate: + rule: slug + required: true + + route: + type: parents + label: PLUGIN_ADMIN.PARENT_PAGE + classes: fancy + validate: + required: true + + name: + type: select + classes: fancy + label: PLUGIN_ADMIN.PAGE_FILE + help: PLUGIN_ADMIN.PAGE_FILE_HELP + data-options@: '\Grav\Plugin\AdminPlugin::pagesTypes' + data-default@: '\Grav\Plugin\Admin\Admin::getLastPageName' + validate: + required: true + + visible: + type: toggle + label: PLUGIN_ADMIN.VISIBLE + help: PLUGIN_ADMIN.VISIBLE_HELP + highlight: '' + default: '' + options: + '': Auto + 1: PLUGIN_ADMIN.YES + 0: PLUGIN_ADMIN.NO + validate: + type: bool + required: true + + blueprint: + type: blueprint diff --git a/user/plugins/admin/blueprints/admin/pages/new_folder.yaml b/user/plugins/admin/blueprints/admin/pages/new_folder.yaml new file mode 100644 index 0000000..9db58f2 --- /dev/null +++ b/user/plugins/admin/blueprints/admin/pages/new_folder.yaml @@ -0,0 +1,31 @@ +rules: + slug: + pattern: '[a-zA-Zа-яA-Я0-9_\-]+' + min: 1 + max: 200 + +form: + validation: loose + fields: + + section: + type: section + title: PLUGIN_ADMIN.ADD_FOLDER + + folder: + type: text + label: PLUGIN_ADMIN.FOLDER_NAME + help: PLUGIN_ADMIN.FOLDER_NAME_HELP + validate: + rule: slug + required: true + + route: + type: parents + label: PLUGIN_ADMIN.PARENT_PAGE + classes: fancy + validate: + required: true + + blueprint: + type: blueprint diff --git a/user/plugins/admin/blueprints/admin/pages/raw.yaml b/user/plugins/admin/blueprints/admin/pages/raw.yaml new file mode 100644 index 0000000..3ddf2ac --- /dev/null +++ b/user/plugins/admin/blueprints/admin/pages/raw.yaml @@ -0,0 +1,103 @@ +rules: + slug: + pattern: '[a-zA-Zа-яA-Я0-9_\-]+' + min: 1 + max: 200 + +form: + validation: loose + fields: + + tabs: + type: tabs + active: 1 + + fields: + content: + type: tab + title: PLUGIN_ADMIN.CONTENT + + fields: + frontmatter: + classes: frontmatter + type: editor + label: PLUGIN_ADMIN.FRONTMATTER + autofocus: true + codemirror: + mode: 'yaml' + indentUnit: 4 + autofocus: true + indentWithTabs: false + lineNumbers: true + styleActiveLine: true + gutters: ['CodeMirror-lint-markers'] + lint: true + + content: + type: markdown + + header.media_order: + type: pagemedia + label: PLUGIN_ADMIN.PAGE_MEDIA + + options: + type: tab + title: PLUGIN_ADMIN.OPTIONS + + fields: + + columns: + type: columns + + fields: + column1: + type: column + + fields: + + ordering: + type: toggle + label: PLUGIN_ADMIN.FOLDER_NUMERIC_PREFIX + help: PLUGIN_ADMIN.FOLDER_NUMERIC_PREFIX_HELP + highlight: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + + folder: + type: text + label: PLUGIN_ADMIN.FOLDER_NAME + help: PLUGIN_ADMIN.FOLDER_NAME_HELP + validate: + rule: slug + required: true + + route: + type: parents + label: PLUGIN_ADMIN.PARENT + classes: fancy + validate: + required: true + + name: + type: select + classes: fancy + label: PLUGIN_ADMIN.DISPLAY_TEMPLATE + help: PLUGIN_ADMIN.DISPLAY_TEMPLATE_HELP + default: default + data-options@: '\Grav\Plugin\AdminPlugin::pagesTypes' + validate: + required: true + + column2: + type: column + + fields: + order: + type: order + label: PLUGIN_ADMIN.ORDERING + + blueprint: + type: blueprint diff --git a/user/plugins/admin/blueprints/config/media.yaml b/user/plugins/admin/blueprints/config/media.yaml new file mode 100644 index 0000000..ba55868 --- /dev/null +++ b/user/plugins/admin/blueprints/config/media.yaml @@ -0,0 +1,36 @@ +title: PLUGIN_ADMIN.MEDIA +form: + validation: loose + fields: + 'types': + name: medias + type: list + label: PLUGIN_ADMIN.MEDIA_TYPES + style: vertical + key: extension + controls: both + collapsed: true + + fields: + .extension: + type: key + label: PLUGIN_ADMIN.FILE_EXTENSION + .type: + type: text + label: PLUGIN_ADMIN.TYPE + .thumb: + type: text + label: PLUGIN_ADMIN.THUMB + .mime: + type: text + label: PLUGIN_ADMIN.MIME_TYPE + validate: + type: lower + .image: + type: textarea + yaml: true + label: PLUGIN_ADMIN.IMAGE_OPTIONS + validate: + type: yaml + + diff --git a/user/plugins/admin/classes/Twig/AdminTwigExtension.php b/user/plugins/admin/classes/Twig/AdminTwigExtension.php new file mode 100644 index 0000000..516ff2b --- /dev/null +++ b/user/plugins/admin/classes/Twig/AdminTwigExtension.php @@ -0,0 +1,176 @@ +grav = Grav::instance(); + $this->lang = $this->grav['user']->language; + } + + public function getFilters() + { + return [ + new \Twig_SimpleFilter('tu', [$this, 'tuFilter']), + new \Twig_SimpleFilter('toYaml', [$this, 'toYamlFilter']), + new \Twig_SimpleFilter('fromYaml', [$this, 'fromYamlFilter']), + new \Twig_SimpleFilter('adminNicetime', [$this, 'adminNicetimeFilter']), + ]; + } + + public function getFunctions() + { + return [ + new \Twig_SimpleFunction('getPageUrl', [$this, 'getPageUrl'], ['needs_context' => true]), + new \Twig_SimpleFunction('clone', [$this, 'cloneFunc']), + ]; + } + + public function cloneFunc($obj) + { + return clone $obj; + } + + public function getPageUrl($context, Page $page) + { + $page_route = trim($page->rawRoute(), '/'); + $page_lang = $page->language(); + $base_url = $context['base_url']; + $base_url_simple = $context['base_url_simple']; + $admin_lang = Grav::instance()['session']->admin_lang ?: 'en'; + + if ($page_lang && $page_lang !== $admin_lang) { + $page_url = $base_url_simple . '/' . $page_lang . '/' . $context['admin_route'] . '/pages/' . $page_route; + } else { + $page_url = $base_url . '/pages/' . $page_route; + } + + return $page_url; + } + + public function tuFilter() + { + $args = func_get_args(); + $numargs = count($args); + $lang = null; + + if (($numargs === 3 && is_array($args[1])) || ($numargs === 2 && !is_array($args[1]))) { + $lang = array_pop($args); + } elseif ($numargs === 2 && is_array($args[1])) { + $subs = array_pop($args); + $args = array_merge($args, $subs); + } + + return $this->grav['admin']->translate($args, $lang); + } + + public function toYamlFilter($value, $inline = true) + { + return Yaml::dump($value, $inline); + + } + + public function fromYamlFilter($value) + { + $yaml = new Parser(); + return $yaml->parse($value); + } + + public function adminNicetimeFilter($date, $long_strings = true) + { + if (empty($date)) { + return $this->grav['admin']->translate('NICETIME.NO_DATE_PROVIDED', null, true); + } + + if ($long_strings) { + $periods = [ + 'NICETIME.SECOND', + 'NICETIME.MINUTE', + 'NICETIME.HOUR', + 'NICETIME.DAY', + 'NICETIME.WEEK', + 'NICETIME.MONTH', + 'NICETIME.YEAR', + 'NICETIME.DECADE' + ]; + } else { + $periods = [ + 'NICETIME.SEC', + 'NICETIME.MIN', + 'NICETIME.HR', + 'NICETIME.DAY', + 'NICETIME.WK', + 'NICETIME.MO', + 'NICETIME.YR', + 'NICETIME.DEC' + ]; + } + + $lengths = ['60', '60', '24', '7', '4.35', '12', '10']; + + $now = time(); + + // check if unix timestamp + if ((string)(int)$date === (string)$date) { + $unix_date = $date; + } else { + $unix_date = strtotime($date); + } + + // check validity of date + if (empty($unix_date)) { + return $this->grav['admin']->translate('NICETIME.BAD_DATE', null, true); + } + + // is it future date or past date + if ($now > $unix_date) { + $difference = $now - $unix_date; + $tense = $this->grav['admin']->translate('NICETIME.AGO', null, true); + + } else { + $difference = $unix_date - $now; + $tense = $this->grav['admin']->translate('NICETIME.FROM_NOW', null, true); + } + + $len = count($lengths) - 1; + for ($j = 0; $difference >= $lengths[$j] && $j < $len; $j++) { + $difference /= $lengths[$j]; + } + + $difference = round($difference); + + if ($difference !== 1) { + $periods[$j] .= '_PLURAL'; + } + + if ($this->grav['language']->getTranslation($this->grav['user']->language, + $periods[$j] . '_MORE_THAN_TWO') + ) { + if ($difference > 2) { + $periods[$j] .= '_MORE_THAN_TWO'; + } + } + + $periods[$j] = $this->grav['admin']->translate($periods[$j], null, true); + + return "{$difference} {$periods[$j]} {$tense}"; + } + +} diff --git a/user/plugins/admin/classes/admin.php b/user/plugins/admin/classes/admin.php new file mode 100644 index 0000000..b3951ca --- /dev/null +++ b/user/plugins/admin/classes/admin.php @@ -0,0 +1,1792 @@ +grav = $grav; + $this->base = $base; + $this->location = $location; + $this->route = $route; + $this->uri = $this->grav['uri']; + $this->session = $this->grav['session']; + $this->user = $this->grav['user']; + $this->permissions = []; + $language = $this->grav['language']; + + // Load utility class + if ($language->enabled()) { + $this->multilang = true; + $this->languages_enabled = $this->grav['config']->get('system.languages.supported', []); + + //Set the currently active language for the admin + $language = $this->grav['uri']->param('lang'); + if (!$language) { + if (!$this->session->admin_lang) { + $this->session->admin_lang = $this->grav['language']->getLanguage(); + } + $language = $this->session->admin_lang; + } + $this->grav['language']->setActive($language ?: 'en'); + } else { + $this->grav['language']->setActive('en'); + $this->multilang = false; + } + + } + + /** + * Return the languages available in the admin + * + * @return array + */ + public static function adminLanguages() + { + $languages = []; + + $path = Grav::instance()['locator']->findResource('plugins://admin/languages'); + + /** @var \DirectoryIterator $directory */ + foreach (new \DirectoryIterator($path) as $file) { + if ($file->isDir() || $file->isDot() || Utils::startsWith($file->getBasename(), '.')) { + continue; + } + + $lang = basename($file->getBasename(), '.yaml'); + + $languages[$lang] = LanguageCodes::getNativeName($lang); + + } + + // sort languages + asort($languages); + + return $languages; + } + + /** + * Return the found configuration blueprints + * + * @return array + */ + public static function configurations() + { + $configurations = []; + + /** @var UniformResourceIterator $iterator */ + $iterator = Grav::instance()['locator']->getIterator('blueprints://config'); + + foreach ($iterator as $file) { + if ($file->isDir() || !preg_match('/^[^.].*.yaml$/', $file->getFilename())) { + continue; + } + $configurations[] = basename($file->getBasename(), '.yaml'); + } + + return $configurations; + } + + /** + * Return the tools found + * + * @return array + */ + public static function tools() + { + $tools = []; + Grav::instance()->fireEvent('onAdminTools', new Event(['tools' => &$tools])); + + return $tools; + } + + /** + * Return the languages available in the site + * + * @return array + */ + public static function siteLanguages() + { + $languages = []; + $lang_data = (array) Grav::instance()['config']->get('system.languages.supported', []); + + foreach ($lang_data as $index => $lang) { + $languages[$lang] = LanguageCodes::getNativeName($lang); + } + + return $languages; + } + + /** + * Static helper method to return the admin form nonce + * + * @return string + */ + public static function getNonce() + { + $action = 'admin-form'; + + return Utils::getNonce($action); + } + + /** + * Static helper method to return the last used page name + * + * @return string + */ + public static function getLastPageName() + { + return Grav::instance()['session']->lastPageName ?: 'default'; + } + + /** + * Static helper method to return the last used page route + * + * @return string + */ + public static function getLastPageRoute() + { + return Grav::instance()['session']->lastPageRoute ?: self::route(); + } + + /** + * Static helper method to return current route. + * + * @return string + */ + public static function route() + { + $pages = Grav::instance()['pages']; + $route = '/' . ltrim(Grav::instance()['admin']->route, '/'); + + /** @var Page $page */ + $page = $pages->dispatch($route); + $parent_route = null; + if ($page) { + /** @var Page $parent */ + $parent = $page->parent(); + $parent_route = $parent->rawRoute(); + } + + return $parent_route; + } + + public static function getTempDir() + { + try { + $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true); + } catch (\Exception $e) { + $tmp_dir = Grav::instance()['locator']->findResource('cache://', true, true) . '/tmp'; + } + + return $tmp_dir; + } + + public static function getPageMedia() + { + $files = []; + $grav = Grav::instance(); + + $pages = $grav['pages']; + $route = '/' . ltrim($grav['admin']->route, '/'); + + /** @var Page $page */ + $page = $pages->dispatch($route); + $parent_route = null; + if ($page) { + $media = $page->media()->all(); + $files = array_keys($media); + } + return $files; + + } + + /** + * Get current session. + * + * @return Session + */ + public function session() + { + return $this->session; + } + + /** + * Fetch and delete messages from the session queue. + * + * @param string $type + * + * @return array + */ + public function messages($type = null) + { + /** @var Message $messages */ + $messages = $this->grav['messages']; + + return $messages->fetch($type); + } + + /** + * Authenticate user. + * + * @param array $credentials User credentials. + */ + public function authenticate($credentials, $post) + { + /** @var Login $login */ + $login = $this->grav['login']; + + // Remove login nonce from the form. + $credentials = array_diff_key($credentials, ['admin-nonce' => true]); + $twofa = $this->grav['config']->get('plugins.admin.twofa_enabled', false); + + $rateLimiter = $login->getRateLimiter('login_attempts'); + + $userKey = isset($credentials['username']) ? (string)$credentials['username'] : ''; + $ipKey = Uri::ip(); + $redirect = isset($post['redirect']) ? $post['redirect'] : $this->uri->route(); + + // Check if the current IP has been used in failed login attempts. + $attempts = count($rateLimiter->getAttempts($ipKey, 'ip')); + + $rateLimiter->registerRateLimitedAction($ipKey, 'ip')->registerRateLimitedAction($userKey); + + // Check rate limit for both IP and user, but allow each IP a single try even if user is already rate limited. + if ($rateLimiter->isRateLimited($ipKey, 'ip') || ($attempts && $rateLimiter->isRateLimited($userKey))) { + $this->setMessage($this->translate(['PLUGIN_LOGIN.TOO_MANY_LOGIN_ATTEMPTS', $rateLimiter->getInterval()]), 'error'); + + $this->grav->redirect('/'); + } + + // Fire Login process. + $event = $login->login( + $credentials, + ['admin' => true, 'twofa' => $twofa], + ['authorize' => 'admin.login', 'return_event' => true] + ); + $user = $event->getUser(); + + if ($user->authenticated) { + $rateLimiter->resetRateLimit($ipKey, 'ip')->resetRateLimit($userKey); + if ($user->authorized) { + $event->defMessage('PLUGIN_ADMIN.LOGIN_LOGGED_IN', 'info'); + + $event->defRedirect($redirect); + } else { + $this->session->redirect = $redirect; + + $event->defRedirect($this->uri->route()); + } + } else { + if ($user->authorized) { + $event->defMessage('PLUGIN_LOGIN.ACCESS_DENIED', 'error'); + } else { + $event->defMessage('PLUGIN_LOGIN.LOGIN_FAILED', 'error'); + } + } + + $event->defRedirect($this->uri->route()); + + $message = $event->getMessage(); + if ($message) { + $this->setMessage($this->translate($message), $event->getMessageType()); + } + + $redirect = $event->getRedirect(); + + $this->grav->redirect($redirect, $event->getRedirectCode()); + } + + /** + * Check Two-Factor Authentication. + */ + public function twoFa($data, $post) + { + /** @var Login $login */ + $login = $this->grav['login']; + + /** @var TwoFactorAuth $twoFa */ + $twoFa = $login->twoFactorAuth(); + $user = $this->grav['user']; + + $code = isset($data['2fa_code']) ? $data['2fa_code'] : null; + + $secret = isset($user->twofa_secret) ? $user->twofa_secret : null; + + if (!$code || !$secret || !$twoFa->verifyCode($secret, $code)) { + $login->logout(['admin' => true]); + + $this->grav['session']->setFlashCookieObject(Admin::TMP_COOKIE_NAME, ['message' => $this->translate('PLUGIN_ADMIN.2FA_FAILED'), 'status' => 'error']); + + $this->grav->redirect($this->uri->route(), 303); + } + + $this->setMessage($this->translate('PLUGIN_ADMIN.LOGIN_LOGGED_IN'), 'info'); + + $user->authorized = true; + + $this->grav->redirect($post['redirect']); + } + + /** + * Logout from admin. + */ + public function Logout($data, $post) + { + /** @var Login $login */ + $login = $this->grav['login']; + + $event = $login->logout(['admin' => true], ['return_event' => true]); + + $event->defMessage('PLUGIN_ADMIN.LOGGED_OUT', 'info'); + $message = $event->getMessage(); + if ($message) { + $this->grav['session']->setFlashCookieObject(Admin::TMP_COOKIE_NAME, ['message' => $this->translate($message), 'status' => $event->getMessageType()]); + } + + $this->grav->redirect($this->base); + } + + /** + * @return bool + */ + public static function doAnyUsersExist() + { + // check for existence of a user account + $account_dir = $file_path = Grav::instance()['locator']->findResource('account://'); + $user_check = glob($account_dir . '/*.yaml'); + + return $user_check ? true : false; + } + + /** + * Add message into the session queue. + * + * @param string $msg + * @param string $type + */ + public function setMessage($msg, $type = 'info') + { + /** @var Message $messages */ + $messages = $this->grav['messages']; + $messages->add($msg, $type); + } + + public function addTempMessage($msg, $type) + { + $this->temp_messages[] = ['message' => $msg, 'scope' => $type]; + } + + public function getTempMessages() + { + return $this->temp_messages; + } + + /** + * Translate a string to the user-defined language + * + * @param array|mixed $args + * + * @param mixed $languages + * + * @return string + */ + public static function translate($args, $languages = null) + { + $grav = Grav::instance(); + + if (is_array($args)) { + $lookup = array_shift($args); + } else { + $lookup = $args; + $args = []; + } + + if (!$languages) { + if ($grav['config']->get('system.languages.translations_fallback', true)) { + $languages = $grav['language']->getFallbackLanguages(); + } else { + $languages = (array)$grav['language']->getDefault(); + } + $languages = $grav['user']->authenticated ? [ $grav['user']->language ] : $languages; + } else { + $languages = (array)$languages; + } + + foreach ((array)$languages as $lang) { + $translation = $grav['language']->getTranslation($lang, $lookup); + + if (!$translation) { + $language = $grav['language']->getDefault() ?: 'en'; + $translation = $grav['language']->getTranslation($language, $lookup); + } + + if (!$translation) { + $language = 'en'; + $translation = $grav['language']->getTranslation($language, $lookup); + } + + if ($translation) { + if (count($args) >= 1) { + return vsprintf($translation, $args); + } + + return $translation; + } + } + + return $lookup; + } + + /** + * Checks user authorisation to the action. + * + * @param string|string[] $action + * + * @return bool + */ + public function authorize($action = 'admin.login') + { + $action = (array)$action; + + foreach ($action as $a) { + if ($this->user->authorize($a)) { + return true; + } + } + + return false; + } + + /** + * Gets configuration data. + * + * @param string $type + * @param array $post + * + * @return mixed + * @throws \RuntimeException + */ + public function data($type, array $post = []) + { + static $data = []; + + if (isset($data[$type])) { + return $data[$type]; + } + + if (!$post) { + $post = isset($_POST['data']) ? $_POST['data'] : []; + } + + // Check to see if a data type is plugin-provided, before looking into core ones + $event = $this->grav->fireEvent('onAdminData', new Event(['type' => &$type])); + if ($event && isset($event['data_type'])) { + return $event['data_type']; + } + + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + $filename = $locator->findResource("config://{$type}.yaml", true, true); + $file = CompiledYamlFile::instance($filename); + + if (preg_match('|plugins/|', $type)) { + /** @var Plugins $plugins */ + $plugins = $this->grav['plugins']; + $obj = $plugins->get(preg_replace('|plugins/|', '', $type)); + + if (!$obj) { + return []; + } + + $obj->merge($post); + $obj->file($file); + + $data[$type] = $obj; + } elseif (preg_match('|themes/|', $type)) { + /** @var Themes $themes */ + $themes = $this->grav['themes']; + $obj = $themes->get(preg_replace('|themes/|', '', $type)); + + if (!$obj) { + return []; + } + + $obj->merge($post); + $obj->file($file); + + $data[$type] = $obj; + } elseif (preg_match('|users/|', $type)) { + $obj = User::load(preg_replace('|users/|', '', $type)); + $obj->merge($post); + + $data[$type] = $obj; + } elseif (preg_match('|user/|', $type)) { + $obj = User::load(preg_replace('|user/|', '', $type)); + $obj->merge($post); + + $data[$type] = $obj; + } elseif (preg_match('|config/|', $type)) { + $type = preg_replace('|config/|', '', $type); + $blueprints = $this->blueprints("config/{$type}"); + $config = $this->grav['config']; + $obj = new Data\Data($config->get($type, []), $blueprints); + $obj->merge($post); + + // FIXME: We shouldn't allow user to change configuration files in system folder! + $filename = $this->grav['locator']->findResource("config://{$type}.yaml") + ?: $this->grav['locator']->findResource("config://{$type}.yaml", true, true); + $file = CompiledYamlFile::instance($filename); + $obj->file($file); + $data[$type] = $obj; + } elseif (preg_match('|media-manager/|', $type)) { + $filename = base64_decode(preg_replace('|media-manager/|', '', $type)); + + $file = File::instance($filename); + + $obj = new \StdClass(); + $obj->title = $file->basename(); + $obj->path = $file->filename(); + $obj->file = $file; + $obj->page = $this->grav['pages']->get(dirname($obj->path)); + + $filename = pathinfo($obj->title)['filename']; + $filename = str_replace(['@3x', '@2x'], '', $filename); + if (isset(pathinfo($obj->title)['extension'])) { + $filename .= '.' . pathinfo($obj->title)['extension']; + } + + if ($obj->page && isset($obj->page->media()[$filename])) { + $obj->metadata = new Data\Data($obj->page->media()[$filename]->metadata()); + } + + $data[$type] = $obj; + } else { + throw new \RuntimeException("Data type '{$type}' doesn't exist!"); + } + + return $data[$type]; + } + + protected function hasErrorMessage() + { + $msgs = $this->grav['messages']->all(); + foreach ($msgs as $msg) { + if (isset($msg['scope']) && $msg['scope'] === 'error') { + return true; + } + } + return false; + } + + /** + * Returns blueprints for the given type. + * + * @param string $type + * + * @return Data\Blueprint + */ + public function blueprints($type) + { + if ($this->blueprints === null) { + $this->blueprints = new Data\Blueprints('blueprints://'); + } + + return $this->blueprints->get($type); + } + + /** + * Converts dot notation to array notation. + * + * @param string $name + * + * @return string + */ + public function field($name) + { + $path = explode('.', $name); + + return array_shift($path) . ($path ? '[' . implode('][', $path) . ']' : ''); + } + + /** + * Get all routes. + * + * @param bool $unique + * + * @return array + */ + public function routes($unique = false) + { + /** @var Pages $pages */ + $pages = $this->grav['pages']; + + if ($unique) { + $routes = array_unique($pages->routes()); + } else { + $routes = $pages->routes(); + } + + return $routes; + } + + /** + * Count the pages + * + * @return array + */ + public function pagesCount() + { + if (!$this->pages_count) { + $this->pages_count = count($this->grav['pages']->all()); + } + + return $this->pages_count; + } + + /** + * Get all template types + * + * @return array + */ + public function types() + { + return Pages::types(); + } + + /** + * Get all modular template types + * + * @return array + */ + public function modularTypes() + { + return Pages::modularTypes(); + } + + /** + * Get all access levels + * + * @return array + */ + public function accessLevels() + { + if (method_exists($this->grav['pages'], 'accessLevels')) { + return $this->grav['pages']->accessLevels(); + } + + return []; + } + + public function license($package_slug) + { + return Licenses::get($package_slug); + } + + /** + * Generate an array of dependencies for a package, used to generate a list of + * packages that can be removed when removing a package. + * + * @param string $slug The package slug + * + * @return array|bool + */ + public function dependenciesThatCanBeRemovedWhenRemoving($slug) + { + $gpm = $this->gpm(); + if (!$gpm) { + return false; + } + + $dependencies = []; + + $package = $this->getPackageFromGPM($slug); + + if ($package) { + if ($package->dependencies) { + foreach ($package->dependencies as $dependency) { +// if (count($gpm->getPackagesThatDependOnPackage($dependency)) > 1) { +// continue; +// } + if (isset($dependency['name'])) { + $dependency = $dependency['name']; + } + + if (!in_array($dependency, $dependencies, true)) { + if (!in_array($dependency, ['admin', 'form', 'login', 'email', 'php'])) { + $dependencies[] = $dependency; + } + } + } + } + } + + return $dependencies; + } + + /** + * Get the GPM instance + * + * @return GPM The GPM instance + */ + public function gpm() + { + if (!$this->gpm) { + try { + $this->gpm = new GPM(); + } catch (\Exception $e) { + } + } + + return $this->gpm; + } + + public function getPackageFromGPM($package_slug) + { + $package = $this->plugins(true)[$package_slug]; + if (!$package) { + $package = $this->themes(true)[$package_slug]; + } + + return $package; + } + + /** + * Get all plugins. + * + * @param bool $local + * + * @return mixed + */ + public function plugins($local = true) + { + $gpm = $this->gpm(); + + if (!$gpm) { + return false; + } + + if ($local) { + return $gpm->getInstalledPlugins(); + } + + $plugins = $gpm->getRepositoryPlugins(); + if ($plugins) { + return $plugins->filter(function ($package, $slug) use ($gpm) { + return !$gpm->isPluginInstalled($slug); + }); + } + + return []; + } + + /** + * Get all themes. + * + * @param bool $local + * + * @return mixed + */ + public function themes($local = true) + { + $gpm = $this->gpm(); + + if (!$gpm) { + return false; + } + + if ($local) { + return $gpm->getInstalledThemes(); + } + + $themes = $gpm->getRepositoryThemes(); + if ($themes) { + return $themes->filter(function ($package, $slug) use ($gpm) { + return !$gpm->isThemeInstalled($slug); + }); + } + + return []; + } + + /** + * Get list of packages that depend on the passed package slug + * + * @param string $slug The package slug + * + * @return array|bool + */ + public function getPackagesThatDependOnPackage($slug) + { + $gpm = $this->gpm(); + if (!$gpm) { + return false; + } + + return $gpm->getPackagesThatDependOnPackage($slug); + } + + /** + * Check the passed packages list can be updated + * + * @param $packages + * + * @throws \Exception + * @return bool + */ + public function checkPackagesCanBeInstalled($packages) + { + $gpm = $this->gpm(); + if (!$gpm) { + return false; + } + + $this->gpm->checkPackagesCanBeInstalled($packages); + + return true; + } + + /** + * Get an array of dependencies needed to be installed or updated for a list of packages + * to be installed. + * + * @param array $packages The packages slugs + * + * @return array|bool + */ + public function getDependenciesNeededToInstall($packages) + { + $gpm = $this->gpm(); + if (!$gpm) { + return false; + } + + return $this->gpm->getDependencies($packages); + } + + /** + * Used by the Dashboard in the admin to display the X latest pages + * that have been modified + * + * @param integer $count number of pages to pull back + * + * @return array|null + */ + public function latestPages($count = 10) + { + /** @var Pages $pages */ + $pages = $this->grav['pages']; + + $latest = []; + + if (null === $pages->routes()) { + return null; + } + + foreach ($pages->routes() as $url => $path) { + $page = $pages->dispatch($url, true); + if ($page && $page->routable()) { + $latest[$page->route()] = ['modified' => $page->modified(), 'page' => $page]; + } + } + + // sort based on modified + uasort($latest, function ($a, $b) { + if ($a['modified'] == $b['modified']) { + return 0; + } + + return ($a['modified'] > $b['modified']) ? -1 : 1; + }); + + // build new array with just pages in it + $list = []; + foreach ($latest as $item) { + $list[] = $item['page']; + } + + return array_slice($list, 0, $count); + } + + /** + * Get log file for fatal errors. + * + * @return string + */ + public function logEntry() + { + $file = File::instance($this->grav['locator']->findResource("log://{$this->route}.html")); + $content = $file->content(); + $file->free(); + + return $content; + } + + /** + * Search in the logs when was the latest backup made + * + * @return array Array containing the latest backup information + */ + public function lastBackup() + { + $file = JsonFile::instance($this->grav['locator']->findResource("log://backup.log")); + $content = $file->content(); + if (empty($content)) { + return [ + 'days' => '∞', + 'chart_fill' => 100, + 'chart_empty' => 0 + ]; + } + + $backup = new \DateTime(); + $backup->setTimestamp($content['time']); + $diff = $backup->diff(new \DateTime()); + + $days = $diff->days; + $chart_fill = $days > 30 ? 100 : round($days / 30 * 100); + + return [ + 'days' => $days, + 'chart_fill' => $chart_fill, + 'chart_empty' => 100 - $chart_fill + ]; + } + + /** + * Determine if the plugin or theme info passed is from Team Grav + * + * @param object $info Plugin or Theme info object + * + * @return bool + */ + public function isTeamGrav($info) + { + return isset($info['author']['name']) && ($info['author']['name'] === 'Team Grav' || Utils::contains($info['author']['name'], 'Trilby Media')); + } + + /** + * Determine if the plugin or theme info passed is premium + * + * @param object $info Plugin or Theme info object + * + * @return bool + */ + public function isPremiumProduct($info) + { + return isset($info['premium']); + } + + /** + * Renders phpinfo + * + * @return string The phpinfo() output + */ + function phpinfo() + { + if (function_exists('phpinfo')) { + ob_start(); + phpinfo(); + $pinfo = ob_get_contents(); + ob_end_clean(); + + $pinfo = preg_replace('%^.*(.*).*$%ms', '$1', $pinfo); + + return $pinfo; + } + + return 'phpinfo() method is not available on this server.'; + } + + /** + * Guest date format based on euro/US + * + * @param $date + * + * @return string + */ + public function guessDateFormat($date) + { + static $guess; + + $date_formats = [ + 'm/d/y', + 'm/d/Y', + 'n/d/y', + 'n/d/Y', + 'd-m-Y', + 'd-m-y', + ]; + + $time_formats = [ + 'H:i', + 'G:i', + 'h:ia', + 'g:ia' + ]; + + if (!isset($guess[$date])) { + foreach ($date_formats as $date_format) { + foreach ($time_formats as $time_format) { + if ($this->validateDate($date, "$date_format $time_format")) { + $guess[$date] = "$date_format $time_format"; + break 2; + } + if ($this->validateDate($date, "$time_format $date_format")) { + $guess[$date] = "$time_format $date_format"; + break 2; + } + } + } + + if (!isset($guess[$date])) { + $guess[$date] = 'd-m-Y H:i'; + } + } + + return $guess[$date]; + } + + public function validateDate($date, $format) + { + $d = DateTime::createFromFormat($format, $date); + + return $d && $d->format($format) == $date; + } + + /** + * @param string $php_format + * + * @return string + */ + public function dateformatToMomentJS($php_format) + { + $SYMBOLS_MATCHING = [ + // Day + 'd' => 'DD', + 'D' => 'ddd', + 'j' => 'D', + 'l' => 'dddd', + 'N' => 'E', + 'S' => 'Do', + 'w' => 'd', + 'z' => 'DDD', + // Week + 'W' => 'W', + // Month + 'F' => 'MMMM', + 'm' => 'MM', + 'M' => 'MMM', + 'n' => 'M', + 't' => '', + // Year + 'L' => '', + 'o' => 'GGGG', + 'Y' => 'YYYY', + 'y' => 'yy', + // Time + 'a' => 'a', + 'A' => 'A', + 'B' => 'SSS', + 'g' => 'h', + 'G' => 'H', + 'h' => 'hh', + 'H' => 'HH', + 'i' => 'mm', + 's' => 'ss', + 'u' => '', + // Timezone + 'e' => '', + 'I' => '', + 'O' => 'ZZ', + 'P' => 'Z', + 'T' => 'z', + 'Z' => '', + // Full Date/Time + 'c' => '', + 'r' => 'llll ZZ', + 'U' => 'X' + ]; + $js_format = ''; + $escaping = false; + $len = strlen($php_format); + for ($i = 0; $i < $len; $i++) { + $char = $php_format[$i]; + if ($char === '\\') // PHP date format escaping character + { + $i++; + if ($escaping) { + $js_format .= $php_format[$i]; + } else { + $js_format .= '\'' . $php_format[$i]; + } + $escaping = true; + } else { + if ($escaping) { + $js_format .= "'"; + $escaping = false; + } + if (isset($SYMBOLS_MATCHING[$char])) { + $js_format .= $SYMBOLS_MATCHING[$char]; + } else { + $js_format .= $char; + } + } + } + + return $js_format; + } + + /** + * Gets the entire permissions array + * + * @return array + */ + public function getPermissions() + { + return $this->permissions; + } + + /** + * Sets the entire permissions array + * + * @param $permissions + */ + public function setPermissions($permissions) + { + $this->permissions = $permissions; + } + + /** + * Adds a permission to the permissions array + * + * @param $permissions + */ + public function addPermissions($permissions) + { + $this->permissions = array_merge($this->permissions, $permissions); + } + + public function processNotifications($notifications) + { + // Sort by date + usort($notifications, function ($a, $b) { + return strcmp($a->date, $b->date); + }); + + $notifications = array_reverse($notifications); + + // Make adminNicetimeFilter available + require_once __DIR__ . '/../classes/Twig/AdminTwigExtension.php'; + $adminTwigExtension = new AdminTwigExtension; + + $filename = $this->grav['locator']->findResource('user://data/notifications/' . $this->grav['user']->username . YAML_EXT, + true, true); + $read_notifications = (array)CompiledYamlFile::instance($filename)->content(); + + $notifications_processed = []; + foreach ($notifications as $key => $notification) { + $is_valid = true; + + if (in_array($notification->id, $read_notifications, true)) { + $notification->read = true; + } + + if ($is_valid && isset($notification->permissions) && !$this->authorize($notification->permissions)) { + $is_valid = false; + } + + if ($is_valid && isset($notification->dependencies)) { + foreach ($notification->dependencies as $dependency => $constraints) { + if ($dependency === 'grav') { + if (!Semver::satisfies(GRAV_VERSION, $constraints)) { + $is_valid = false; + } + } else { + $packages = array_merge($this->plugins()->toArray(), $this->themes()->toArray()); + if (!isset($packages[$dependency])) { + $is_valid = false; + } else { + $version = $packages[$dependency]['version']; + if (!Semver::satisfies($version, $constraints)) { + $is_valid = false; + } + } + } + + if (!$is_valid) { + break; + } + } + } + + if ($is_valid) { + $notifications_processed[] = $notification; + } + } + + // Process notifications + $notifications_processed = array_map(function ($notification) use ($adminTwigExtension) { + $notification->date = $adminTwigExtension->adminNicetimeFilter($notification->date); + + return $notification; + }, $notifications_processed); + + return $notifications_processed; + } + + public function findFormFields($type, $fields, $found_fields = []) + { + foreach ($fields as $key => $field) { + + if (isset($field['type']) && $field['type'] == $type) { + $found_fields[$key] = $field; + } elseif (isset($field['fields'])) { + $result = $this->findFormFields($type, $field['fields'], $found_fields); + if (!empty($result)) { + $found_fields = array_merge($found_fields, $result); + } + } + } + + return $found_fields; + } + + public function getPagePathFromToken($path) + { + return Utils::getPagePathFromToken($path, $this->page(true)); + } + + /** + * Returns edited page. + * + * @param bool $route + * + * @param null $path + * + * @return Page + */ + public function page($route = false, $path = null) + { + if (!$path) { + $path = $this->route; + } + + if ($route && !$path) { + $path = '/'; + } + + if (!isset($this->pages[$path])) { + $this->pages[$path] = $this->getPage($path); + } + + return $this->pages[$path]; + } + + /** + * Returns the page creating it if it does not exist. + * + * @param $path + * + * @return Page + */ + public function getPage($path) + { + /** @var Pages $pages */ + $pages = $this->grav['pages']; + + if ($path && $path[0] !== '/') { + $path = "/{$path}"; + } + + $page = $path ? $pages->dispatch($path, true) : $pages->root(); + + if (!$page) { + $slug = basename($path); + + if ($slug === '') { + return null; + } + + $ppath = str_replace('\\', '/', dirname($path)); + + // Find or create parent(s). + $parent = $this->getPage($ppath !== '/' ? $ppath : ''); + + // Create page. + $page = new Page; + $page->parent($parent); + $page->filePath($parent->path() . '/' . $slug . '/' . $page->name()); + + // Add routing information. + $pages->addPage($page, $path); + + // Set if Modular + $page->modularTwig($slug[0] === '_'); + + // Determine page type. + if (isset($this->session->{$page->route()})) { + // Found the type and header from the session. + $data = $this->session->{$page->route()}; + + // Set the key header value + $header = ['title' => $data['title']]; + + if (isset($data['visible'])) { + if ($data['visible'] === '' || $data['visible']) { + // if auto (ie '') + $pageParent = $page->parent(); + $children = $pageParent ? $pageParent->children() : []; + foreach ($children as $child) { + if ($child->order()) { + // set page order + $page->order(AdminController::getNextOrderInFolder($pageParent->path())); + break; + } + } + } + if ($data['visible'] == 1 && !$page->order()) { + $header['visible'] = $data['visible']; + } + + } + + if ($data['name'] === 'modular') { + $header['body_classes'] = 'modular'; + } + + $name = $page->modular() ? str_replace('modular/', '', $data['name']) : $data['name']; + $page->name($name . '.md'); + + // Fire new event to allow plugins to manipulate page frontmatter + $this->grav->fireEvent('onAdminCreatePageFrontmatter', new Event(['header' => &$header, + 'data' => $data])); + + $page->header($header); + $page->frontmatter(Yaml::dump((array)$page->header(), 20)); + } else { + // Find out the type by looking at the parent. + $type = $parent->childType() + ? $parent->childType() + : $parent->blueprints()->get('child_type', + 'default'); + $page->name($type . CONTENT_EXT); + $page->header(); + } + $page->modularTwig($slug[0] === '_'); + } + + return $page; + } + + /** + * Get https://getgrav.org news feed + * + * @return mixed + */ + public function getFeed() + { + $feed_url = 'https://getgrav.org/blog.atom'; + + $body = Response::get($feed_url); + + $reader = new Reader(); + $parser = $reader->getParser($feed_url, $body, 'utf-8'); + + return $parser->execute(); + + } + + public function getRouteDetails() + { + return [$this->base, $this->location, $this->route]; + } + + /** + * Get the files list + * + * @todo allow pagination + * @return array + */ + public function files($filtered = true, $page_index = 0) + { + $param_type = $this->grav['uri']->param('type'); + $param_date = $this->grav['uri']->param('date'); + $param_page = $this->grav['uri']->param('page'); + $param_page = str_replace('\\', '/', $param_page); + + $files_cache_key = 'media-manager-files'; + + if ($param_type) { + $files_cache_key .= "-{$param_type}"; + } + if ($param_date) { + $files_cache_key .= "-{$param_date}"; + } + if ($param_page) { + $files_cache_key .= "-{$param_page}"; + } + + $page_files = null; + + $cache_enabled = $this->grav['config']->get('plugins.admin.cache_enabled'); + if (!$cache_enabled) { + $this->grav['cache']->setEnabled(true); + } + + $page_files = $this->grav['cache']->fetch(md5($files_cache_key)); + + if (!$cache_enabled) { + $this->grav['cache']->setEnabled(false); + } + + if (!$page_files) { + $page_files = []; + $pages = $this->grav['pages']; + + if ($param_page) { + $page = $pages->dispatch($param_page); + + $page_files = $this->getFiles('images', $page, $page_files, $filtered); + $page_files = $this->getFiles('videos', $page, $page_files, $filtered); + $page_files = $this->getFiles('audios', $page, $page_files, $filtered); + $page_files = $this->getFiles('files', $page, $page_files, $filtered); + } else { + $allPages = $pages->all(); + + if ($allPages) foreach ($allPages as $page) { + $page_files = $this->getFiles('images', $page, $page_files, $filtered); + $page_files = $this->getFiles('videos', $page, $page_files, $filtered); + $page_files = $this->getFiles('audios', $page, $page_files, $filtered); + $page_files = $this->getFiles('files', $page, $page_files, $filtered); + } + } + + if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) { + $this->shouldLoadAdditionalFilesInBackground(true); + } + + if (!$cache_enabled) { + $this->grav['cache']->setEnabled(true); + } + $this->grav['cache']->save(md5($files_cache_key), $page_files, 600); //cache for 10 minutes + if (!$cache_enabled) { + $this->grav['cache']->setEnabled(false); + } + + } + + if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) { + $page_files = array_slice($page_files, $page_index * self::MEDIA_PAGINATION_INTERVAL, self::MEDIA_PAGINATION_INTERVAL); + } + + return $page_files; + } + + public function shouldLoadAdditionalFilesInBackground($status = null) + { + if ($status) { + $this->load_additional_files_in_background = true; + } + + return $this->load_additional_files_in_background; + } + + public function loadAdditionalFilesInBackground($status = null) + { + if (!$this->loading_additional_files_in_background) { + $this->loading_additional_files_in_background = true; + $this->files(false, false); + $this->shouldLoadAdditionalFilesInBackground(false); + $this->loading_additional_files_in_background = false; + } + } + + private function getFiles($type, $page, $page_files, $filtered) + { + $page_files = $this->getMediaOfType($type, $page, $page_files); + + if ($filtered) { + $page_files = $this->filterByType($page_files); + $page_files = $this->filterByDate($page_files); + } + + return $page_files; + } + + /** + * Get all the media of a type ('images' | 'audios' | 'videos' | 'files') + * + * @param string $type + * @param Page|null $page + * @param array $files + * + * @return array + */ + private function getMediaOfType($type, Page $page = null, array $files) + { + if ($page) { + $media = $page->media(); + $mediaOfType = $media->$type(); + + foreach($mediaOfType as $title => $file) { + $files[] = [ + 'title' => $title, + 'type' => $type, + 'page_route' => $page->route(), + 'file' => $file->higherQualityAlternative() + ]; + } + + return $files; + } + + return []; + } + + /** + * Filter media by type + * + * @param array $filesFiltered + * + * @return array + */ + private function filterByType($filesFiltered) + { + $filter_type = $this->grav['uri']->param('type'); + if (!$filter_type) { + return $filesFiltered; + } + + $filesFiltered = array_filter($filesFiltered, function ($file) use ($filter_type) { + return $file['type'] == $filter_type; + }); + + return $filesFiltered; + } + + /** + * Filter media by date + * + * @param array $filesFiltered + * + * @return array + */ + private function filterByDate($filesFiltered) + { + $filter_date = $this->grav['uri']->param('date'); + if (!$filter_date) { + return $filesFiltered; + } + + $year = substr($filter_date, 0, 4); + $month = substr($filter_date, 5, 2); + + $filesFilteredByDate = []; + + foreach($filesFiltered as $file) { + $filedate = $this->fileDate($file['file']); + $fileYear = $filedate->format('Y'); + $fileMonth = $filedate->format('m'); + + if ($fileYear == $year && $fileMonth == $month) { + $filesFilteredByDate[] = $file; + } + } + + return $filesFilteredByDate; + } + + /** + * Return the DateTime object representation of a file modified date + * + * @param File $file + * + * @return DateTime + */ + private function fileDate($file) { + $datetime = new \DateTime(); + $datetime->setTimestamp($file->toArray()['modified']); + return $datetime; + } + + /** + * Get the files dates list to be used in the Media Files filter + * + * @return array + */ + public function filesDates() + { + $files = $this->files(false); + $dates = []; + + foreach ($files as $file) { + $datetime = $this->fileDate($file['file']); + $year = $datetime->format('Y'); + $month = $datetime->format('m'); + + if (!isset($dates[$year])) { + $dates[$year] = []; + } + + if (!isset($dates[$year][$month])) { + $dates[$year][$month] = 1; + } else { + $dates[$year][$month]++; + } + } + + return $dates; + } + + /** + * Get the pages list to be used in the Media Files filter + * + * @return array + */ + public function pages() + { + /** @var Collection $pages */ + $pages = $this->grav['pages']->all(); + + $pagesWithFiles = []; + foreach ($pages as $page) { + if (count($page->media()->all())) { + $pagesWithFiles[] = $page; + } + } + + return $pagesWithFiles; + } + + /** + * Return HTTP_REFERRER if set + * + * @return null + */ + public function getReferrer() + { + return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null; + } +} diff --git a/user/plugins/admin/classes/adminbasecontroller.php b/user/plugins/admin/classes/adminbasecontroller.php new file mode 100644 index 0000000..5803a91 --- /dev/null +++ b/user/plugins/admin/classes/adminbasecontroller.php @@ -0,0 +1,1007 @@ + 'There is no error, the file uploaded with success', + 1 => 'The uploaded file exceeds the max upload size', + 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML', + 3 => 'The uploaded file was only partially uploaded', + 4 => 'No file was uploaded', + 6 => 'Missing a temporary folder', + 7 => 'Failed to write file to disk', + 8 => 'A PHP extension stopped the file upload' + ]; + + /** @var array */ + public $blacklist_views = []; + + /** + * Performs a task. + * + * @return bool True if the action was performed successfully. + */ + public function execute() + { + if (in_array($this->view, $this->blacklist_views, true)) { + return false; + } + + if (!$this->validateNonce()) { + return false; + } + + $method = 'task' . ucfirst($this->task); + + if (method_exists($this, $method)) { + try { + $success = $this->{$method}(); + } catch (\RuntimeException $e) { + $success = true; + $this->admin->setMessage($e->getMessage(), 'error'); + } + } else { + $success = $this->grav->fireEvent('onAdminTaskExecute', + new Event(['controller' => $this, 'method' => $method])); + } + + // Grab redirect parameter. + $redirect = isset($this->post['_redirect']) ? $this->post['_redirect'] : null; + unset($this->post['_redirect']); + + // Redirect if requested. + if ($redirect) { + $this->setRedirect($redirect); + } + + return $success; + } + + protected function validateNonce() + { + if (strtolower($_SERVER['REQUEST_METHOD']) === 'post') { + if (isset($this->post['admin-nonce'])) { + $nonce = $this->post['admin-nonce']; + } else { + $nonce = $this->grav['uri']->param('admin-nonce'); + } + + if (!$nonce || !Utils::verifyNonce($nonce, 'admin-form')) { + if ($this->task === 'addmedia') { + + $message = sprintf($this->admin->translate('PLUGIN_ADMIN.FILE_TOO_LARGE', null), + ini_get('post_max_size')); + + //In this case it's more likely that the image is too big than POST can handle. Show message + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $message + ]; + + return false; + } + + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'), 'error'); + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN') + ]; + + return false; + } + unset($this->post['admin-nonce']); + } else { + if ($this->task === 'logout') { + $nonce = $this->grav['uri']->param('logout-nonce'); + if (null === $nonce || !Utils::verifyNonce($nonce, 'logout-form')) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'), + 'error'); + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN') + ]; + + return false; + } + } else { + $nonce = $this->grav['uri']->param('admin-nonce'); + if (null === $nonce || !Utils::verifyNonce($nonce, 'admin-form')) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'), + 'error'); + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN') + ]; + + return false; + } + } + } + + return true; + } + + /** + * Sets the page redirect. + * + * @param string $path The path to redirect to + * @param int $code The HTTP redirect code + */ + public function setRedirect($path, $code = 303) + { + $this->redirect = $path; + $this->redirectCode = $code; + } + + /** + * Handles ajax upload for files. + * Stores in a flash object the temporary file and deals with potential file errors. + * + * @return bool True if the action was performed. + */ + public function taskFilesUpload() + { + if (null === $_FILES || !$this->authorizeTask('save', $this->dataPermissions())) { + return false; + } + + /** @var Config $config */ + $config = $this->grav['config']; + $data = $this->view === 'pages' ? $this->admin->page(true) : $this->prepareData([]); + $settings = $data->blueprints()->schema()->getProperty($this->post['name']); + $settings = (object)array_merge([ + 'avoid_overwriting' => false, + 'random_name' => false, + 'accept' => ['image/*'], + 'limit' => 10, + 'filesize' => $config->get('system.media.upload_limit', 5242880) // 5MB + ], (array)$settings, ['name' => $this->post['name']]); + + $upload = $this->normalizeFiles($_FILES['data'], $settings->name); + + $filename = trim($upload->file->name); + + // Handle bad filenames. + if (strtr($filename, "\t\n\r\0\x0b", '_____') !== $filename || rtrim($filename, '. ') !== $filename || preg_match('|\.php|', $filename)) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD', null), + $filename, 'Bad filename') + ]; + + return false; + } + + if (!isset($settings->destination)) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.DESTINATION_NOT_SPECIFIED', null) + ]; + + return false; + } + + // Do not use self@ outside of pages + if ($this->view !== 'pages' && in_array($settings->destination, ['@self', 'self@'])) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_PREVENT_SELF', null), + $settings->destination) + ]; + + return false; + } + + // Handle errors and breaks without proceeding further + if ($upload->file->error != UPLOAD_ERR_OK) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD', null), + $upload->file->name, $this->upload_errors[$upload->file->error]) + ]; + + return false; + } + + // Handle file size limits + $settings->filesize *= 1048576; // 2^20 [MB in Bytes] + if ($settings->filesize > 0 && $upload->file->size > $settings->filesize) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT') + ]; + + return false; + } + + // Handle Accepted file types + // Accept can only be mime types (image/png | image/*) or file extensions (.pdf|.jpg) + $accepted = false; + $errors = []; + + foreach ((array)$settings->accept as $type) { + // Force acceptance of any file when star notation + if ($type === '*') { + $accepted = true; + break; + } + + $isMime = strstr($type, '/'); + $find = str_replace('*', '.*', $type); + + $match = preg_match('#' . $find . '$#', $isMime ? $upload->file->type : $upload->file->name); + if (!$match) { + $message = $isMime ? 'The MIME type "' . $upload->file->type . '"' : 'The File Extension'; + $errors[] = $message . ' for the file "' . $upload->file->name . '" is not an accepted.'; + $accepted |= false; + } else { + $accepted |= true; + } + } + + if (!$accepted) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => implode('
    ', $errors) + ]; + + return false; + } + + // Remove the error object to avoid storing it + unset($upload->file->error); + + // we need to move the file at this stage or else + // it won't be available upon save later on + // since php removes it from the upload location + $tmp_dir = Admin::getTempDir(); + $tmp_file = $upload->file->tmp_name; + $tmp = $tmp_dir . '/uploaded-files/' . basename($tmp_file); + + Folder::create(dirname($tmp)); + if (!move_uploaded_file($tmp_file, $tmp)) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_MOVE', null), '', + $tmp) + ]; + + return false; + } + + $upload->file->tmp_name = $tmp; + + // Retrieve the current session of the uploaded files for the field + // and initialize it if it doesn't exist + $sessionField = base64_encode($this->grav['uri']->url()); + $flash = $this->admin->session()->getFlashObject('files-upload'); + if (!$flash) { + $flash = []; + } + if (!isset($flash[$sessionField])) { + $flash[$sessionField] = []; + } + if (!isset($flash[$sessionField][$upload->field])) { + $flash[$sessionField][$upload->field] = []; + } + + // Set destination + if ($this->grav['locator']->isStream($settings->destination)) { + $destination = $this->grav['locator']->findResource($settings->destination, false, true); + } else { + $destination = Folder::getRelativePath(rtrim($settings->destination, '/')); + $destination = $this->admin->getPagePathFromToken($destination); + } + + // Create destination if needed + if (!is_dir($destination)) { + Folder::mkdir($destination); + } + + // Generate random name if required + if ($settings->random_name) { // TODO: document + $extension = pathinfo($upload->file->name)['extension']; + $upload->file->name = Utils::generateRandomString(15) . '.' . $extension; + } + + // Handle conflicting name if needed + if ($settings->avoid_overwriting) { // TODO: document + if (file_exists($destination . '/' . $upload->file->name)) { + $upload->file->name = date('YmdHis') . '-' . $upload->file->name; + } + } + + // Prepare object for later save + $path = $destination . '/' . $upload->file->name; + $upload->file->path = $path; + // $upload->file->route = $page ? $path : null; + + // Prepare data to be saved later + $flash[$sessionField][$upload->field][$path] = (array)$upload->file; + + // Finally store the new uploaded file in the field session + $this->admin->session()->setFlashObject('files-upload', $flash); + $this->admin->json_response = [ + 'status' => 'success', + 'session' => \json_encode([ + 'sessionField' => base64_encode($this->grav['uri']->url()), + 'path' => $upload->file->path, + 'field' => $settings->name + ]) + ]; + + return true; + } + + /** + * Checks if the user is allowed to perform the given task with its associated permissions + * + * @param string $task The task to execute + * @param array $permissions The permissions given + * + * @return bool True if authorized. False if not. + */ + public function authorizeTask($task = '', $permissions = []) + { + if (!$this->admin->authorize($permissions)) { + if ($this->grav['uri']->extension() === 'json') { + $this->admin->json_response = [ + 'status' => 'unauthorized', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' ' . $task . '.' + ]; + } else { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' ' . $task . '.', + 'error'); + } + + return false; + } + + return true; + } + + /** + * Gets the permissions needed to access a given view + * + * @return array An array of permissions + */ + protected function dataPermissions() + { + $type = $this->view; + $permissions = ['admin.super']; + + switch ($type) { + case 'configuration': + case 'config': + case 'system': + $permissions[] = 'admin.configuration'; + break; + case 'settings': + case 'site': + $permissions[] = 'admin.settings'; + break; + case 'plugins': + $permissions[] = 'admin.plugins'; + break; + case 'themes': + $permissions[] = 'admin.themes'; + break; + case 'users': + $permissions[] = 'admin.users'; + break; + case 'user': + $permissions[] = 'admin.login'; + $permissions[] = 'admin.users'; + break; + case 'pages': + $permissions[] = 'admin.pages'; + break; + } + + return $permissions; + } + + /** + * Gets the configuration data for a given view & post + * + * @param array $data + * + * @return array + */ + protected function prepareData(array $data) + { + return $data; + } + + /** + * Internal method to normalize the $_FILES array + * + * @param array $data $_FILES starting point data + * @param string $key + * + * @return object a new Object with a normalized list of files + */ + protected function normalizeFiles($data, $key = '') + { + $files = new \stdClass(); + $files->field = $key; + $files->file = new \stdClass(); + + foreach ($data as $fieldName => $fieldValue) { + // Since Files Upload are always happening via Ajax + // we are not interested in handling `multiple="true"` + // because they are always handled one at a time. + // For this reason we normalize the value to string, + // in case it is arriving as an array. + $value = (array)Utils::getDotNotation($fieldValue, $key); + $files->file->{$fieldName} = array_shift($value); + } + + return $files; + } + + /** + * Removes a file from the flash object session, before it gets saved + * + * @return bool True if the action was performed. + */ + public function taskFilesSessionRemove() + { + if (!$this->authorizeTask('save', $this->dataPermissions()) || !isset($_FILES)) { + return false; + } + + // Retrieve the current session of the uploaded files for the field + // and initialize it if it doesn't exist + $sessionField = base64_encode($this->grav['uri']->url()); + $request = \json_decode($this->post['session']); + + // Ensure the URI requested matches the current one, otherwise fail + if ($request->sessionField !== $sessionField) { + return false; + } + + // Retrieve the flash object and remove the requested file from it + $flash = $this->admin->session()->getFlashObject('files-upload'); + $endpoint = $flash[$request->sessionField][$request->field][$request->path]; + + if (isset($endpoint)) { + if (file_exists($endpoint['tmp_name'])) { + unlink($endpoint['tmp_name']); + } + + unset($endpoint); + } + + // Walk backward to cleanup any empty field that's left + // Field + if (isset($flash[$request->sessionField][$request->field][$request->path])) { + unset($flash[$request->sessionField][$request->field][$request->path]); + } + + // Field + if (isset($flash[$request->sessionField][$request->field]) && empty($flash[$request->sessionField][$request->field])) { + unset($flash[$request->sessionField][$request->field]); + } + + // Session Field + if (isset($flash[$request->sessionField]) && empty($flash[$request->sessionField])) { + unset($flash[$request->sessionField]); + } + + + // If there's anything left to restore in the flash object, do so + if (count($flash)) { + $this->admin->session()->setFlashObject('files-upload', $flash); + } + + $this->admin->json_response = ['status' => 'success']; + + return true; + } + + /** + * 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) + && 0 !== strpos($this->redirect, substr($base, 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); + } + + /** + * Prepare and return POST data. + * + * @param array $post + * + * @return array + */ + protected function getPost($post) + { + if (!is_array($post)) { + return []; + } + + unset($post['task']); + + // Decode JSON encoded fields and merge them to data. + if (isset($post['_json'])) { + $post = array_replace_recursive($post, $this->jsonDecode($post['_json'])); + unset($post['_json']); + } + + $post = $this->cleanDataKeys($post); + + return $post; + } + + /** + * Recursively JSON decode data. + * + * @param array $data + * + * @return array + */ + protected function jsonDecode(array $data) + { + foreach ($data as &$value) { + if (is_array($value)) { + $value = $this->jsonDecode($value); + } else { + $value = json_decode($value, true); + } + } + + return $data; + } + + protected function cleanDataKeys($source = []) + { + $out = []; + + if (is_array($source)) { + foreach ($source as $key => $value) { + $key = str_replace(['%5B', '%5D'], ['[', ']'], $key); + if (is_array($value)) { + $out[$key] = $this->cleanDataKeys($value); + } else { + $out[$key] = $value; + } + } + } + + return $out; + } + + /** + * Return true if multilang is active + * + * @return bool True if multilang is active + */ + protected function isMultilang() + { + return count($this->grav['config']->get('system.languages.supported', [])) > 1; + } + + /** + * @param \Grav\Common\Page\Page|\Grav\Common\Data\Data $obj + * + * @return \Grav\Common\Page\Page|\Grav\Common\Data\Data + */ + protected function storeFiles($obj) + { + // Process previously uploaded files for the current URI + // and finally store them. Everything else will get discarded + $queue = $this->admin->session()->getFlashObject('files-upload'); + $queue = $queue[base64_encode($this->grav['uri']->url())]; + if (is_array($queue)) { + foreach ($queue as $key => $files) { + foreach ($files as $destination => $file) { + if (!rename($file['tmp_name'], $destination)) { + throw new \RuntimeException(sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_MOVE', + null), '"' . $file['tmp_name'] . '"', $destination)); + } + + unset($files[$destination]['tmp_name']); + } + + if ($this->view === 'pages') { + $keys = explode('.', preg_replace('/^header./', '', $key)); + $init_key = array_shift($keys); + if (count($keys) > 0) { + $new_data = isset($obj->header()->{$init_key}) ? $obj->header()->{$init_key} : []; + Utils::setDotNotation($new_data, implode('.', $keys), $files, true); + } else { + $new_data = $files; + } + if (isset($data['header'][$init_key])) { + $obj->modifyHeader($init_key, + array_replace_recursive([], $data['header'][$init_key], $new_data)); + } else { + $obj->modifyHeader($init_key, $new_data); + } + } else { + // TODO: [this is JS handled] if it's single file, remove existing and use set, if it's multiple, use join + $obj->join($key, $files); // stores + } + + } + } + + return $obj; + } + + /** + * Used by the filepicker field to get a list of files in a folder. + */ + protected function taskGetFilesInFolder() + { + if (!$this->authorizeTask('save', $this->dataPermissions())) { + return false; + } + + $data = $this->view === 'pages' ? $this->admin->page(true) : $this->prepareData([]); + $settings = $data->blueprints()->schema()->getProperty($this->post['name']); + + if (isset($settings['folder'])) { + $folder = $settings['folder']; + } else { + $folder = '@self'; + } + + // Do not use self@ outside of pages + if ($this->view !== 'pages' && in_array($folder, ['@self', 'self@', '@self@'])) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_PREVENT_SELF', null), $folder) + ]; + + return false; + } + + // Set destination + $folder = Folder::getRelativePath(rtrim($folder, '/')); + $folder = $this->admin->getPagePathFromToken($folder); + + $media = new Media($folder); + $available_files = []; + $metadata = []; + $thumbs = []; + + + foreach ($media->all() as $name => $medium) { + + $available_files[] = $name; + + if (isset($settings['include_metadata'])) { + $img_metadata = $medium->metadata(); + if ($img_metadata) { + $metadata[$name] = $img_metadata; + } + } + + } + + // Peak in the flashObject for optimistic filepicker updates + $pending_files = []; + $sessionField = base64_encode($this->grav['uri']->url()); + $flash = $this->admin->session()->getFlashObject('files-upload'); + + if ($flash && isset($flash[$sessionField])) { + foreach ($flash[$sessionField] as $field => $data) { + foreach ($data as $file) { + if (dirname($file['path']) === $folder) { + $pending_files[] = $file['name']; + } + } + } + } + + $this->admin->session()->setFlashObject('files-upload', $flash); + + // Handle Accepted file types + // Accept can only be file extensions (.pdf|.jpg) + if (isset($settings['accept'])) { + $available_files = array_filter($available_files, function ($file) use ($settings) { + return $this->filterAcceptedFiles($file, $settings); + }); + + $pending_files = array_filter($pending_files, function ($file) use ($settings) { + return $this->filterAcceptedFiles($file, $settings); + }); + } + + // Generate thumbs if needed + if (isset($settings['preview_images']) && $settings['preview_images'] === true) { + foreach ($available_files as $filename) { + $thumbs[$filename] = $media[$filename]->zoomCrop(100,100)->url(); + } + } + + $this->admin->json_response = [ + 'status' => 'success', + 'files' => array_values($available_files), + 'pending' => array_values($pending_files), + 'folder' => $folder, + 'metadata' => $metadata, + 'thumbs' => $thumbs + ]; + + return true; + } + + protected function filterAcceptedFiles($file, $settings) + { + $valid = false; + + foreach ((array)$settings['accept'] as $type) { + $find = str_replace('*', '.*', $type); + $valid |= preg_match('#' . $find . '$#', $file); + } + + return $valid; + } + + /** + * 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'); + + $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(['config/', '/blueprints'], '', $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; + } + + /** + * Handles removing a media file + * + * @return bool True if the action was performed + */ + public function taskRemoveMedia() + { + if (!$this->canEditMedia()) { + return false; + } + + $filename = base64_decode($this->grav['uri']->param('route')); + if (!$filename) { + $filename = base64_decode($this->route); + } + + $file = File::instance($filename); + $resultRemoveMedia = false; + + if ($file->exists()) { + $resultRemoveMedia = $file->delete(); + + $fileParts = pathinfo($filename); + + foreach (scandir($fileParts['dirname']) as $file) { + $regex_pattern = '/' . preg_quote($fileParts['filename'], '/') . "@\d+x\." . $fileParts['extension'] . "(?:\.meta\.yaml)?$|" . preg_quote($fileParts['basename'], '/') . "\.meta\.yaml$/"; + if (preg_match($regex_pattern, $file)) { + $path = $fileParts['dirname'] . '/' . $file; + @unlink($path); + } + } + + } + + if ($resultRemoveMedia) { + if ($this->grav['uri']->extension() === 'json') { + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate('PLUGIN_ADMIN.REMOVE_SUCCESSFUL') + ]; + } else { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.REMOVE_SUCCESSFUL'), 'info'); + $this->clearMediaCache(); + $this->setRedirect('/media-manager'); + } + + return true; + } + + if ($this->grav['uri']->extension() === 'json') { + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate('PLUGIN_ADMIN.REMOVE_FAILED') + ]; + } else { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.REMOVE_FAILED'), 'error'); + } + + return false; + } + + /** + * Handles clearing the media cache + * + * @return bool True if the action was performed + */ + protected function clearMediaCache() + { + $key = 'media-manager-files'; + $cache = $this->grav['cache']; + $cache->delete(md5($key)); + + return true; + } + + /** + * Determine if the user can edit media + * + * @param string $type + * + * @return bool True if the media action is allowed + */ + protected function canEditMedia($type = 'media') + { + if (!$this->authorizeTask('edit media', ['admin.' . $type, 'admin.super'])) { + return false; + } + + return true; + } +} diff --git a/user/plugins/admin/classes/admincontroller.php b/user/plugins/admin/classes/admincontroller.php new file mode 100644 index 0000000..e3b1be8 --- /dev/null +++ b/user/plugins/admin/classes/admincontroller.php @@ -0,0 +1,2297 @@ + "There is no error, the file uploaded with success", + 1 => "The uploaded file exceeds the max upload size", + 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML", + 3 => "The uploaded file was only partially uploaded", + 4 => "No file was uploaded", + 6 => "Missing a temporary folder", + 7 => "Failed to write file to disk", + 8 => "A PHP extension stopped the file upload" + ]; + + /** + * @param Grav $grav + * @param string $view + * @param string $task + * @param string $route + * @param array $post + */ + public function initialize(Grav $grav = null, $view = null, $task = null, $route = null, $post = null) + { + $this->grav = $grav; + $this->view = $view; + $this->task = $task ? $task : 'display'; + if (isset($post['data'])) { + $this->data = $this->getPost($post['data']); + unset($post['data']); + } else { + // Backwards compatibility for Form plugin <= 1.2 + $this->data = $this->getPost($post); + } + $this->post = $this->getPost($post); + $this->route = $route; + $this->admin = $this->grav['admin']; + + $this->grav->fireEvent('onAdminControllerInit', new Event(['controller' => &$this])); + } + + /** + * Handle login. + * + * @return bool True if the action was performed. + */ + protected function taskLogin() + { + $this->admin->authenticate($this->data, $this->post); + + return true; + } + + /** + * @return bool True if the action was performed. + */ + protected function taskTwofa() + { + $this->admin->twoFa($this->data, $this->post); + + return true; + } + + /** + * Handle logout. + * + * @return bool True if the action was performed. + */ + protected function taskLogout() + { + $this->admin->logout($this->data, $this->post); + + return true; + } + + /** + * @param null $secret + * @return bool + */ + public function taskRegenerate2FASecret() + { + if (!$this->authorizeTask('regenerate 2FA Secret', ['admin.login'])) { + return false; + } + + try { + /** @var User $user */ + $user = $this->grav['user']; + + /** @var TwoFactorAuth $twoFa */ + $twoFa = $this->grav['login']->twoFactorAuth(); + $secret = $twoFa->createSecret(); + $image = $twoFa->getQrImageData($user->username, $secret); + + // Save secret into the user file. + $file = $user->file(); + if ($file->exists()) { + $content = $file->content(); + $content['twofa_secret'] = $secret; + $file->save($content); + $file->free(); + } + + // Change secret in the session. + $user->twofa_secret = $secret; + + $this->admin->json_response = ['status' => 'success', 'image' => $image, 'secret' => preg_replace('|(\w{4})|', '\\1 ', $secret)]; + } catch (\Exception $e) { + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + return false; + } + + return true; + } + + /** + * Handle the reset password action. + * + * @return bool True if the action was performed. + */ + public function taskReset() + { + $data = $this->data; + + if (isset($data['password'])) { + $username = isset($data['username']) ? strip_tags(strtolower($data['username'])) : null; + $user = $username ? User::load($username) : null; + $password = isset($data['password']) ? $data['password'] : null; + $token = isset($data['token']) ? $data['token'] : null; + + if ($user && $user->exists() && !empty($user->reset)) { + list($good_token, $expire) = explode('::', $user->reset); + + if ($good_token === $token) { + if (time() > $expire) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_LINK_EXPIRED'), 'error'); + $this->setRedirect('/forgot'); + + return true; + } + + unset($user->hashed_password, $user->reset); + $user->password = $password; + + $user->validate(); + $user->filter(); + $user->save(); + + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_PASSWORD_RESET'), 'info'); + $this->setRedirect('/'); + + return true; + } + } + + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_INVALID_LINK'), 'error'); + $this->setRedirect('/forgot'); + + return true; + + } + + $user = $this->grav['uri']->param('user'); + $token = $this->grav['uri']->param('token'); + + if (empty($user) || empty($token)) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_INVALID_LINK'), 'error'); + $this->setRedirect('/forgot'); + + return true; + } + + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_NEW_PASSWORD'), 'info'); + + $this->admin->forgot = ['username' => $user, 'token' => $token]; + + return true; + } + + /** + * Handle the email password recovery procedure. + * + * @return bool True if the action was performed. + * @todo LOGIN + */ + protected function taskForgot() + { + $param_sep = $this->grav['config']->get('system.param_sep', ':'); + $post = $this->post; + $data = $this->data; + $login = $this->grav['login']; + + $username = isset($data['username']) ? strip_tags(strtolower($data['username'])) : ''; + $user = !empty($username) ? User::load($username) : null; + + if (!isset($this->grav['Email'])) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error'); + $this->setRedirect($post['redirect']); + + return true; + } + + if (!$user || !$user->exists()) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'), + 'info'); + $this->setRedirect($post['redirect']); + + return true; + } + + if (empty($user->email)) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'), + 'info'); + $this->setRedirect($post['redirect']); + + return true; + } + + $count = $this->grav['config']->get('plugins.login.max_pw_resets_count', 0); + $interval =$this->grav['config']->get('plugins.login.max_pw_resets_interval', 2); + + if ($login->isUserRateLimited($user, 'pw_resets', $count, $interval)) { + $this->admin->setMessage($this->admin->translate(['PLUGIN_LOGIN.FORGOT_CANNOT_RESET_IT_IS_BLOCKED', $user->email, $interval]), 'error'); + $this->setRedirect($post['redirect']); + + return true; + } + + $token = md5(uniqid(mt_rand(), true)); + $expire = time() + 604800; // next week + + $user->reset = $token . '::' . $expire; + $user->save(); + + $author = $this->grav['config']->get('site.author.name', ''); + $fullname = $user->fullname ?: $username; + $reset_link = rtrim($this->grav['uri']->rootUrl(true), '/') . '/' . trim($this->admin->base, + '/') . '/reset/task' . $param_sep . 'reset/user' . $param_sep . $username . '/token' . $param_sep . $token . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form'); + + $sitename = $this->grav['config']->get('site.title', 'Website'); + $from = $this->grav['config']->get('plugins.email.from'); + + if (empty($from)) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error'); + $this->setRedirect($post['redirect']); + + return true; + } + + $to = $user->email; + + $subject = $this->admin->translate(['PLUGIN_ADMIN.FORGOT_EMAIL_SUBJECT', $sitename]); + $content = $this->admin->translate([ + 'PLUGIN_ADMIN.FORGOT_EMAIL_BODY', + $fullname, + $reset_link, + $author, + $sitename + ]); + + $body = $this->grav['twig']->processTemplate('email/base.html.twig', ['content' => $content]); + + $message = $this->grav['Email']->message($subject, $body, 'text/html')->setFrom($from)->setTo($to); + + $sent = $this->grav['Email']->send($message); + + if ($sent < 1) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_FAILED_TO_EMAIL'), 'error'); + } else { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'), + 'info'); + } + + $this->setRedirect('/'); + + return true; + } + + /** + * Enable a plugin. + * + * @return bool True if the action was performed. + */ + public function taskEnable() + { + if (!$this->authorizeTask('enable plugin', ['admin.plugins', 'admin.super'])) { + return false; + } + + if ($this->view !== 'plugins') { + return false; + } + + // Filter value and save it. + $this->post = ['enabled' => true]; + $obj = $this->prepareData($this->post); + $obj->save(); + + $this->post = ['_redirect' => 'plugins']; + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_ENABLED_PLUGIN'), 'info'); + + return true; + } + + /** + * Gets the configuration data for a given view & post + * + * @param array $data + * + * @return object + */ + protected function prepareData(array $data) + { + $type = trim("{$this->view}/{$this->admin->route}", '/'); + $data = $this->admin->data($type, $data); + + return $data; + } + + /** + * Disable a plugin. + * + * @return bool True if the action was performed. + */ + public function taskDisable() + { + if (!$this->authorizeTask('disable plugin', ['admin.plugins', 'admin.super'])) { + return false; + } + + if ($this->view !== 'plugins') { + return false; + } + + // Filter value and save it. + $this->post = ['enabled' => false]; + $obj = $this->prepareData($this->post); + $obj->save(); + + $this->post = ['_redirect' => 'plugins']; + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_DISABLED_PLUGIN'), 'info'); + + return true; + } + + /** + * Set the default theme. + * + * @return bool True if the action was performed. + */ + public function taskActivate() + { + if (!$this->authorizeTask('activate theme', ['admin.themes', 'admin.super'])) { + return false; + } + + if ($this->view !== 'themes') { + return false; + } + + $this->post = ['_redirect' => 'themes']; + + // Make sure theme exists (throws exception) + $name = $this->route; + $this->grav['themes']->get($name); + + // Store system configuration. + $system = $this->admin->data('config/system'); + $system->set('pages.theme', $name); + $system->save(); + + // Force configuration reload and save. + /** @var Config $config */ + $config = $this->grav['config']; + $config->reload()->save(); + + $config->set('system.pages.theme', $name); + + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_CHANGED_THEME'), 'info'); + + return true; + } + + /** + * Handles updating Grav + * + * @return bool True if the action was performed + */ + public function taskUpdategrav() + { + if (!$this->authorizeTask('install grav', ['admin.super'])) { + return false; + } + + $gpm = Gpm::GPM(); + $version = $gpm->grav->getVersion(); + $result = Gpm::selfupgrade(); + + if ($result) { + $this->admin->json_response = [ + 'status' => 'success', + 'type' => 'updategrav', + 'version' => $version, + 'message' => $this->admin->translate('PLUGIN_ADMIN.GRAV_WAS_SUCCESSFULLY_UPDATED_TO') . ' ' . $version + ]; + } else { + $this->admin->json_response = [ + 'status' => 'error', + 'type' => 'updategrav', + 'version' => GRAV_VERSION, + 'message' => $this->admin->translate('PLUGIN_ADMIN.GRAV_UPDATE_FAILED') . '
    ' . Installer::lastErrorMsg() + ]; + } + + return true; + } + + /** + * Handles uninstalling plugins and themes + * + * @deprecated + * + * @return bool True if the action was performed + */ + public function taskUninstall() + { + $type = $this->view === 'plugins' ? 'plugins' : 'themes'; + if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) { + return false; + } + + $package = $this->route; + + $result = Gpm::uninstall($package, []); + + if ($result) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL'), 'info'); + } else { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED'), 'error'); + } + + $this->post = ['_redirect' => $this->view]; + + return true; + } + + /** + * Handles creating an empty page folder (without markdown file) + * + * @return bool True if the action was performed. + */ + public function taskSaveNewFolder() + { + if (!$this->authorizeTask('save', $this->dataPermissions())) { + return false; + } + + $data = (array)$this->data; + + if ($data['route'] === '/') { + $path = $this->grav['locator']->findResource('page://'); + } else { + $path = $this->grav['page']->find($data['route'])->path(); + } + + $orderOfNewFolder = $this->getNextOrderInFolder($path); + $new_path = $path . '/' . $orderOfNewFolder . '.' . $data['folder']; + + Folder::create($new_path); + Cache::clearCache('standard'); + + $this->grav->fireEvent('onAdminAfterSaveAs', new Event(['path' => $new_path])); + + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info'); + + $multilang = $this->isMultilang(); + $admin_route = $this->admin->base; + $redirect_url = '/' . ($multilang ? ($this->grav['session']->admin_lang) : '') . $admin_route . '/' . $this->view; + $this->setRedirect($redirect_url); + + return true; + } + + /** + * Get the next available ordering number in a folder + * + * @param $path + * + * @return string the correct order string to prepend + */ + public static function getNextOrderInFolder($path) + { + $files = Folder::all($path, ['recursive' => false]); + + $highestOrder = 0; + foreach ($files as $file) { + preg_match(PAGE_ORDER_PREFIX_REGEX, $file, $order); + + if (isset($order[0])) { + $theOrder = (int)trim($order[0], '.'); + } else { + $theOrder = 0; + } + + if ($theOrder >= $highestOrder) { + $highestOrder = $theOrder; + } + } + + $orderOfNewFolder = $highestOrder + 1; + + if ($orderOfNewFolder < 10) { + $orderOfNewFolder = '0' . $orderOfNewFolder; + } + + return $orderOfNewFolder; + } + + /** + * Handles form and saves the input data if its valid. + * + * @return bool True if the action was performed. + */ + public function taskSave() + { + if (!$this->authorizeTask('save', $this->dataPermissions())) { + return false; + } + + $reorder = true; + $data = (array)$this->data; + + // Special handler for user data. + if ($this->view === 'user') { + if (!$this->admin->authorize(['admin.super', 'admin.users'])) { + //not admin.super or admin.users + if ($this->prepareData($data)->username !== $this->grav['user']->username) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' save.', + 'error'); + + return false; + } + } + } + + // Special handler for pages data. + if ($this->view === 'pages') { + /** @var Pages $pages */ + $pages = $this->grav['pages']; + + // Find new parent page in order to build the path. + $route = !isset($data['route']) ? dirname($this->admin->route) : $data['route']; + + /** @var Page $obj */ + $obj = $this->admin->page(true); + + if (!isset($data['folder']) || !$data['folder']) { + $data['folder'] = $obj->slug(); + $this->data['folder'] = $obj->slug(); + } + + // Ensure route is prefixed with a forward slash. + $route = '/' . ltrim($route, '/'); + + if (isset($data['frontmatter']) && !$this->checkValidFrontmatter($data['frontmatter'])) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_FRONTMATTER_COULD_NOT_SAVE'), + 'error'); + + return false; + } + + + $parent = $route && $route !== '/' && $route !== '.' && $route !== '/.' ? $pages->dispatch($route, true) : $pages->root(); + $original_order = (int)trim($obj->order(), '.'); + + try { + // Change parent if needed and initialize move (might be needed also on ordering/folder change). + $obj = $obj->move($parent); + $this->preparePage($obj, false, $obj->language()); + $obj->validate(); + + } catch (\Exception $e) { + $this->admin->setMessage($e->getMessage(), 'error'); + + return false; + } + $obj->filter(); + + // rename folder based on visible + if ($original_order === 1000) { + // increment order to force reshuffle + $obj->order($original_order + 1); + } + + if (isset($data['order']) && !empty($data['order'])) { + $reorder = explode(',', $data['order']); + } + + // add or remove numeric prefix based on ordering value + if (isset($data['ordering'])) { + if ($data['ordering'] && !$obj->order()) { + $obj->order($this->getNextOrderInFolder($obj->parent()->path())); + $reorder = false; + } elseif (!$data['ordering'] && $obj->order()) { + $obj->folder($obj->slug()); + } + } + + } else { + // Handle standard data types. + $obj = $this->prepareData($data); + + try { + $obj->validate(); + } catch (\Exception $e) { + $this->admin->setMessage($e->getMessage(), 'error'); + + return false; + } + + $obj->filter(); + } + + $obj = $this->storeFiles($obj); + + if ($obj) { + // Event to manipulate data before saving the object + $this->grav->fireEvent('onAdminSave', new Event(['object' => &$obj])); + $obj->save($reorder); + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info'); + $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $obj])); + } + + if ($this->view !== 'pages') { + // Force configuration reload. + /** @var Config $config */ + $config = $this->grav['config']; + $config->reload(); + + if ($this->view === 'user') { + if ($obj->username === $this->grav['user']->username) { + //Editing current user. Reload user object + unset($this->grav['user']->avatar); + $this->grav['user']->merge(User::load($this->admin->route)->toArray()); + } + } + } + + // Always redirect if a page route was changed, to refresh it + if ($obj instanceof Page) { + if (method_exists($obj, 'unsetRouteSlug')) { + $obj->unsetRouteSlug(); + } + + $multilang = $this->isMultilang(); + + if ($multilang) { + if (!$obj->language()) { + $obj->language($this->grav['session']->admin_lang); + } + } + $admin_route = $this->admin->base; + + $route = $obj->rawRoute(); + $redirect_url = ($multilang ? '/' . $obj->language() : '') . $admin_route . '/' . $this->view . $route; + $this->setRedirect($redirect_url); + } + + return true; + } + + /** + * @param string $frontmatter + * + * @return bool + */ + public function checkValidFrontmatter($frontmatter) + { + try { + // Try native PECL YAML PHP extension first if available. + if (function_exists('yaml_parse')) { + $saved = @ini_get('yaml.decode_php'); + @ini_set('yaml.decode_php', 0); + @yaml_parse("---\n" . $frontmatter . "\n..."); + @ini_set('yaml.decode_php', $saved); + } else { + Yaml::parse($frontmatter); + } + } catch (ParseException $e) { + return false; + } + + return true; + } + + /** + * Continue to the new page. + * + * @return bool True if the action was performed. + */ + public function taskContinue() + { + $data = (array)$this->data; + + if ($this->view === 'users') { + $username = strip_tags(strtolower($data['username'])); + $this->setRedirect("{$this->view}/{$username}"); + + return true; + } + + if ($this->view === 'groups') { + $this->setRedirect("{$this->view}/{$data['groupname']}"); + + return true; + } + + if ($this->view !== 'pages') { + return false; + } + + $route = $data['route'] !== '/' ? $data['route'] : ''; + $folder = $data['folder']; + // Handle @slugify-{field} value, automatically slugifies the specified field + if (0 === strpos($folder, '@slugify-')) { + $folder = \Grav\Plugin\Admin\Utils::slug($data[substr($folder, 9)]); + } + $folder = ltrim($folder, '_'); + if (!empty($data['modular'])) { + $folder = '_' . $folder; + } + $path = $route . '/' . $folder; + + $this->admin->session()->{$path} = $data; + + // Store the name and route of a page, to be used pre-filled defaults of the form in the future + $this->admin->session()->lastPageName = $data['name']; + $this->admin->session()->lastPageRoute = $data['route']; + + $this->setRedirect("{$this->view}/" . ltrim($path, '/')); + + return true; + } + + /** + * Toggle the gpm.releases setting + */ + protected function taskGpmRelease() + { + if (!$this->authorizeTask('configuration', ['admin.configuration', 'admin.super'])) { + return false; + } + + // Default release state + $release = 'stable'; + $reload = false; + + // Get the testing release value if set + if ($this->post['release'] === 'testing') { + $release = 'testing'; + } + + $config = $this->grav['config']; + $current_release = $config->get('system.gpm.releases'); + + // If the releases setting is different, save it in the system config + if ($current_release !== $release) { + $data = new Data\Data($config->get('system')); + $data->set('gpm.releases', $release); + + // Get the file location + $file = CompiledYamlFile::instance($this->grav['locator']->findResource('config://system.yaml')); + $data->file($file); + + // Save the configuration + $data->save(); + $config->reload(); + $reload = true; + } + + $this->admin->json_response = ['status' => 'success', 'reload' => $reload]; + + return true; + } + + /** + * Keep alive + */ + protected function taskKeepAlive() + { + exit(); + } + + protected function taskGetNewsFeed() + { + $cache = $this->grav['cache']; + + if ($this->post['refresh'] === 'true') { + $cache->delete('news-feed'); + } + + $feed_data = $cache->fetch('news-feed'); + + if (!$feed_data) { + try { + $feed = $this->admin->getFeed(); + if (is_object($feed)) { + + require_once __DIR__ . '/../classes/Twig/AdminTwigExtension.php'; + $adminTwigExtension = new AdminTwigExtension; + + $feed_items = $feed->getItems(); + + // Feed should only every contain 10, but just in case! + if (count($feed_items) > 10) { + $feed_items = array_slice($feed_items, 0, 10); + } + + foreach ($feed_items as $item) { + $datetime = $adminTwigExtension->adminNicetimeFilter($item->getDate()->getTimestamp()); + $feed_data[] = '
  • ' . $datetime . ' getTitle()) . '">' . $item->getTitle() . '
  • '; + } + } + + // cache for 1 hour + $cache->save('news-feed', $feed_data, 60 * 60); + + } catch (\Exception $e) { + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + + return; + } + } + + $this->admin->json_response = ['status' => 'success', 'feed_data' => $feed_data]; + } + + /** + * Get update status from GPM + */ + protected function taskGetUpdates() + { + $data = $this->post; + $flush = (isset($data['flush']) && $data['flush'] == true) ? true : false; + + if (isset($this->grav['session'])) { + $this->grav['session']->close(); + } + + try { + $gpm = new GravGPM($flush); + + $resources_updates = $gpm->getUpdatable(); + if ($gpm->grav != null) { + $grav_updates = [ + 'isUpdatable' => $gpm->grav->isUpdatable(), + 'assets' => $gpm->grav->getAssets(), + 'version' => GRAV_VERSION, + 'available' => $gpm->grav->getVersion(), + 'date' => $gpm->grav->getDate(), + 'isSymlink' => $gpm->grav->isSymlink() + ]; + + $this->admin->json_response = [ + 'status' => 'success', + 'payload' => [ + 'resources' => $resources_updates, + 'grav' => $grav_updates, + 'installed' => $gpm->countInstalled(), + 'flushed' => $flush + ] + ]; + } else { + $this->admin->json_response = ['status' => 'error', 'message' => 'Cannot connect to the GPM']; + } + + } catch (\Exception $e) { + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + } + + } + + /** + * Get Notifications from cache. + * + */ + protected function taskGetNotifications() + { + $cache = $this->grav['cache']; + if (!(bool)$this->grav['config']->get('system.cache.enabled') || !$notifications = $cache->fetch('notifications')) { + //No notifications cache (first time) + $this->admin->json_response = ['status' => 'success', 'notifications' => [], 'need_update' => true]; + + return; + } + + $need_update = false; + if (!$last_checked = $cache->fetch('notifications_last_checked')) { + $need_update = true; + } else { + if (time() - $last_checked > 86400) { + $need_update = true; + } + } + + try { + $notifications = $this->admin->processNotifications($notifications); + } catch (\Exception $e) { + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + + return; + } + + $this->admin->json_response = [ + 'status' => 'success', + 'notifications' => $notifications, + 'need_update' => $need_update + ]; + } + + /** + * Process Notifications. Store the notifications object locally. + * + * @return bool + */ + protected function taskProcessNotifications() + { + $cache = $this->grav['cache']; + + $data = $this->post; + $notifications = json_decode($data['notifications']); + + try { + $notifications = $this->admin->processNotifications($notifications); + } catch (\Exception $e) { + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + + return false; + } + + $show_immediately = false; + if (!$cache->fetch('notifications_last_checked')) { + $show_immediately = true; + } + + $cache->save('notifications', $notifications); + $cache->save('notifications_last_checked', time()); + + $this->admin->json_response = [ + 'status' => 'success', + 'notifications' => $notifications, + 'show_immediately' => $show_immediately + ]; + + return true; + } + + /** + * Handle getting a new package dependencies needed to be installed + * + * @return bool + */ + protected function taskGetPackagesDependencies() + { + $data = $this->post; + $packages = isset($data['packages']) ? explode(',', $data['packages']) : ''; + $packages = (array)$packages; + + try { + $this->admin->checkPackagesCanBeInstalled($packages); + $dependencies = $this->admin->getDependenciesNeededToInstall($packages); + } catch (\Exception $e) { + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + + return false; + } + + $this->admin->json_response = ['status' => 'success', 'dependencies' => $dependencies]; + + return true; + } + + protected function taskInstallDependenciesOfPackages() + { + $data = $this->post; + $packages = isset($data['packages']) ? explode(',', $data['packages']) : ''; + $packages = (array)$packages; + + $type = isset($data['type']) ? $data['type'] : ''; + + if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') + ]; + + return false; + } + + try { + $dependencies = $this->admin->getDependenciesNeededToInstall($packages); + } catch (\Exception $e) { + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + + return false; + } + + $result = Gpm::install(array_keys($dependencies), ['theme' => $type === 'theme']); + + if ($result) { + $this->admin->json_response = ['status' => 'success', 'message' => 'Dependencies installed successfully']; + } else { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED') + ]; + } + + return true; + } + + protected function taskInstallPackage($reinstall = false) + { + $data = $this->post; + $package = isset($data['package']) ? $data['package'] : ''; + $type = isset($data['type']) ? $data['type'] : ''; + + if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') + ]; + + return false; + } + + try { + $result = Gpm::install($package, ['theme' => $type === 'theme']); + } catch (\Exception $e) { + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + + return false; + } + + if ($result) { + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate(is_string($result) ? $result : sprintf($this->admin->translate($reinstall ?: 'PLUGIN_ADMIN.PACKAGE_X_REINSTALLED_SUCCESSFULLY', + null), $package)) + ]; + } else { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate($reinstall ?: 'PLUGIN_ADMIN.INSTALLATION_FAILED') + ]; + } + + return true; + } + + /** + * Handle removing a package + * + * @return bool + */ + protected function taskRemovePackage() + { + $data = $this->post; + $package = isset($data['package']) ? $data['package'] : ''; + $type = isset($data['type']) ? $data['type'] : ''; + + if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) { + $json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') + ]; + echo json_encode($json_response); + exit; + } + + //check if there are packages that have this as a dependency. Abort and show which ones + $dependent_packages = $this->admin->getPackagesThatDependOnPackage($package); + if (count($dependent_packages) > 0) { + if (count($dependent_packages) > 1) { + $message = 'The installed packages ' . implode(', ', + $dependent_packages) . ' depends on this package. Please remove those first.'; + } else { + $message = 'The installed package ' . implode(', ', + $dependent_packages) . ' depends on this package. Please remove it first.'; + } + + $json_response = ['status' => 'error', 'message' => $message]; + echo json_encode($json_response); + exit; + } + + try { + $dependencies = $this->admin->dependenciesThatCanBeRemovedWhenRemoving($package); + $result = Gpm::uninstall($package, []); + } catch (\Exception $e) { + $json_response = ['status' => 'error', 'message' => $e->getMessage()]; + echo json_encode($json_response); + exit; + } + + if ($result) { + $json_response = [ + 'status' => 'success', + 'dependencies' => $dependencies, + 'message' => $this->admin->translate(is_string($result) ? $result : 'PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL') + ]; + echo json_encode($json_response); + exit; + } + + $json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED') + ]; + echo json_encode($json_response); + exit; + } + + /** + * Handle reinstalling a package + */ + protected function taskReinstallPackage() + { + $data = $this->post; + + $slug = isset($data['slug']) ? $data['slug'] : ''; + $type = isset($data['type']) ? $data['type'] : ''; + $package_name = isset($data['package_name']) ? $data['package_name'] : ''; + $current_version = isset($data['current_version']) ? $data['current_version'] : ''; + + $url = "https://getgrav.org/download/{$type}s/$slug/$current_version"; + + $result = Gpm::directInstall($url); + + if ($result === true) { + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate(sprintf($this->admin->translate('PLUGIN_ADMIN.PACKAGE_X_REINSTALLED_SUCCESSFULLY', + null), $package_name)) + ]; + } else { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.REINSTALLATION_FAILED') + ]; + } + } + + /** + * Clear the cache. + * + * @return bool True if the action was performed. + */ + protected function taskClearCache() + { + if (!$this->authorizeTask('clear cache', ['admin.cache', 'admin.super', 'admin.maintenance'])) { + return false; + } + + // get optional cleartype param + $clear_type = $this->grav['uri']->param('cleartype'); + + if ($clear_type) { + $clear = $clear_type; + } else { + $clear = 'standard'; + } + + $results = Cache::clearCache($clear); + if (count($results) > 0) { + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate('PLUGIN_ADMIN.CACHE_CLEARED') . '
    ' . $this->admin->translate('PLUGIN_ADMIN.METHOD') . ': ' . $clear . '' + ]; + } else { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.ERROR_CLEARING_CACHE') + ]; + } + + return true; + } + + /** + * Clear the cache. + * + * @return bool True if the action was performed. + */ + protected function taskHideNotification() + { + if (!$this->authorizeTask('hide notification', ['admin.login'])) { + return false; + } + + $notification_id = $this->grav['uri']->param('notification_id'); + + if (!$notification_id) { + $this->admin->json_response = [ + 'status' => 'error' + ]; + + return false; + } + + $filename = $this->grav['locator']->findResource('user://data/notifications/' . $this->grav['user']->username . YAML_EXT, + true, true); + $file = CompiledYamlFile::instance($filename); + $data = $file->content(); + $data[] = $notification_id; + $file->save($data); + + $this->admin->json_response = [ + 'status' => 'success' + ]; + + return true; + } + + /** + * Handle the backup action + * + * @return bool True if the action was performed. + */ + protected function taskBackup() + { + $param_sep = $this->grav['config']->get('system.param_sep', ':'); + if (!$this->authorizeTask('backup', ['admin.maintenance', 'admin.super'])) { + return false; + } + + $download = $this->grav['uri']->param('download'); + + if ($download) { + $file = base64_decode(urldecode($download)); + $backups_root_dir = $this->grav['locator']->findResource('backup://', true); + + if (0 !== strpos($file, $backups_root_dir)) { + header('HTTP/1.1 401 Unauthorized'); + exit(); + } + + Utils::download($file, true); + } + + $log = JsonFile::instance($this->grav['locator']->findResource("log://backup.log", true, true)); + + try { + $backup = ZipBackup::backup(); + } catch (\Exception $e) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.AN_ERROR_OCCURRED') . '. ' . $e->getMessage() + ]; + + return true; + } + + $download = urlencode(base64_encode($backup)); + $url = rtrim($this->grav['uri']->rootUrl(true), '/') . '/' . trim($this->admin->base, + '/') . '/task' . $param_sep . 'backup/download' . $param_sep . $download . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form'); + + $log->content([ + 'time' => time(), + 'location' => $backup + ]); + $log->save(); + + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate('PLUGIN_ADMIN.YOUR_BACKUP_IS_READY_FOR_DOWNLOAD') . '. ' . $this->admin->translate('PLUGIN_ADMIN.DOWNLOAD_BACKUP') . '', + 'toastr' => [ + 'timeOut' => 0, + 'extendedTimeOut' => 0, + 'closeButton' => true + ] + ]; + + return true; + } + + protected function taskGetChildTypes() + { + if (!$this->authorizeTask('get childtypes', ['admin.pages', 'admin.super'])) { + return false; + } + + $data = $this->post; + + $rawroute = !empty($data['rawroute']) ? $data['rawroute'] : null; + + if ($rawroute) { + /** @var Page $page */ + $page = $this->grav['pages']->dispatch($rawroute); + + if ($page) { + $child_type = $page->childType(); + + if (isset($child_type)) { + $this->admin->json_response = [ + 'status' => 'success', + 'child_type' => $child_type + ]; + return true; + } + } + } + + $this->admin->json_response = [ + 'status' => 'success', + 'child_type' => '', + 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_CHILD_TYPE') + ]; + + return true; + } + + /** + * Handles filtering the page by modular/visible/routable in the pages list. + */ + protected function taskFilterPages() + { + if (!$this->authorizeTask('filter pages', ['admin.pages', 'admin.super'])) { + return; + } + + $data = $this->post; + + $flags = !empty($data['flags']) ? array_map('strtolower', explode(',', $data['flags'])) : []; + $queries = !empty($data['query']) ? explode(',', $data['query']) : []; + + /** @var Collection $collection */ + $collection = $this->grav['pages']->all(); + + if (count($flags)) { + // Filter by state + $pageStates = [ + 'modular', + 'nonmodular', + 'visible', + 'nonvisible', + 'routable', + 'nonroutable', + 'published', + 'nonpublished' + ]; + + if (count(array_intersect($pageStates, $flags)) > 0) { + if (in_array('modular', $flags, true)) { + $collection = $collection->modular(); + } + + if (in_array('nonmodular', $flags, true)) { + $collection = $collection->nonModular(); + } + + if (in_array('visible', $flags, true)) { + $collection = $collection->visible(); + } + + if (in_array('nonvisible', $flags, true)) { + $collection = $collection->nonVisible(); + } + + if (in_array('routable', $flags, true)) { + $collection = $collection->routable(); + } + + if (in_array('nonroutable', $flags, true)) { + $collection = $collection->nonRoutable(); + } + + if (in_array('published', $flags, true)) { + $collection = $collection->published(); + } + + if (in_array('nonpublished', $flags, true)) { + $collection = $collection->nonPublished(); + } + } + foreach ($pageStates as $pageState) { + if (($pageState = array_search($pageState, $flags, true)) !== false) { + unset($flags[$pageState]); + } + } + + // Filter by page type + if ($flags) { + $types = []; + + $pageTypes = array_keys(Pages::pageTypes()); + foreach ($pageTypes as $pageType) { + if (($pageKey = array_search($pageType, $flags)) !== false) { + $types[] = $pageType; + unset($flags[$pageKey]); + } + } + + if (count($types)) { + $collection = $collection->ofOneOfTheseTypes($types); + } + } + + // Filter by page type + if ($flags) { + $accessLevels = $flags; + $collection = $collection->ofOneOfTheseAccessLevels($accessLevels); + } + } + + if (!empty($queries)) { + foreach ($collection as $page) { + foreach ($queries as $query) { + $query = trim($query); + if (stripos($page->getRawContent(), $query) === false && stripos($page->title(), + $query) === false && stripos($page->slug(), \Grav\Plugin\Admin\Utils::slug($query)) === false && stripos($page->folder(), + $query) === false + ) { + $collection->remove($page); + } + } + } + } + + $results = []; + foreach ($collection as $path => $page) { + $results[] = $page->route(); + } + + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate('PLUGIN_ADMIN.PAGES_FILTERED'), + 'results' => $results + ]; + $this->admin->collection = $collection; + } + + /** + * Determines the file types allowed to be uploaded + * + * @return bool True if the action was performed. + */ + protected function taskListmedia() + { + if (!$this->authorizeTask('list media', ['admin.pages', 'admin.super'])) { + return false; + } + + $media = $this->getMedia(); + if (!$media) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND') + ]; + + return false; + } + + $media_list = []; + /** + * @var string $name + * @var Medium $medium + */ + foreach ($media->all() as $name => $medium) { + + $metadata = []; + $img_metadata = $medium->metadata(); + if ($img_metadata) { + $metadata = $img_metadata; + } + + // Get original name + $source = $medium->higherQualityAlternative(); + + $media_list[$name] = ['url' => $medium->display($medium->get('extension') === 'svg' ? 'source' : 'thumbnail')->cropZoom(400, 300)->url(), 'size' => $medium->get('size'), 'metadata' => $metadata, 'original' => $source->get('filename')]; + } + + $this->admin->json_response = ['status' => 'success', 'results' => $media_list]; + + return true; + } + + /** + * @return Media + */ + protected function getMedia() + { + $this->uri = $this->uri ?: $this->grav['uri']; + $uri = $this->uri->post('uri'); + if ($uri) { + /** @var UniformResourceLocator $locator */ + $locator = $this->grav['locator']; + + $media_path = $locator->isStream($uri) ? $uri : null; + } else { + $page = $this->admin->page(true); + + $media_path = $page ? $page->path() : null; + } + + return $media_path ? new Media($media_path) : null; + } + + /** + * Handles adding a media file to a page + * + * @return bool True if the action was performed. + */ + protected function taskAddmedia() + { + if (!$this->authorizeTask('add media', ['admin.pages', 'admin.super'])) { + return false; + } + + /** @var Config $config */ + $config = $this->grav['config']; + + if (!isset($_FILES['file']['error']) || is_array($_FILES['file']['error'])) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_PARAMETERS') + ]; + + return false; + } + + // Check $_FILES['file']['error'] value. + switch ($_FILES['file']['error']) { + case UPLOAD_ERR_OK: + break; + case UPLOAD_ERR_NO_FILE: + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_FILES_SENT') + ]; + + return false; + case UPLOAD_ERR_INI_SIZE: + case UPLOAD_ERR_FORM_SIZE: + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT') + ]; + + return false; + case UPLOAD_ERR_NO_TMP_DIR: + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR') + ]; + + return false; + default: + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.UNKNOWN_ERRORS') + ]; + + return false; + } + + $grav_limit = $config->get('system.media.upload_limit', 0); + // You should also check filesize here. + if ($grav_limit > 0 && $_FILES['file']['size'] > $grav_limit) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT') + ]; + + return false; + } + + + // Check extension + $fileParts = pathinfo($_FILES['file']['name']); + + $fileExt = ''; + if (isset($fileParts['extension'])) { + $fileExt = strtolower($fileParts['extension']); + } + + // If not a supported type, return + if (!$fileExt || !$config->get("media.types.{$fileExt}")) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $fileExt + ]; + + return false; + } + + + $media = $this->getMedia(); + if (!$media) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND') + ]; + + return false; + } + + // Upload it + if (!move_uploaded_file($_FILES['file']['tmp_name'], + sprintf('%s/%s', $media->path(), $_FILES['file']['name'])) + ) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.FAILED_TO_MOVE_UPLOADED_FILE') + ]; + + return false; + } + + // Add metadata if needed + $include_metadata = Grav::instance()['config']->get('system.media.auto_metadata_exif', false); + $filename = $fileParts['basename']; + $filename = str_replace(['@3x', '@2x'], '', $filename); + + $metadata = []; + + if ($include_metadata && isset($media[$filename])) { + $img_metadata = $media[$filename]->metadata(); + if ($img_metadata) { + $metadata = $img_metadata; + } + } + + $page = $this->admin->page(true); + if ($page) { + $this->grav->fireEvent('onAdminAfterAddMedia', new Event(['page' => $page])); + } + + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_UPLOADED_SUCCESSFULLY'), + 'metadata' => $metadata, + ]; + + return true; + } + + /** + * Handles deleting a media file from a page + * + * @return bool True if the action was performed. + */ + protected function taskDelmedia() + { + if (!$this->authorizeTask('delete media', ['admin.pages', 'admin.super'])) { + return false; + } + + $media = $this->getMedia(); + if (!$media) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND') + ]; + + return false; + } + + $filename = !empty($this->post['filename']) ? $this->post['filename'] : null; + + if (!$filename) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_FILE_FOUND') + ]; + + return false; + } + + $targetPath = $media->path() . '/' . $filename; + $fileParts = pathinfo($filename); + + $found = false; + + if (file_exists($targetPath)) { + $found = true; + $result = unlink($targetPath); + + if (!$result) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename + ]; + + return false; + } + } + + // Remove Extra Files + foreach (scandir($media->path(), SCANDIR_SORT_NONE) as $file) { + if (preg_match("/{$fileParts['filename']}@\d+x\.{$fileParts['extension']}(?:\.meta\.yaml)?$|{$filename}\.meta\.yaml$/", $file)) { + $result = unlink($media->path() . '/' . $file); + + if (!$result) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename + ]; + + return false; + } + + $found = true; + } + } + + if (!$found) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_NOT_FOUND') . ': ' . $filename + ]; + + return false; + } + + $page = $this->admin->page(true); + if ($page) { + $this->grav->fireEvent('onAdminAfterDelMedia', new Event(['page' => $page])); + } + + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_DELETED') . ': ' . $filename + ]; + + return true; + } + + /** + * Process the page Markdown + * + * @return bool True if the action was performed. + */ + protected function taskProcessMarkdown() + { + /*if (!$this->authorizeTask('process markdown', ['admin.pages', 'admin.super'])) { + return; + }*/ + + try { + $page = $this->admin->page(true); + + if (!$page) { + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND') + ]; + + return false; + } + + $this->preparePage($page, true); + $page->header(); + + // Add theme template paths to Twig loader + $template_paths = $this->grav['locator']->findResources('theme://templates'); + $this->grav['twig']->twig->getLoader()->addLoader(new \Twig_Loader_Filesystem($template_paths)); + + $html = $page->content(); + + $this->admin->json_response = ['status' => 'success', 'preview' => $html]; + } catch (\Exception $e) { + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + + return false; + } + + return true; + } + + /** + * Prepare a page to be stored: update its folder, name, template, header and content + * + * @param \Grav\Common\Page\Page $page + * @param bool $clean_header + * @param string $language + */ + protected function preparePage(Page $page, $clean_header = false, $language = '') + { + $input = (array)$this->data; + + if (isset($input['folder']) && $input['folder'] !== $page->value('folder')) { + $order = $page->value('order'); + $ordering = $order ? sprintf('%02d.', $order) : ''; + $page->folder($ordering . $input['folder']); + } + + if (isset($input['name']) && !empty($input['name'])) { + $type = strtolower($input['name']); + $name = preg_replace('|.*/|', '', $type); + if ($language) { + $name .= '.' . $language; + } else { + $language = $this->grav['language']; + if ($language->enabled()) { + $name .= '.' . $language->getLanguage(); + } + } + $name .= '.md'; + $page->name($name); + $page->template($type); + } + + // Special case for Expert mode: build the raw, unset content + if (isset($input['frontmatter'], $input['content'])) { + $page->raw("---\n" . (string)$input['frontmatter'] . "\n---\n" . (string)$input['content']); + unset($input['content']); + // Handle header normally + } elseif (isset($input['header'])) { + $header = $input['header']; + + foreach ($header as $key => $value) { + if ($key === 'metadata' && is_array($header[$key])) { + foreach ($header['metadata'] as $key2 => $value2) { + if (isset($input['toggleable_header']['metadata'][$key2]) && !$input['toggleable_header']['metadata'][$key2]) { + $header['metadata'][$key2] = ''; + } + } + } elseif ($key === 'taxonomy' && is_array($header[$key])) { + foreach ($header[$key] as $taxkey => $taxonomy) { + if (is_array($taxonomy) && count($taxonomy) == 1 && trim($taxonomy[0]) == '') { + unset($header[$key][$taxkey]); + } + } + } else { + if (isset($input['toggleable_header'][$key]) && !$input['toggleable_header'][$key]) { + $header[$key] = null; + } + } + } + if ($clean_header) { + $header = Utils::arrayFilterRecursive($header, function ($k, $v) { + return !(null === $v || $v === ''); + }); + } + $page->header((object)$header); + $page->frontmatter(Yaml::dump((array)$page->header()), 20); + } + // Fill content last because it also renders the output. + if (isset($input['content'])) { + $page->rawMarkdown((string)$input['content']); + } + } + + /** + * Save page as a new copy. + * + * @return bool True if the action was performed. + * @throws \RuntimeException + */ + protected function taskCopy() + { + if (!$this->authorizeTask('copy page', ['admin.pages', 'admin.super'])) { + return false; + } + + // Only applies to pages. + if ($this->view !== 'pages') { + return false; + } + + try { + /** @var Pages $pages */ + $pages = $this->grav['pages']; + + // Get the current page. + $original_page = $this->admin->page(true); + + // Find new parent page in order to build the path. + $parent = $original_page->parent() ?: $pages->root(); + // Make a copy of the current page and fill the updated information into it. + $page = $original_page->copy($parent); + + $order = 0; + if ($page->order()) { + $order = $this->getNextOrderInFolder($page->parent()->path()); + } + + // Make sure the header is loaded in case content was set through raw() (expert mode) + $page->header(); + + if ($page->order()) { + $page->order($order); + } + + $folder = $this->findFirstAvailable('folder', $page); + $slug = $this->findFirstAvailable('slug', $page); + + $page->path($page->parent()->path() . DS . $page->order() . $folder); + $page->route($page->parent()->route() . '/' . $slug); + $page->rawRoute($page->parent()->rawRoute() . '/' . $slug); + + // Append progressive number to the copied page title + $match = preg_split('/(\d+)(?!.*\d)/', $original_page->title(), 2, PREG_SPLIT_DELIM_CAPTURE); + $header = $page->header(); + if (!isset($match[1])) { + $header->title = $match[0] . ' 2'; + } else { + $header->title = $match[0] . ((int)$match[1] + 1); + } + + $page->header($header); + $page->save(false); + + $redirect = $this->view . $page->rawRoute(); + $header = $page->header(); + + if (isset($header->slug)) { + $match = preg_split('/-(\d+)$/', $header->slug, 2, PREG_SPLIT_DELIM_CAPTURE); + $header->slug = $match[0] . '-' . (isset($match[1]) ? (int)$match[1] + 1 : 2); + } + + $page->header($header); + + $page->save(); + + $this->grav->fireEvent('onAdminAfterSave', new Event(['page' => $page])); + + // Enqueue message and redirect to new location. + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_COPIED'), 'info'); + $this->setRedirect($redirect); + + } catch (\Exception $e) { + throw new \RuntimeException('Copying page failed on error: ' . $e->getMessage()); + } + + return true; + } + + /** + * Find the first available $item ('slug' | 'folder') for a page + * Used when copying a page, to determine the first available slot + * + * @param string $item + * @param Page $page + * + * @return string The first available slot + */ + protected function findFirstAvailable($item, $page) + { + if (!$page->parent()->children()) { + return $page->$item(); + } + + $withoutPrefix = function ($string) { + $match = preg_split('/^[0-9]+\./u', $string, 2, PREG_SPLIT_DELIM_CAPTURE); + + return isset($match[1]) ? $match[1] : $match[0]; + }; + + $withoutPostfix = function ($string) { + $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE); + + return $match[0]; + }; + + /* $appendedNumber = function ($string) { + $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE); + $append = (isset($match[1]) ? (int)$match[1] + 1 : 2); + + return $append; + };*/ + + $highest = 1; + $siblings = $page->parent()->children(); + $findCorrectAppendedNumber = function ($item, $page_item, $highest) use ( + $siblings, + &$findCorrectAppendedNumber, + &$withoutPrefix + ) { + foreach ($siblings as $sibling) { + if ($withoutPrefix($sibling->$item()) == ($highest === 1 ? $page_item : $page_item . '-' . $highest)) { + $highest = $findCorrectAppendedNumber($item, $page_item, $highest + 1); + + return $highest; + } + } + + return $highest; + }; + + $base = $withoutPrefix($withoutPostfix($page->$item())); + + $return = $base; + $highest = $findCorrectAppendedNumber($item, $base, $highest); + + if ($highest > 1) { + $return .= '-' . $highest; + } + + return $return; + } + + /** + * Reorder pages. + * + * @return bool True if the action was performed. + */ + protected function taskReorder() + { + if (!$this->authorizeTask('reorder pages', ['admin.pages', 'admin.super'])) { + return false; + } + + // Only applies to pages. + if ($this->view !== 'pages') { + return false; + } + + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.REORDERING_WAS_SUCCESSFUL'), 'info'); + + return true; + } + + /** + * Delete page. + * + * @return bool True if the action was performed. + * @throws \RuntimeException + */ + protected function taskDelete() + { + if (!$this->authorizeTask('delete page', ['admin.pages', 'admin.super'])) { + return false; + } + + // Only applies to pages. + if ($this->view !== 'pages') { + return false; + } + + try { + $page = $this->admin->page(); + + if (count($page->translatedLanguages()) > 1) { + $page->file()->delete(); + } else { + Folder::delete($page->path()); + } + + $this->grav->fireEvent('onAdminAfterDelete', new Event(['page' => $page])); + + Cache::clearCache('standard'); + + // Set redirect to either referrer or pages list. + $redirect = 'pages'; + + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_DELETED'), 'info'); + $this->setRedirect($redirect); + + } catch (\Exception $e) { + throw new \RuntimeException('Deleting page failed on error: ' . $e->getMessage()); + } + + return true; + } + + /** + * Switch the content language. Optionally redirect to a different page. + * + */ + protected function taskSwitchlanguage() + { + $data = (array)$this->data; + + if (isset($data['lang'])) { + $language = $data['lang']; + } else { + $language = $this->grav['uri']->param('lang'); + } + + if (isset($data['redirect'])) { + $redirect = 'pages/' . $data['redirect']; + } else { + $redirect = 'pages'; + } + + + if ($language) { + $this->grav['session']->admin_lang = $language ?: 'en'; + } + + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info'); + + $admin_route = $this->admin->base; + $this->setRedirect('/' . $language . $admin_route . '/' . $redirect); + } + + /** + * 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->template($obj->template()); + $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; + } + + /** + * The what should be the new filename when saving as a new language + * + * @param string $current_filename the current file name, including .md. Example: default.en.md + * @param string $language The new language it will be saved as. Example: 'it' or 'en-GB'. + * + * @return string The new filename. Example: 'default.it' + */ + public function determineFilenameIncludingLanguage($current_filename, $language) + { + $filename = substr($current_filename, 0, -strlen('.md')); + + if (substr($filename, -3, 1) === '.') { + $filename = str_replace(substr($filename, -2), $language, $filename); + } elseif (substr($filename, -6, 1) === '.') { + $filename = str_replace(substr($filename, -5), $language, $filename); + } else { + $filename .= '.' . $language; + } + + return $filename . '.md'; + } + + /** + * Handle direct install. + */ + protected function taskDirectInstall() + { + $file_path = isset($this->data['file_path']) ? $this->data['file_path'] : null ; + + if (isset($_FILES['uploaded_file'])) { + + // Check $_FILES['file']['error'] value. + switch ($_FILES['uploaded_file']['error']) { + case UPLOAD_ERR_OK: + break; + case UPLOAD_ERR_NO_FILE: + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.NO_FILES_SENT'), 'error'); + return false; + case UPLOAD_ERR_INI_SIZE: + case UPLOAD_ERR_FORM_SIZE: + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT'), 'error'); + return false; + case UPLOAD_ERR_NO_TMP_DIR: + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR'), 'error'); + return false; + default: + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNKNOWN_ERRORS'), 'error'); + return false; + } + + $file_path = $_FILES['uploaded_file']['tmp_name']; + } + + + $result = Gpm::directInstall($file_path); + + if ($result === true) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info'); + } else { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED') . ': ' . $result, + 'error'); + } + + $this->setRedirect('/tools'); + + return true; + } +} diff --git a/user/plugins/admin/classes/gpm.php b/user/plugins/admin/classes/gpm.php new file mode 100644 index 0000000..acddb08 --- /dev/null +++ b/user/plugins/admin/classes/gpm.php @@ -0,0 +1,383 @@ +loadRemoteGrav(); + } + } + + return static::$GPM; + } + + /** + * Default options for the install + * + * @var array + */ + protected static $options = [ + 'destination' => GRAV_ROOT, + 'overwrite' => true, + 'ignore_symlinks' => true, + 'skip_invalid' => true, + 'install_deps' => true, + 'theme' => false + ]; + + /** + * @param Package[]|string[]|string $packages + * @param array $options + * + * @return bool + */ + public static function install($packages, array $options) + { + $options = array_merge(self::$options, $options); + + if (!Installer::isGravInstance($options['destination']) || !Installer::isValidDestination($options['destination'], + [Installer::EXISTS, Installer::IS_LINK]) + ) { + return false; + } + + $packages = is_array($packages) ? $packages : [$packages]; + $count = count($packages); + + $packages = array_filter(array_map(function ($p) { + return !is_string($p) ? $p instanceof Package ? $p : false : self::GPM()->findPackage($p); + }, $packages)); + + if (!$options['skip_invalid'] && $count !== count($packages)) { + return false; + } + + $messages = ''; + + foreach ($packages as $package) { + if (isset($package->dependencies) && $options['install_deps']) { + $result = static::install($package->dependencies, $options); + + if (!$result) { + return false; + } + } + + // Check destination + Installer::isValidDestination($options['destination'] . DS . $package->install_path); + + if (Installer::lastErrorCode() === Installer::EXISTS && !$options['overwrite']) { + return false; + } + + if (Installer::lastErrorCode() === Installer::IS_LINK && !$options['ignore_symlinks']) { + return false; + } + + $license = Licenses::get($package->slug); + $local = static::download($package, $license); + + Installer::install($local, $options['destination'], + ['install_path' => $package->install_path, 'theme' => $options['theme']]); + Folder::delete(dirname($local)); + + $errorCode = Installer::lastErrorCode(); + if ($errorCode) { + $msg = Installer::lastErrorMsg(); + throw new \RuntimeException($msg); + } + + if (count($packages) === 1) { + $message = Installer::getMessage(); + if ($message) { + return $message; + } + + $messages .= $message; + } + } + + return $messages ?: true; + } + + /** + * @param Package[]|string[]|string $packages + * @param array $options + * + * @return bool + */ + public static function update($packages, array $options) + { + $options['overwrite'] = true; + + return static::install($packages, $options); + } + + /** + * @param Package[]|string[]|string $packages + * @param array $options + * + * @return bool + */ + public static function uninstall($packages, array $options) + { + $options = array_merge(self::$options, $options); + + $packages = is_array($packages) ? $packages : [$packages]; + $count = count($packages); + + $packages = array_filter(array_map(function ($p) { + + if (is_string($p)) { + $p = strtolower($p); + $plugin = static::GPM()->getInstalledPlugin($p); + $p = $plugin ?: static::GPM()->getInstalledTheme($p); + } + + return $p instanceof Package ? $p : false; + + }, $packages)); + + if (!$options['skip_invalid'] && $count !== count($packages)) { + return false; + } + + foreach ($packages as $package) { + + $location = Grav::instance()['locator']->findResource($package->package_type . '://' . $package->slug); + + // Check destination + Installer::isValidDestination($location); + + if (!$options['ignore_symlinks'] && Installer::lastErrorCode() === Installer::IS_LINK) { + return false; + } + + Installer::uninstall($location); + + $errorCode = Installer::lastErrorCode(); + if ($errorCode && $errorCode !== Installer::IS_LINK && $errorCode !== Installer::EXISTS) { + $msg = Installer::lastErrorMsg(); + throw new \RuntimeException($msg); + } + + if (count($packages) === 1) { + $message = Installer::getMessage(); + if ($message) { + return $message; + } + } + } + + return true; + } + + /** + * Direct install a file + * + * @param $package_file + * + * @return bool + */ + public static function directInstall($package_file) + { + if (!$package_file) { + return Admin::translate('PLUGIN_ADMIN.NO_PACKAGE_NAME'); + } + + $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true); + $tmp_zip = $tmp_dir . '/Grav-' . uniqid(); + + if (Response::isRemote($package_file)) { + $zip = GravGPM::downloadPackage($package_file, $tmp_zip); + } else { + $zip = GravGPM::copyPackage($package_file, $tmp_zip); + } + + if (file_exists($zip)) { + $tmp_source = $tmp_dir . '/Grav-' . uniqid(); + $extracted = Installer::unZip($zip, $tmp_source); + + if (!$extracted) { + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + return Admin::translate('PLUGIN_ADMIN.PACKAGE_EXTRACTION_FAILED'); + } + + $type = GravGPM::getPackageType($extracted); + + if (!$type) { + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + return Admin::translate('PLUGIN_ADMIN.NOT_VALID_GRAV_PACKAGE'); + } + + if ($type === 'grav') { + Installer::isValidDestination(GRAV_ROOT . '/system'); + if (Installer::IS_LINK === Installer::lastErrorCode()) { + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + return Admin::translate('PLUGIN_ADMIN.CANNOT_OVERWRITE_SYMLINKS'); + } + Installer::install($zip, GRAV_ROOT, + ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true, 'ignores' => ['tmp','user','vendor']], $extracted); + } else { + $name = GravGPM::getPackageName($extracted); + + if (!$name) { + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + return Admin::translate('PLUGIN_ADMIN.NAME_COULD_NOT_BE_DETERMINED'); + } + + $install_path = GravGPM::getInstallPath($type, $name); + $is_update = file_exists($install_path); + + Installer::isValidDestination(GRAV_ROOT . DS . $install_path); + if (Installer::lastErrorCode() === Installer::IS_LINK) { + Folder::delete($tmp_source); + Folder::delete($tmp_zip); + return Admin::translate('PLUGIN_ADMIN.CANNOT_OVERWRITE_SYMLINKS'); + } + + Installer::install($zip, GRAV_ROOT, + ['install_path' => $install_path, 'theme' => $type === 'theme', 'is_update' => $is_update], + $extracted); + } + + Folder::delete($tmp_source); + + if (Installer::lastErrorCode()) { + return Installer::lastErrorMsg(); + } + + } else { + return Admin::translate('PLUGIN_ADMIN.ZIP_PACKAGE_NOT_FOUND'); + } + + Folder::delete($tmp_zip); + + return true; + } + + /** + * @param Package $package + * + * @return string + */ + private static function download(Package $package, $license = null) + { + $query = ''; + + if ($package->premium) { + $query = \json_encode(array_merge($package->premium, [ + 'slug' => $package->slug, + 'filename' => $package->premium['filename'], + 'license_key' => $license + ])); + + $query = '?d=' . base64_encode($query); + } + + try { + $contents = Response::get($package->zipball_url . $query, []); + } catch (\Exception $e) { + throw new \RuntimeException($e->getMessage()); + } + + $tmp_dir = Admin::getTempDir() . '/Grav-' . uniqid(); + Folder::mkdir($tmp_dir); + + $bad_chars = array_merge(array_map('chr', range(0, 31)), ["<", ">", ":", '"', "/", "\\", "|", "?", "*"]); + + $filename = $package->slug . str_replace($bad_chars, "", basename($package->zipball_url)); + $filename = preg_replace('/[\\\\\/:"*?&<>|]+/mi', '-', $filename); + + file_put_contents($tmp_dir . DS . $filename . '.zip', $contents); + + return $tmp_dir . DS . $filename . '.zip'; + } + + /** + * @param array $package + * @param string $tmp + * + * @return string + */ + private static function _downloadSelfupgrade(array $package, $tmp) + { + $output = Response::get($package['download'], []); + Folder::mkdir($tmp); + file_put_contents($tmp . DS . $package['name'], $output); + + return $tmp . DS . $package['name']; + } + + /** + * @return bool + */ + public static function selfupgrade() + { + $upgrader = new Upgrader(); + + if (!Installer::isGravInstance(GRAV_ROOT)) { + return false; + } + + if (is_link(GRAV_ROOT . DS . 'index.php')) { + Installer::setError(Installer::IS_LINK); + + return false; + } + + if (method_exists($upgrader, 'meetsRequirements') && + method_exists($upgrader, 'minPHPVersion') && + !$upgrader->meetsRequirements()) { + $error = []; + $error[] = '

    Grav has increased the minimum PHP requirement.
    '; + $error[] = 'You are currently running PHP ' . phpversion() . ''; + $error[] = ', but PHP ' . $upgrader->minPHPVersion() . ' is required.

    '; + $error[] = '

    Additional information

    '; + + Installer::setError(implode("\n", $error)); + + return false; + } + + $update = $upgrader->getAssets()['grav-update']; + $tmp = Admin::getTempDir() . '/Grav-' . uniqid(); + $file = self::_downloadSelfupgrade($update, $tmp); + + Installer::install($file, GRAV_ROOT, ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true]); + + $errorCode = Installer::lastErrorCode(); + + Folder::delete($tmp); + + return !($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)); + } +} diff --git a/user/plugins/admin/classes/popularity.php b/user/plugins/admin/classes/popularity.php new file mode 100644 index 0000000..ffa138b --- /dev/null +++ b/user/plugins/admin/classes/popularity.php @@ -0,0 +1,295 @@ +config = Grav::instance()['config']; + + $this->data_path = Grav::instance()['locator']->findResource('log://popularity', true, true); + $this->daily_file = $this->data_path . '/' . self::DAILY_FILE; + $this->monthly_file = $this->data_path . '/' . self::MONTHLY_FILE; + $this->totals_file = $this->data_path . '/' . self::TOTALS_FILE; + $this->visitors_file = $this->data_path . '/' . self::VISITORS_FILE; + + } + + public function trackHit() + { + // Don't track bot or crawler requests + if (!Grav::instance()['browser']->isHuman()) { + return; + } + + /** @var Page $page */ + $page = Grav::instance()['page']; + $relative_url = str_replace(Grav::instance()['base_url_relative'], '', $page->url()); + + // Don't track error pages or pages that have no route + if ($page->template() === 'error' || !$page->route()) { + return; + } + + // Make sure no 'widcard-style' ignore matches this url + foreach ((array)$this->config->get('plugins.admin.popularity.ignore') as $ignore) { + if (fnmatch($ignore, $relative_url)) { + return; + } + } + + // initial creation if it doesn't exist + if (!file_exists($this->data_path)) { + mkdir($this->data_path); + $this->flushPopularity(); + } + + // Update the data we want to track + $this->updateDaily(); + $this->updateMonthly(); + $this->updateTotals($page->route()); + $this->updateVisitors(Grav::instance()['uri']->ip()); + + } + + protected function updateDaily() + { + + if (!$this->daily_data) { + $this->daily_data = $this->getData($this->daily_file); + } + + $day_month_year = date(self::DAILY_FORMAT); + + // get the daily access count + if (array_key_exists($day_month_year, $this->daily_data)) { + $this->daily_data[$day_month_year] = (int)$this->daily_data[$day_month_year] + 1; + } else { + $this->daily_data[$day_month_year] = 1; + } + + // keep correct number as set by history + $count = (int)$this->config->get('plugins.admin.popularity.history.daily', 30); + $total = count($this->daily_data); + + if ($total > $count) { + $this->daily_data = array_slice($this->daily_data, -$count, $count, true); + } + + file_put_contents($this->daily_file, json_encode($this->daily_data)); + } + + /** + * @return array + */ + public function getDailyChartData() + { + if (!$this->daily_data) { + $this->daily_data = $this->getData($this->daily_file); + } + + $limit = (int)$this->config->get('plugins.admin.popularity.dashboard.days_of_stats', 7); + $chart_data = array_slice($this->daily_data, -$limit, $limit); + + $labels = []; + $data = []; + + foreach ($chart_data as $date => $count) { + $labels[] = Grav::instance()['grav']['admin']->translate([ + 'PLUGIN_ADMIN.' . strtoupper(date('D', strtotime($date)))]) . + '
    ' . date('M d', strtotime($date)); + $data[] = $count; + } + + return ['labels' => $labels, 'data' => $data]; + } + + /** + * @return int + */ + public function getDailyTotal() + { + if (!$this->daily_data) { + $this->daily_data = $this->getData($this->daily_file); + } + + if (isset($this->daily_data[date(self::DAILY_FORMAT)])) { + return $this->daily_data[date(self::DAILY_FORMAT)]; + } + + return 0; + } + + /** + * @return int + */ + public function getWeeklyTotal() + { + if (!$this->daily_data) { + $this->daily_data = $this->getData($this->daily_file); + } + + $day = 0; + $total = 0; + foreach (array_reverse($this->daily_data) as $daily) { + $total += $daily; + $day++; + if ($day === 7) { + break; + } + } + + return $total; + } + + /** + * @return int + */ + public function getMonthlyTotal() + { + if (!$this->monthly_data) { + $this->monthly_data = $this->getData($this->monthly_file); + } + if (isset($this->monthly_data[date(self::MONTHLY_FORMAT)])) { + return $this->monthly_data[date(self::MONTHLY_FORMAT)]; + } + + return 0; + } + + protected function updateMonthly() + { + + if (!$this->monthly_data) { + $this->monthly_data = $this->getData($this->monthly_file); + } + + $month_year = date(self::MONTHLY_FORMAT); + + // get the monthly access count + if (array_key_exists($month_year, $this->monthly_data)) { + $this->monthly_data[$month_year] = (int)$this->monthly_data[$month_year] + 1; + } else { + $this->monthly_data[$month_year] = 1; + } + + // keep correct number as set by history + $count = (int)$this->config->get('plugins.admin.popularity.history.monthly', 12); + $total = count($this->monthly_data); + $this->monthly_data = array_slice($this->monthly_data, $total - $count, $count); + + + file_put_contents($this->monthly_file, json_encode($this->monthly_data)); + } + + /** + * @return array + */ + protected function getMonthyChartData() + { + if (!$this->monthly_data) { + $this->monthly_data = $this->getData($this->monthly_file); + } + + $labels = []; + $data = []; + + foreach ($this->monthly_data as $date => $count) { + $labels[] = date('M', strtotime($date)); + $data[] = $count; + } + + return ['labels' => $labels, 'data' => $data]; + } + + /** + * @param string $url + */ + protected function updateTotals($url) + { + if (!$this->totals_data) { + $this->totals_data = $this->getData($this->totals_file); + } + + // get the totals for this url + if (array_key_exists($url, $this->totals_data)) { + $this->totals_data[$url] = (int)$this->totals_data[$url] + 1; + } else { + $this->totals_data[$url] = 1; + } + + file_put_contents($this->totals_file, json_encode($this->totals_data)); + } + + /** + * @param string $ip + */ + protected function updateVisitors($ip) + { + if (!$this->visitors_data) { + $this->visitors_data = $this->getData($this->visitors_file); + } + + // update with current timestamp + $this->visitors_data[hash('sha1', $ip)] = time(); + $visitors = $this->visitors_data; + arsort($visitors); + + $count = (int)$this->config->get('plugins.admin.popularity.history.visitors', 20); + $this->visitors_data = array_slice($visitors, 0, $count, true); + + file_put_contents($this->visitors_file, json_encode($this->visitors_data)); + } + + /** + * @param string $path + * + * @return array + */ + protected function getData($path) + { + if (file_exists($path)) { + return (array)json_decode(file_get_contents($path), true); + } + + return []; + } + + + public function flushPopularity() + { + file_put_contents($this->daily_file, []); + file_put_contents($this->monthly_file, []); + file_put_contents($this->totals_file, []); + file_put_contents($this->visitors_file, []); + } +} diff --git a/user/plugins/admin/classes/themes.php b/user/plugins/admin/classes/themes.php new file mode 100644 index 0000000..519a0fa --- /dev/null +++ b/user/plugins/admin/classes/themes.php @@ -0,0 +1,21 @@ +grav['themes']; + $themes->configure(); + $themes->initTheme(); + + $this->grav->fireEvent('onAdminThemeInitialized'); + } +} diff --git a/user/plugins/admin/classes/utils.php b/user/plugins/admin/classes/utils.php new file mode 100644 index 0000000..957b2bc --- /dev/null +++ b/user/plugins/admin/classes/utils.php @@ -0,0 +1,60 @@ +findResource('account://'); + $files = array_diff(scandir($account_dir, SCANDIR_SORT_ASCENDING), ['.', '..']); + + 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); + } + + /** + * Generates a slug of the given string + * + * @param string $str + * @return string + */ + public static function slug($str) + { + if (function_exists('transliterator_transliterate')) { + $str = transliterator_transliterate('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove;', $str); + } else { + $str = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $str); + } + + $str = strtolower($str); + $str = preg_replace('/[-\s]+/', '-', $str); + $str = preg_replace('/[^a-z0-9-]/i', '', $str); + $str = trim($str, '-'); + + return $str; + } +} diff --git a/user/plugins/admin/codeception.yml b/user/plugins/admin/codeception.yml new file mode 100644 index 0000000..7d317a5 --- /dev/null +++ b/user/plugins/admin/codeception.yml @@ -0,0 +1,18 @@ +actor: Tester +paths: + tests: tests + log: tests/_output + data: tests/_data + support: tests/_support + envs: tests/_envs +settings: + bootstrap: _bootstrap.php + colors: true + memory_limit: 1024M +extensions: + enabled: + - Codeception\Extension\RunFailed + # - Codeception\Extension\Recorder + +modules: + config: diff --git a/user/plugins/admin/composer.json b/user/plugins/admin/composer.json new file mode 100644 index 0000000..c8786b6 --- /dev/null +++ b/user/plugins/admin/composer.json @@ -0,0 +1,18 @@ +{ + "require": { + "composer/semver": "^1.4", + "fguillot/picofeed": "@stable" + }, + "require-dev": { + "codeception/codeception": "^2.1", + "fzaninotto/faker": "^1.5", + "symfony/yaml": "~2.8", + "symfony/console": "~2.8", + "symfony/finder": "~2.8", + "symfony/event-dispatcher": "~2.8" + }, + "scripts": { + "test": "vendor/bin/codecept run unit", + "test-windows": "vendor\\bin\\codecept run unit" + } +} diff --git a/user/plugins/admin/composer.lock b/user/plugins/admin/composer.lock new file mode 100644 index 0000000..6852cb1 --- /dev/null +++ b/user/plugins/admin/composer.lock @@ -0,0 +1,2796 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "9d176f21be9e6aa53b047ac12215bb45", + "packages": [ + { + "name": "composer/semver", + "version": "1.4.2", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "c7cb9a2095a074d131b65a8a0cd294479d785573" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/c7cb9a2095a074d131b65a8a0cd294479d785573", + "reference": "c7cb9a2095a074d131b65a8a0cd294479d785573", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.5 || ^5.0.5", + "phpunit/phpunit-mock-objects": "2.3.0 || ^3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "time": "2016-08-30T16:08:34+00:00" + }, + { + "name": "fguillot/picofeed", + "version": "v0.1.37", + "source": { + "type": "git", + "url": "https://github.com/miniflux/picoFeed.git", + "reference": "402b7f07629577e7929625e78bc88d3d5831a22d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/miniflux/picoFeed/zipball/402b7f07629577e7929625e78bc88d3d5831a22d", + "reference": "402b7f07629577e7929625e78bc88d3d5831a22d", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-iconv": "*", + "ext-libxml": "*", + "ext-simplexml": "*", + "ext-xml": "*", + "php": ">=5.3.0", + "zendframework/zendxml": "^1.0" + }, + "require-dev": { + "phpdocumentor/reflection-docblock": "2.0.4", + "phpunit/phpunit": "4.8.26", + "symfony/yaml": "2.8.7" + }, + "suggest": { + "ext-curl": "PicoFeed will use cURL if present" + }, + "bin": [ + "picofeed" + ], + "type": "library", + "autoload": { + "psr-0": { + "PicoFeed": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frédéric Guillot" + } + ], + "description": "Modern library to handle RSS/Atom feeds", + "homepage": "https://github.com/miniflux/picoFeed", + "abandoned": true, + "time": "2017-11-02T03:20:36+00:00" + }, + { + "name": "zendframework/zendxml", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/zendframework/ZendXml.git", + "reference": "267db6a2c431a08a8f8ff0f1f4c302a5ba6f5b99" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/ZendXml/zipball/267db6a2c431a08a8f8ff0f1f4c302a5ba6f5b99", + "reference": "267db6a2c431a08a8f8ff0f1f4c302a5ba6f5b99", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.4", + "zendframework/zend-coding-standard": "~1.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev", + "dev-develop": "1.2.x-dev" + } + }, + "autoload": { + "psr-4": { + "ZendXml\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "Utility library for XML usage, best practices, and security in PHP", + "keywords": [ + "ZendFramework", + "security", + "xml", + "zf" + ], + "time": "2018-04-30T15:11:04+00:00" + } + ], + "packages-dev": [ + { + "name": "behat/gherkin", + "version": "v4.5.1", + "source": { + "type": "git", + "url": "https://github.com/Behat/Gherkin.git", + "reference": "74ac03d52c5e23ad8abd5c5cce4ab0e8dc1b530a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Behat/Gherkin/zipball/74ac03d52c5e23ad8abd5c5cce4ab0e8dc1b530a", + "reference": "74ac03d52c5e23ad8abd5c5cce4ab0e8dc1b530a", + "shasum": "" + }, + "require": { + "php": ">=5.3.1" + }, + "require-dev": { + "phpunit/phpunit": "~4.5|~5", + "symfony/phpunit-bridge": "~2.7|~3", + "symfony/yaml": "~2.3|~3" + }, + "suggest": { + "symfony/yaml": "If you want to parse features, represented in YAML files" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.4-dev" + } + }, + "autoload": { + "psr-0": { + "Behat\\Gherkin": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Konstantin Kudryashov", + "email": "ever.zet@gmail.com", + "homepage": "http://everzet.com" + } + ], + "description": "Gherkin DSL parser for PHP 5.3", + "homepage": "http://behat.org/", + "keywords": [ + "BDD", + "Behat", + "Cucumber", + "DSL", + "gherkin", + "parser" + ], + "time": "2017-08-30T11:04:43+00:00" + }, + { + "name": "codeception/codeception", + "version": "2.4.1", + "source": { + "type": "git", + "url": "https://github.com/Codeception/Codeception.git", + "reference": "bca3547632556875f1cdd567d6057cc14fe472b8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Codeception/Codeception/zipball/bca3547632556875f1cdd567d6057cc14fe472b8", + "reference": "bca3547632556875f1cdd567d6057cc14fe472b8", + "shasum": "" + }, + "require": { + "behat/gherkin": "^4.4.0", + "codeception/phpunit-wrapper": "^6.0.9|^7.0.6", + "codeception/stub": "^1.0", + "ext-json": "*", + "ext-mbstring": "*", + "facebook/webdriver": ">=1.1.3 <2.0", + "guzzlehttp/guzzle": ">=4.1.4 <7.0", + "guzzlehttp/psr7": "~1.0", + "php": ">=5.4.0 <8.0", + "symfony/browser-kit": ">=2.7 <5.0", + "symfony/console": ">=2.7 <5.0", + "symfony/css-selector": ">=2.7 <5.0", + "symfony/dom-crawler": ">=2.7 <5.0", + "symfony/event-dispatcher": ">=2.7 <5.0", + "symfony/finder": ">=2.7 <5.0", + "symfony/yaml": ">=2.7 <5.0" + }, + "require-dev": { + "codeception/specify": "~0.3", + "facebook/graph-sdk": "~5.3", + "flow/jsonpath": "~0.2", + "monolog/monolog": "~1.8", + "pda/pheanstalk": "~3.0", + "php-amqplib/php-amqplib": "~2.4", + "predis/predis": "^1.0", + "squizlabs/php_codesniffer": "~2.0", + "symfony/process": ">=2.7 <5.0", + "vlucas/phpdotenv": "^2.4.0" + }, + "suggest": { + "aws/aws-sdk-php": "For using AWS Auth in REST module and Queue module", + "codeception/phpbuiltinserver": "Start and stop PHP built-in web server for your tests", + "codeception/specify": "BDD-style code blocks", + "codeception/verify": "BDD-style assertions", + "flow/jsonpath": "For using JSONPath in REST module", + "league/factory-muffin": "For DataFactory module", + "league/factory-muffin-faker": "For Faker support in DataFactory module", + "phpseclib/phpseclib": "for SFTP option in FTP Module", + "stecman/symfony-console-completion": "For BASH autocompletion", + "symfony/phpunit-bridge": "For phpunit-bridge support" + }, + "bin": [ + "codecept" + ], + "type": "library", + "extra": { + "branch-alias": [] + }, + "autoload": { + "psr-4": { + "Codeception\\": "src\\Codeception", + "Codeception\\Extension\\": "ext" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Bodnarchuk", + "email": "davert@mail.ua", + "homepage": "http://codegyre.com" + } + ], + "description": "BDD-style testing framework", + "homepage": "http://codeception.com/", + "keywords": [ + "BDD", + "TDD", + "acceptance testing", + "functional testing", + "unit testing" + ], + "time": "2018-03-31T22:30:43+00:00" + }, + { + "name": "codeception/phpunit-wrapper", + "version": "7.1.1", + "source": { + "type": "git", + "url": "https://github.com/Codeception/phpunit-wrapper.git", + "reference": "33e8ccf2f7abf5c031eeae9802b821d30ec0f7fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Codeception/phpunit-wrapper/zipball/33e8ccf2f7abf5c031eeae9802b821d30ec0f7fc", + "reference": "33e8ccf2f7abf5c031eeae9802b821d30ec0f7fc", + "shasum": "" + }, + "require": { + "phpunit/php-code-coverage": "^6.0", + "phpunit/phpunit": "^7.1", + "sebastian/comparator": "^2.0", + "sebastian/diff": "^3.0" + }, + "require-dev": { + "codeception/specify": "*", + "vlucas/phpdotenv": "^2.4" + }, + "type": "library", + "autoload": { + "psr-4": { + "Codeception\\PHPUnit\\": "src\\" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Davert", + "email": "davert.php@resend.cc" + } + ], + "description": "PHPUnit classes used by Codeception", + "time": "2018-04-20T10:17:13+00:00" + }, + { + "name": "codeception/stub", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/Codeception/Stub.git", + "reference": "95fb7a36b81890dd2e5163e7ab31310df6f1bb99" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Codeception/Stub/zipball/95fb7a36b81890dd2e5163e7ab31310df6f1bb99", + "reference": "95fb7a36b81890dd2e5163e7ab31310df6f1bb99", + "shasum": "" + }, + "require": { + "phpunit/phpunit-mock-objects": ">2.3 <7.0" + }, + "require-dev": { + "phpunit/phpunit": ">=4.8 <8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Codeception\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Flexible Stub wrapper for PHPUnit's Mock Builder", + "time": "2018-02-18T13:56:56+00:00" + }, + { + "name": "doctrine/instantiator", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/instantiator.git", + "reference": "185b8868aa9bf7159f5f953ed5afb2d7fcdc3bda" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/instantiator/zipball/185b8868aa9bf7159f5f953ed5afb2d7fcdc3bda", + "reference": "185b8868aa9bf7159f5f953ed5afb2d7fcdc3bda", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "athletic/athletic": "~0.1.8", + "ext-pdo": "*", + "ext-phar": "*", + "phpunit/phpunit": "^6.2.3", + "squizlabs/php_codesniffer": "^3.0.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Marco Pivetta", + "email": "ocramius@gmail.com", + "homepage": "http://ocramius.github.com/" + } + ], + "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors", + "homepage": "https://github.com/doctrine/instantiator", + "keywords": [ + "constructor", + "instantiate" + ], + "time": "2017-07-22T11:58:36+00:00" + }, + { + "name": "facebook/webdriver", + "version": "1.5.0", + "source": { + "type": "git", + "url": "https://github.com/facebook/php-webdriver.git", + "reference": "86b5ca2f67173c9d34340845dd690149c886a605" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/facebook/php-webdriver/zipball/86b5ca2f67173c9d34340845dd690149c886a605", + "reference": "86b5ca2f67173c9d34340845dd690149c886a605", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "ext-zip": "*", + "php": "^5.6 || ~7.0", + "symfony/process": "^2.8 || ^3.1 || ^4.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.0", + "guzzle/guzzle": "^3.4.1", + "php-coveralls/php-coveralls": "^1.0.2", + "php-mock/php-mock-phpunit": "^1.1", + "phpunit/phpunit": "^5.7", + "sebastian/environment": "^1.3.4 || ^2.0 || ^3.0", + "squizlabs/php_codesniffer": "^2.6", + "symfony/var-dumper": "^3.3 || ^4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-community": "1.5-dev" + } + }, + "autoload": { + "psr-4": { + "Facebook\\WebDriver\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "description": "A PHP client for Selenium WebDriver", + "homepage": "https://github.com/facebook/php-webdriver", + "keywords": [ + "facebook", + "php", + "selenium", + "webdriver" + ], + "time": "2017-11-15T11:08:09+00:00" + }, + { + "name": "fzaninotto/faker", + "version": "v1.7.1", + "source": { + "type": "git", + "url": "https://github.com/fzaninotto/Faker.git", + "reference": "d3ed4cc37051c1ca52d22d76b437d14809fc7e0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fzaninotto/Faker/zipball/d3ed4cc37051c1ca52d22d76b437d14809fc7e0d", + "reference": "d3ed4cc37051c1ca52d22d76b437d14809fc7e0d", + "shasum": "" + }, + "require": { + "php": "^5.3.3 || ^7.0" + }, + "require-dev": { + "ext-intl": "*", + "phpunit/phpunit": "^4.0 || ^5.0", + "squizlabs/php_codesniffer": "^1.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.8-dev" + } + }, + "autoload": { + "psr-4": { + "Faker\\": "src/Faker/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "François Zaninotto" + } + ], + "description": "Faker is a PHP library that generates fake data for you.", + "keywords": [ + "data", + "faker", + "fixtures" + ], + "time": "2017-08-15T16:48:10+00:00" + }, + { + "name": "guzzlehttp/guzzle", + "version": "6.3.3", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/407b0cb880ace85c9b63c5f9551db498cb2d50ba", + "reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba", + "shasum": "" + }, + "require": { + "guzzlehttp/promises": "^1.0", + "guzzlehttp/psr7": "^1.4", + "php": ">=5.5" + }, + "require-dev": { + "ext-curl": "*", + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0", + "psr/log": "^1.0" + }, + "suggest": { + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.3-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "rest", + "web service" + ], + "time": "2018-04-22T15:46:56+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "v1.3.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "shasum": "" + }, + "require": { + "php": ">=5.5.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "time": "2016-12-20T10:07:11+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "1.4.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/f5b8a8512e2b58b0071a7280e39f14f72e05d87c", + "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c", + "shasum": "" + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Schultze", + "homepage": "https://github.com/Tobion" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "request", + "response", + "stream", + "uri", + "url" + ], + "time": "2017-03-20T17:10:46+00:00" + }, + { + "name": "myclabs/deep-copy", + "version": "1.7.0", + "source": { + "type": "git", + "url": "https://github.com/myclabs/DeepCopy.git", + "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e", + "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0" + }, + "require-dev": { + "doctrine/collections": "^1.0", + "doctrine/common": "^2.6", + "phpunit/phpunit": "^4.1" + }, + "type": "library", + "autoload": { + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + }, + "files": [ + "src/DeepCopy/deep_copy.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "time": "2017-10-19T19:58:43+00:00" + }, + { + "name": "phar-io/manifest", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/phar-io/manifest.git", + "reference": "2df402786ab5368a0169091f61a7c1e0eb6852d0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/2df402786ab5368a0169091f61a7c1e0eb6852d0", + "reference": "2df402786ab5368a0169091f61a7c1e0eb6852d0", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-phar": "*", + "phar-io/version": "^1.0.1", + "php": "^5.6 || ^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", + "time": "2017-03-05T18:14:27+00:00" + }, + { + "name": "phar-io/version", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/phar-io/version.git", + "reference": "a70c0ced4be299a63d32fa96d9281d03e94041df" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/version/zipball/a70c0ced4be299a63d32fa96d9281d03e94041df", + "reference": "a70c0ced4be299a63d32fa96d9281d03e94041df", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Library for handling version information and constraints", + "time": "2017-03-05T17:38:23+00:00" + }, + { + "name": "phpdocumentor/reflection-common", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionCommon.git", + "reference": "21bdeb5f65d7ebf9f43b1b25d404f87deab5bfb6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/21bdeb5f65d7ebf9f43b1b25d404f87deab5bfb6", + "reference": "21bdeb5f65d7ebf9f43b1b25d404f87deab5bfb6", + "shasum": "" + }, + "require": { + "php": ">=5.5" + }, + "require-dev": { + "phpunit/phpunit": "^4.6" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": [ + "src" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jaap van Otterdijk", + "email": "opensource@ijaap.nl" + } + ], + "description": "Common reflection classes used by phpdocumentor to reflect the code structure", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "FQSEN", + "phpDocumentor", + "phpdoc", + "reflection", + "static analysis" + ], + "time": "2017-09-11T18:02:19+00:00" + }, + { + "name": "phpdocumentor/reflection-docblock", + "version": "4.3.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", + "reference": "94fd0001232e47129dd3504189fa1c7225010d08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/94fd0001232e47129dd3504189fa1c7225010d08", + "reference": "94fd0001232e47129dd3504189fa1c7225010d08", + "shasum": "" + }, + "require": { + "php": "^7.0", + "phpdocumentor/reflection-common": "^1.0.0", + "phpdocumentor/type-resolver": "^0.4.0", + "webmozart/assert": "^1.0" + }, + "require-dev": { + "doctrine/instantiator": "~1.0.5", + "mockery/mockery": "^1.0", + "phpunit/phpunit": "^6.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "me@mikevanriel.com" + } + ], + "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", + "time": "2017-11-30T07:14:17+00:00" + }, + { + "name": "phpdocumentor/type-resolver", + "version": "0.4.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/TypeResolver.git", + "reference": "9c977708995954784726e25d0cd1dddf4e65b0f7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/9c977708995954784726e25d0cd1dddf4e65b0f7", + "reference": "9c977708995954784726e25d0cd1dddf4e65b0f7", + "shasum": "" + }, + "require": { + "php": "^5.5 || ^7.0", + "phpdocumentor/reflection-common": "^1.0" + }, + "require-dev": { + "mockery/mockery": "^0.9.4", + "phpunit/phpunit": "^5.2||^4.8.24" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "me@mikevanriel.com" + } + ], + "time": "2017-07-14T14:27:02+00:00" + }, + { + "name": "phpspec/prophecy", + "version": "1.7.6", + "source": { + "type": "git", + "url": "https://github.com/phpspec/prophecy.git", + "reference": "33a7e3c4fda54e912ff6338c48823bd5c0f0b712" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpspec/prophecy/zipball/33a7e3c4fda54e912ff6338c48823bd5c0f0b712", + "reference": "33a7e3c4fda54e912ff6338c48823bd5c0f0b712", + "shasum": "" + }, + "require": { + "doctrine/instantiator": "^1.0.2", + "php": "^5.3|^7.0", + "phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0", + "sebastian/comparator": "^1.1|^2.0|^3.0", + "sebastian/recursion-context": "^1.0|^2.0|^3.0" + }, + "require-dev": { + "phpspec/phpspec": "^2.5|^3.2", + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.7.x-dev" + } + }, + "autoload": { + "psr-0": { + "Prophecy\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Konstantin Kudryashov", + "email": "ever.zet@gmail.com", + "homepage": "http://everzet.com" + }, + { + "name": "Marcello Duarte", + "email": "marcello.duarte@gmail.com" + } + ], + "description": "Highly opinionated mocking framework for PHP 5.3+", + "homepage": "https://github.com/phpspec/prophecy", + "keywords": [ + "Double", + "Dummy", + "fake", + "mock", + "spy", + "stub" + ], + "time": "2018-04-18T13:57:24+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "6.0.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "52187754b0eed0b8159f62a6fa30073327e8c2ca" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/52187754b0eed0b8159f62a6fa30073327e8c2ca", + "reference": "52187754b0eed0b8159f62a6fa30073327e8c2ca", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-xmlwriter": "*", + "php": "^7.1", + "phpunit/php-file-iterator": "^1.4.2", + "phpunit/php-text-template": "^1.2.1", + "phpunit/php-token-stream": "^3.0", + "sebastian/code-unit-reverse-lookup": "^1.0.1", + "sebastian/environment": "^3.1", + "sebastian/version": "^2.0.1", + "theseer/tokenizer": "^1.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.0" + }, + "suggest": { + "ext-xdebug": "^2.6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "time": "2018-04-29T14:59:09+00:00" + }, + { + "name": "phpunit/php-file-iterator", + "version": "1.4.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/730b01bc3e867237eaac355e06a36b85dd93a8b4", + "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "time": "2017-11-27T13:52:08+00:00" + }, + { + "name": "phpunit/php-text-template", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/31f8b717e51d9a2afca6c9f046f5d69fc27c8686", + "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "time": "2015-06-21T13:50:34+00:00" + }, + { + "name": "phpunit/php-timer", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "8b8454ea6958c3dee38453d3bd571e023108c91f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/8b8454ea6958c3dee38453d3bd571e023108c91f", + "reference": "8b8454ea6958c3dee38453d3bd571e023108c91f", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "time": "2018-02-01T13:07:23+00:00" + }, + { + "name": "phpunit/php-token-stream", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-token-stream.git", + "reference": "21ad88bbba7c3d93530d93994e0a33cd45f02ace" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/21ad88bbba7c3d93530d93994e0a33cd45f02ace", + "reference": "21ad88bbba7c3d93530d93994e0a33cd45f02ace", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Wrapper around PHP's tokenizer extension.", + "homepage": "https://github.com/sebastianbergmann/php-token-stream/", + "keywords": [ + "tokenizer" + ], + "time": "2018-02-01T13:16:43+00:00" + }, + { + "name": "phpunit/phpunit", + "version": "7.1.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "6d51299e307dc510149e0b7cd1931dd11770e1cb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/6d51299e307dc510149e0b7cd1931dd11770e1cb", + "reference": "6d51299e307dc510149e0b7cd1931dd11770e1cb", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xml": "*", + "myclabs/deep-copy": "^1.6.1", + "phar-io/manifest": "^1.0.1", + "phar-io/version": "^1.0", + "php": "^7.1", + "phpspec/prophecy": "^1.7", + "phpunit/php-code-coverage": "^6.0.1", + "phpunit/php-file-iterator": "^1.4.3", + "phpunit/php-text-template": "^1.2.1", + "phpunit/php-timer": "^2.0", + "phpunit/phpunit-mock-objects": "^6.1.1", + "sebastian/comparator": "^2.1 || ^3.0", + "sebastian/diff": "^3.0", + "sebastian/environment": "^3.1", + "sebastian/exporter": "^3.1", + "sebastian/global-state": "^2.0", + "sebastian/object-enumerator": "^3.0.3", + "sebastian/resource-operations": "^1.0", + "sebastian/version": "^2.0.1" + }, + "require-dev": { + "ext-pdo": "*" + }, + "suggest": { + "ext-xdebug": "*", + "phpunit/php-invoker": "^2.0" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "7.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "time": "2018-04-18T13:41:53+00:00" + }, + { + "name": "phpunit/phpunit-mock-objects", + "version": "6.1.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git", + "reference": "70c740bde8fd9ea9ea295be1cd875dd7b267e157" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/70c740bde8fd9ea9ea295be1cd875dd7b267e157", + "reference": "70c740bde8fd9ea9ea295be1cd875dd7b267e157", + "shasum": "" + }, + "require": { + "doctrine/instantiator": "^1.0.5", + "php": "^7.1", + "phpunit/php-text-template": "^1.2.1", + "sebastian/exporter": "^3.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.0" + }, + "suggest": { + "ext-soap": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Mock Object library for PHPUnit", + "homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/", + "keywords": [ + "mock", + "xunit" + ], + "time": "2018-04-11T04:50:36+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "time": "2016-08-06T14:39:51+00:00" + }, + { + "name": "psr/log", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2016-10-10T12:19:37+00:00" + }, + { + "name": "sebastian/code-unit-reverse-lookup", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", + "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/4419fcdb5eabb9caa61a27c7a1db532a6b55dd18", + "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^5.7 || ^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Looks up which function or method a line of code belongs to", + "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", + "time": "2017-03-04T06:30:41+00:00" + }, + { + "name": "sebastian/comparator", + "version": "2.1.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/comparator.git", + "reference": "34369daee48eafb2651bea869b4b15d75ccc35f9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/34369daee48eafb2651bea869b4b15d75ccc35f9", + "reference": "34369daee48eafb2651bea869b4b15d75ccc35f9", + "shasum": "" + }, + "require": { + "php": "^7.0", + "sebastian/diff": "^2.0 || ^3.0", + "sebastian/exporter": "^3.1" + }, + "require-dev": { + "phpunit/phpunit": "^6.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides the functionality to compare PHP values for equality", + "homepage": "https://github.com/sebastianbergmann/comparator", + "keywords": [ + "comparator", + "compare", + "equality" + ], + "time": "2018-02-01T13:46:46+00:00" + }, + { + "name": "sebastian/diff", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "e09160918c66281713f1c324c1f4c4c3037ba1e8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/e09160918c66281713f1c324c1f4c4c3037ba1e8", + "reference": "e09160918c66281713f1c324c1f4c4c3037ba1e8", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.0", + "symfony/process": "^2 || ^3.3 || ^4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "time": "2018-02-01T13:45:15+00:00" + }, + { + "name": "sebastian/environment", + "version": "3.1.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/environment.git", + "reference": "cd0871b3975fb7fc44d11314fd1ee20925fce4f5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/cd0871b3975fb7fc44d11314fd1ee20925fce4f5", + "reference": "cd0871b3975fb7fc44d11314fd1ee20925fce4f5", + "shasum": "" + }, + "require": { + "php": "^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.1.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides functionality to handle HHVM/PHP environments", + "homepage": "http://www.github.com/sebastianbergmann/environment", + "keywords": [ + "Xdebug", + "environment", + "hhvm" + ], + "time": "2017-07-01T08:51:00+00:00" + }, + { + "name": "sebastian/exporter", + "version": "3.1.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/exporter.git", + "reference": "234199f4528de6d12aaa58b612e98f7d36adb937" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/234199f4528de6d12aaa58b612e98f7d36adb937", + "reference": "234199f4528de6d12aaa58b612e98f7d36adb937", + "shasum": "" + }, + "require": { + "php": "^7.0", + "sebastian/recursion-context": "^3.0" + }, + "require-dev": { + "ext-mbstring": "*", + "phpunit/phpunit": "^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.1.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides the functionality to export PHP variables for visualization", + "homepage": "http://www.github.com/sebastianbergmann/exporter", + "keywords": [ + "export", + "exporter" + ], + "time": "2017-04-03T13:19:02+00:00" + }, + { + "name": "sebastian/global-state", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4", + "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4", + "shasum": "" + }, + "require": { + "php": "^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "suggest": { + "ext-uopz": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Snapshotting of global state", + "homepage": "http://www.github.com/sebastianbergmann/global-state", + "keywords": [ + "global state" + ], + "time": "2017-04-27T15:39:26+00:00" + }, + { + "name": "sebastian/object-enumerator", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-enumerator.git", + "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/7cfd9e65d11ffb5af41198476395774d4c8a84c5", + "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5", + "shasum": "" + }, + "require": { + "php": "^7.0", + "sebastian/object-reflector": "^1.1.1", + "sebastian/recursion-context": "^3.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Traverses array structures and object graphs to enumerate all referenced objects", + "homepage": "https://github.com/sebastianbergmann/object-enumerator/", + "time": "2017-08-03T12:35:26+00:00" + }, + { + "name": "sebastian/object-reflector", + "version": "1.1.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-reflector.git", + "reference": "773f97c67f28de00d397be301821b06708fca0be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/773f97c67f28de00d397be301821b06708fca0be", + "reference": "773f97c67f28de00d397be301821b06708fca0be", + "shasum": "" + }, + "require": { + "php": "^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Allows reflection of object attributes, including inherited and non-public ones", + "homepage": "https://github.com/sebastianbergmann/object-reflector/", + "time": "2017-03-29T09:07:27+00:00" + }, + { + "name": "sebastian/recursion-context", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/recursion-context.git", + "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8", + "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8", + "shasum": "" + }, + "require": { + "php": "^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "http://www.github.com/sebastianbergmann/recursion-context", + "time": "2017-03-03T06:23:57+00:00" + }, + { + "name": "sebastian/resource-operations", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/resource-operations.git", + "reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/ce990bb21759f94aeafd30209e8cfcdfa8bc3f52", + "reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52", + "shasum": "" + }, + "require": { + "php": ">=5.6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides a list of PHP built-in functions that operate on resources", + "homepage": "https://www.github.com/sebastianbergmann/resource-operations", + "time": "2015-07-28T20:34:47+00:00" + }, + { + "name": "sebastian/version", + "version": "2.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/99732be0ddb3361e16ad77b68ba41efc8e979019", + "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "time": "2016-10-03T07:35:21+00:00" + }, + { + "name": "symfony/browser-kit", + "version": "v4.0.9", + "source": { + "type": "git", + "url": "https://github.com/symfony/browser-kit.git", + "reference": "c43bfa0182363b3fd64331b5e64e467349ff4670" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/browser-kit/zipball/c43bfa0182363b3fd64331b5e64e467349ff4670", + "reference": "c43bfa0182363b3fd64331b5e64e467349ff4670", + "shasum": "" + }, + "require": { + "php": "^7.1.3", + "symfony/dom-crawler": "~3.4|~4.0" + }, + "require-dev": { + "symfony/css-selector": "~3.4|~4.0", + "symfony/process": "~3.4|~4.0" + }, + "suggest": { + "symfony/process": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\BrowserKit\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony BrowserKit Component", + "homepage": "https://symfony.com", + "time": "2018-03-19T22:35:49+00:00" + }, + { + "name": "symfony/console", + "version": "v2.8.39", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "932d1e4f7f33ee37d3534f5f452474daa66283c2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/932d1e4f7f33ee37d3534f5f452474daa66283c2", + "reference": "932d1e4f7f33ee37d3534f5f452474daa66283c2", + "shasum": "" + }, + "require": { + "php": ">=5.3.9", + "symfony/debug": "^2.7.2|~3.0.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/event-dispatcher": "~2.1|~3.0.0", + "symfony/process": "~2.1|~3.0.0" + }, + "suggest": { + "psr/log-implementation": "For using the console logger", + "symfony/event-dispatcher": "", + "symfony/process": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Console Component", + "homepage": "https://symfony.com", + "time": "2018-04-30T01:21:07+00:00" + }, + { + "name": "symfony/css-selector", + "version": "v4.0.9", + "source": { + "type": "git", + "url": "https://github.com/symfony/css-selector.git", + "reference": "03f965583147957f1ecbad7ea1c9d6fd5e525ec2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/03f965583147957f1ecbad7ea1c9d6fd5e525ec2", + "reference": "03f965583147957f1ecbad7ea1c9d6fd5e525ec2", + "shasum": "" + }, + "require": { + "php": "^7.1.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\CssSelector\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jean-François Simon", + "email": "jeanfrancois.simon@sensiolabs.com" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony CssSelector Component", + "homepage": "https://symfony.com", + "time": "2018-03-19T22:35:49+00:00" + }, + { + "name": "symfony/debug", + "version": "v3.0.9", + "source": { + "type": "git", + "url": "https://github.com/symfony/debug.git", + "reference": "697c527acd9ea1b2d3efac34d9806bf255278b0a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/debug/zipball/697c527acd9ea1b2d3efac34d9806bf255278b0a", + "reference": "697c527acd9ea1b2d3efac34d9806bf255278b0a", + "shasum": "" + }, + "require": { + "php": ">=5.5.9", + "psr/log": "~1.0" + }, + "conflict": { + "symfony/http-kernel": ">=2.3,<2.3.24|~2.4.0|>=2.5,<2.5.9|>=2.6,<2.6.2" + }, + "require-dev": { + "symfony/class-loader": "~2.8|~3.0", + "symfony/http-kernel": "~2.8|~3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Debug\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Debug Component", + "homepage": "https://symfony.com", + "time": "2016-07-30T07:22:48+00:00" + }, + { + "name": "symfony/dom-crawler", + "version": "v4.0.9", + "source": { + "type": "git", + "url": "https://github.com/symfony/dom-crawler.git", + "reference": "d6c04c7532535b5e0b63db45b543cd60818e0fbc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/d6c04c7532535b5e0b63db45b543cd60818e0fbc", + "reference": "d6c04c7532535b5e0b63db45b543cd60818e0fbc", + "shasum": "" + }, + "require": { + "php": "^7.1.3", + "symfony/polyfill-mbstring": "~1.0" + }, + "require-dev": { + "symfony/css-selector": "~3.4|~4.0" + }, + "suggest": { + "symfony/css-selector": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\DomCrawler\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony DomCrawler Component", + "homepage": "https://symfony.com", + "time": "2018-03-19T22:35:49+00:00" + }, + { + "name": "symfony/event-dispatcher", + "version": "v2.8.39", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "9b69aad7d4c086dc94ebade2d5eb9145da5dac8c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/9b69aad7d4c086dc94ebade2d5eb9145da5dac8c", + "reference": "9b69aad7d4c086dc94ebade2d5eb9145da5dac8c", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "^2.0.5|~3.0.0", + "symfony/dependency-injection": "~2.6|~3.0.0", + "symfony/expression-language": "~2.6|~3.0.0", + "symfony/stopwatch": "~2.3|~3.0.0" + }, + "suggest": { + "symfony/dependency-injection": "", + "symfony/http-kernel": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony EventDispatcher Component", + "homepage": "https://symfony.com", + "time": "2018-04-06T07:35:03+00:00" + }, + { + "name": "symfony/finder", + "version": "v2.8.39", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "423746fc18ccf31f9abec43e4f078bb6e024b2d5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/423746fc18ccf31f9abec43e4f078bb6e024b2d5", + "reference": "423746fc18ccf31f9abec43e4f078bb6e024b2d5", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Finder Component", + "homepage": "https://symfony.com", + "time": "2018-04-04T13:38:31+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.8.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "3296adf6a6454a050679cde90f95350ad604b171" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/3296adf6a6454a050679cde90f95350ad604b171", + "reference": "3296adf6a6454a050679cde90f95350ad604b171", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "time": "2018-04-26T10:06:28+00:00" + }, + { + "name": "symfony/process", + "version": "v4.0.9", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "d7dc1ee5dfe9f732cb1bba7310f5b99f2b7a6d25" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/d7dc1ee5dfe9f732cb1bba7310f5b99f2b7a6d25", + "reference": "d7dc1ee5dfe9f732cb1bba7310f5b99f2b7a6d25", + "shasum": "" + }, + "require": { + "php": "^7.1.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Process Component", + "homepage": "https://symfony.com", + "time": "2018-04-03T05:24:00+00:00" + }, + { + "name": "symfony/yaml", + "version": "v2.8.39", + "source": { + "type": "git", + "url": "https://github.com/symfony/yaml.git", + "reference": "d20bd2bdee063863e426297af41eda45ccad6f7e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/yaml/zipball/d20bd2bdee063863e426297af41eda45ccad6f7e", + "reference": "d20bd2bdee063863e426297af41eda45ccad6f7e", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Yaml\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Yaml Component", + "homepage": "https://symfony.com", + "time": "2018-04-08T07:53:13+00:00" + }, + { + "name": "theseer/tokenizer", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/theseer/tokenizer.git", + "reference": "cb2f008f3f05af2893a87208fe6a6c4985483f8b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/cb2f008f3f05af2893a87208fe6a6c4985483f8b", + "reference": "cb2f008f3f05af2893a87208fe6a6c4985483f8b", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": "^7.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + } + ], + "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", + "time": "2017-04-07T12:08:54+00:00" + }, + { + "name": "webmozart/assert", + "version": "1.3.0", + "source": { + "type": "git", + "url": "https://github.com/webmozart/assert.git", + "reference": "0df1908962e7a3071564e857d86874dad1ef204a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webmozart/assert/zipball/0df1908962e7a3071564e857d86874dad1ef204a", + "reference": "0df1908962e7a3071564e857d86874dad1ef204a", + "shasum": "" + }, + "require": { + "php": "^5.3.3 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.6", + "sebastian/version": "^1.0.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Webmozart\\Assert\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Assertions to validate method input/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "time": "2018-01-29T19:49:41+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": { + "fguillot/picofeed": 0 + }, + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [] +} diff --git a/user/plugins/admin/languages/ar.yaml b/user/plugins/admin/languages/ar.yaml new file mode 100644 index 0000000..dbed7f4 --- /dev/null +++ b/user/plugins/admin/languages/ar.yaml @@ -0,0 +1,92 @@ +--- +PLUGIN_ADMIN: + ADMIN_BETA_MSG: "هذا إصدار بيتا! استخدم هذا في الإنتاج على مسؤوليتك الخاصة..." + ADMIN_REPORT_ISSUE: "وجدت مشكلة؟ الرجاء الإبلاغ عن GitHub." + EMAIL_FOOTER: "Powered by Grav - The Modern Flat File CMS" + LOGIN_BTN: "تسجل الدخول" + LOGIN_BTN_FORGOT: "نسيت" + LOGIN_BTN_RESET: "إعادة تعيين كلمة المرور" + LOGIN_BTN_SEND_INSTRUCTIONS: "إرسال إرشادات إعادة تعيين" + LOGIN_BTN_CLEAR: "مسح النموذج" + LOGIN_BTN_CREATE_USER: "أنشاء مستخدم جديد" + LOGIN_LOGGED_IN: "لقد تم تسجيل بنجاح" + LOGIN_FAILED: "فشل تسجيل الخول" + LOGGED_OUT: "لقد قمت بتسجيل الخروج" + RESET_NEW_PASSWORD: "إدخال كلمة سر جديدة رجاءً …" + RESET_LINK_EXPIRED: "انتهت مدة صلاحية إعادة الارتباط، الرجاء المحاولة مرة أخرى" + RESET_PASSWORD_RESET: "لقد تم إعادة تعيين كلمة المرور" + RESET_INVALID_LINK: "اللينك خاطئ ، الرجاء المحاولة مرة أخرى" + FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL: "تم إرسال إرشادات إعادة تعيين كلمة المرور الخاصة بك عبر البريد الإلكتروني إلى %s" + FORGOT_FAILED_TO_EMAIL: "فشل في تعليمات البريد الإلكتروني، الرجاء المحاولة مرة أخرى لاحقاً" + FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL: "لا يمكن إعادة تعيين كلمة المرور ل %s، لم يتم تعيين عنوان البريد الإلكتروني" + FORGOT_USERNAME_DOES_NOT_EXIST: "لا يوجد المستخدم مع اسم المستخدم %s" + FORGOT_EMAIL_NOT_CONFIGURED: "لا يمكن إعادة تعيين كلمة المرور. لم يتم تكوين هذا الموقع لإرسال رسائل البريد الإلكتروني" + FORGOT_EMAIL_SUBJECT: "طلب إعادة تعيين كلمة المرور %s" + MANAGE_PAGES: "إدارة الصفحات" + PAGES: "الصفحات" + PLUGINS: "البرامج الإضافية" + PLUGIN: "البرنامج الإضافي" + THEMES: "المواضيع" + LOGOUT: "تسجيل الخروج" + BACK: "الرجوع" + ADD_PAGE: "إضافة صفحة" + ADD_MODULAR: "إضافة وحدة" + MOVE: "انقل" + DELETE: "حذف" + SAVE: "حفظ" + NORMAL: "عادي" + EXPERT: "خبير" + EXPAND_ALL: "عرض الكل" + COLLAPSE_ALL: "طي الكل" + ERROR: "خطأ" + CLOSE: "أغلق" + CANCEL: "إلغاء" + CONTINUE: "المتابعة" + MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_TITLE: "التأكيد مطلوب" + MODAL_CHANGED_DETECTED_TITLE: "تم الكشف عن التغييرات" + MODAL_CHANGED_DETECTED_DESC: "وقد تغييرات غير محفوظة. هل أنت متأكد من أنك تريد ترك دون الحفظ؟" + MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_TITLE: "التأكيد مطلوب" + MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_DESC: "هل أنت متأكد من حذف هذا الملف؟ لا يمكن التراجع عن هذا الإجراء." + ADD_FILTERS: "إضافة عامل تصفية" + SEARCH_PAGES: "صفحات البحث" + VERSION: "النسخة" + WAS_MADE_WITH: "تم عمله مع" + BY: "بواسطة" + UPDATE_THEME: "تحديث الموضوع" + UPDATE_PLUGIN: "تحديث البرنامج الإضافي" + AUTHOR: "المؤلّف" + HOMEPAGE: "الصفحة الرئيسية" + DEMO: "عرض تجريبي" + BUG_TRACKER: "متتبع الأخطاء" + KEYWORDS: "الكلمات الرئيسية" + LICENSE: "الرخصة" + DESCRIPTION: "الوصف" + README: "الملف التمهيدي" + REMOVE_THEME: "إزالة الموضوع" + INSTALL_THEME: "تثبيت الموضوع" + THEME: "الموضوع" + BACK_TO_THEMES: "العودة إلى المواضيع" + BACK_TO_PLUGINS: "العودة إلى البرامج الإضافية" + CHECK_FOR_UPDATES: "التحقق من وجود تحديثات" + ADD: "أَضِف" + CLEAR_CACHE: "مسح ذاكرة التخزين المؤقتة" + CLEAR_CACHE_IMAGES_ONLY: "الصور فقط" + DASHBOARD: "لوحة المعلومات" + UPDATES_AVAILABLE: "تحديثات متوفّرة" + DAYS: "أيام" + UPDATE: "تحديث" + STATISTICS: "إحصائيات" + TODAY: "اليوم" + WEEK: "اسبوع" + MONTH: "شهر" + MAINTENANCE: "الصيانه" + MON: "الإثنين" + TUE: "الثلاثاء" + WED: "الإربعاء" + THU: "الخميس" + FRI: "الجمعة" + SAT: "السبت" + SUN: "الأحد" + COPY: "نسخ" + EDIT: "تحرير" + CREATE: "انشاء" diff --git a/user/plugins/admin/languages/bg.yaml b/user/plugins/admin/languages/bg.yaml new file mode 100644 index 0000000..a743085 --- /dev/null +++ b/user/plugins/admin/languages/bg.yaml @@ -0,0 +1,262 @@ +--- +PLUGIN_ADMIN: + ADMIN_BETA_MSG: "Това е Бета версия! Използвате на ваша отговорност..." + ADMIN_REPORT_ISSUE: "Открили сте проблем? Моля, съобщете за него в GitHub." + EMAIL_FOOTER: "Задвижван от Grav - Модерният Флат Файл CMS" + LOGIN_BTN: "Вход" + LOGIN_BTN_FORGOT: "Забравена парола" + LOGIN_BTN_RESET: "Промяна на паролата" + LOGIN_BTN_SEND_INSTRUCTIONS: "Изпращане на инструкциите за възстановяването" + LOGIN_BTN_CLEAR: "Изтриване на формуляра" + LOGIN_BTN_CREATE_USER: "Създаване на потребител" + LOGIN_LOGGED_IN: "Влязохте успешно" + LOGIN_FAILED: "Влизането не е успешно" + LOGGED_OUT: "Излязохте от системата" + RESET_NEW_PASSWORD: "Въведете нова парола …" + RESET_LINK_EXPIRED: "Връзката за нулиране е изтекла, опитайте отново" + RESET_PASSWORD_RESET: "Паролата е променена" + RESET_INVALID_LINK: "Използвана невалидна връзка за нулиране, моля опитайте отново" + FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL: "На Вашия имейл, бяха изпратени инструкции за възстановяване на паролата" + FORGOT_FAILED_TO_EMAIL: "Неуспешно изпращане на имейл с инструкции, опитайте по-късно" + FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL: "Паролата на %s не може да бъде обновена, няма въведен имейл адрес" + FORGOT_USERNAME_DOES_NOT_EXIST: "Потребител с име %s не съществува" + FORGOT_EMAIL_NOT_CONFIGURED: "Не може да обнови паролата. Този сайт не е конфигуриран да изпраща имейли" + FORGOT_EMAIL_SUBJECT: "%s - искане за смяна на парола" + FORGOT_EMAIL_BODY: "

    Смяна на парола

    Уважаеми %1$s

    На %4$s бе направено искане за смяна на парола.


    Натиснете тук за да обновите паролата си

    Като алтернатива, можете да копирате линка в адресната лента на браузъра си:

    %2$s


    С уважение,

    %3$s

    " + MANAGE_PAGES: "Управление на страниците" + CONFIGURATION: "Настройки" + PAGES: "Страници" + PLUGINS: "Разширения" + PLUGIN: "Разширение" + THEMES: "Теми" + LOGOUT: "Изход" + BACK: "Назад" + ADD_PAGE: "Добавяне на страница" + ADD_MODULAR: "Добавяне на модулна страница" + MOVE: "Преместване" + DELETE: "Изтриване" + VIEW: "Виж" + SAVE: "Запазване" + NORMAL: "Обикновен" + EXPERT: "Експертен" + EXPAND_ALL: "Разгъване на всички" + COLLAPSE_ALL: "Свиване на всички" + ERROR: "Грешка" + CLOSE: "Затваряне" + CANCEL: "Отказ" + CONTINUE: "Продължаване" + MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_TITLE: "Изисква се потвърждение" + MODAL_CHANGED_DETECTED_TITLE: "Засечени са промени" + MODAL_CHANGED_DETECTED_DESC: "Имате незапазени промени. Наистина ли искате да излезете без да сте ги запазили?" + MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_TITLE: "Изисква се потвърждение" + MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_DESC: "Наистина ли искате да изтриете този файл? Това действие не може да бъде отменено." + ADD_FILTERS: "Добавяне на филтри" + SEARCH_PAGES: "Търсене" + VERSION: "Версия" + WAS_MADE_WITH: "е създаден с" + BY: "от" + UPDATE_THEME: "Актуализация на тема" + UPDATE_PLUGIN: "Актуализация на разширение" + OF_THIS_THEME_IS_NOW_AVAILABLE: "на тази тема е наличен" + OF_THIS_PLUGIN_IS_NOW_AVAILABLE: "на този плъгин е вече наличен" + AUTHOR: "Автор" + HOMEPAGE: "Страница" + DEMO: "Демо" + BUG_TRACKER: "Докладване за грешки" + KEYWORDS: "Ключови думи" + LICENSE: "Лиценз" + DESCRIPTION: "Описание" + README: "Документация" + REMOVE_THEME: "Премахване на тема" + INSTALL_THEME: "Инсталиране на тема" + THEME: "Тема" + BACK_TO_THEMES: "Обратно към темите" + BACK_TO_PLUGINS: "Обратно към разширенията" + CHECK_FOR_UPDATES: "Проверка за актуализации" + ADD: "Добавяне" + CLEAR_CACHE: "Изтриване на временните файлове" + CLEAR_CACHE_ALL_CACHE: "Всички" + CLEAR_CACHE_ASSETS_ONLY: "Само Assets" + CLEAR_CACHE_IMAGES_ONLY: "Само изображенията" + CLEAR_CACHE_CACHE_ONLY: "Само временните файлове" + CLEAR_CACHE_TMP_ONLY: "само временен" + DASHBOARD: "Контролен панел" + UPDATES_AVAILABLE: "Налични актуализации" + DAYS: "Дни" + UPDATE: "Актуализация" + BACKUP: "Резервно копие" + STATISTICS: "Статистика" + TODAY: "Днес" + WEEK: "Седмица" + MONTH: "Месец" + LATEST_PAGE_UPDATES: "Скоро актуализирани страници" + MAINTENANCE: "Техническа поддръжка" + UPDATED: "Актуализиран" + MON: "пон" + TUE: "вт" + WED: "ср" + THU: "чт" + FRI: "пт" + SAT: "сб" + SUN: "нд" + COPY: "Копиране" + EDIT: "Редактиране" + CREATE: "Създаване" + GRAV_ADMIN: "Grav Admin" + GRAV_OFFICIAL_PLUGIN: "Официално разширение на Grav" + GRAV_OFFICIAL_THEME: "Официална тема на Grav" + PLUGIN_SYMBOLICALLY_LINKED: "Този плъгин е символично свързан. Актуализации няма да бъдат отразени." + THEME_SYMBOLICALLY_LINKED: "Тази тема е символично свързана. Актуализации няма да бъдат отразени." + REMOVE_PLUGIN: "Премахване на разширение" + INSTALL_PLUGIN: "Инсталиране на разширение" + AVAILABLE: "Налични" + INSTALLED: "Инсталирани" + INSTALL: "Инсталиране" + ACTIVE_THEME: "Активна тема" + SWITCHING_TO: "Превключване към" + SWITCHING_TO_DESCRIPTION: "При превключването към различна тема няма гаранция, че всички страници са поддържани, което може да доведе до потенциални грешки при опит за зареждане на тези страници." + SWITCHING_TO_CONFIRMATION: "Искате ли да продължите и да превключите към темата" + CREATE_NEW_USER: "Създаване на нов потребител" + REMOVE_USER: "Премахване на потребител" + ACCESS_DENIED: "Нямате достъп" + ACCOUNT_NOT_ADMIN: "вашият профил няма администраторски права" + PHP_INFO: "Информация за PHP" + INSTALLER: "Инсталатор" + AVAILABLE_THEMES: "Налични теми" + AVAILABLE_PLUGINS: "Налични разширения" + INSTALLED_THEMES: "Инсталирани теми" + INSTALLED_PLUGINS: "Инсталирани разширения" + BROWSE_ERROR_LOGS: "Преглед на дневниците за грешки" + SITE: "Сайт" + INFO: "Информация" + SYSTEM: "Система" + USER: "Потребител" + ADD_ACCOUNT: "Добавяне на профил" + SWITCH_LANGUAGE: "Превключване на езика" + SUCCESSFULLY_ENABLED_PLUGIN: "Разширението е активирано успешно" + SUCCESSFULLY_DISABLED_PLUGIN: "Разширението е спряно" + SUCCESSFULLY_CHANGED_THEME: "Промяната на подразбиращата се тема е успешно" + INSTALLATION_FAILED: "Неуспешна инсталация" + INSTALLATION_SUCCESSFUL: "Инсталацията е успешна" + UNINSTALL_FAILED: "Неуспешно деинсталиране" + UNINSTALL_SUCCESSFUL: "Деинсталирането е успешно" + SUCCESSFULLY_SAVED: "Успешно запазено" + SUCCESSFULLY_COPIED: "Успешно копирано" + REORDERING_WAS_SUCCESSFUL: "Записът бе успешен" + SUCCESSFULLY_DELETED: "Успешно изтрити" + SUCCESSFULLY_SWITCHED_LANGUAGE: "Езикът е променен успешно" + INSUFFICIENT_PERMISSIONS_FOR_TASK: "Нямате достатъчно права за тази задача" + CACHE_CLEARED: "Временните файлове са изчистени" + METHOD: "Метод" + ERROR_CLEARING_CACHE: "Грешка при изтриването на временните файлове" + AN_ERROR_OCCURRED: "Възникна грешка" + YOUR_BACKUP_IS_READY_FOR_DOWNLOAD: "Резервното копие е готово за изтегляне" + DOWNLOAD_BACKUP: "Изтегляне на резервното копие" + PAGES_FILTERED: "Филтрирани страници" + NO_PAGE_FOUND: "Няма намерени страници" + INVALID_PARAMETERS: "Невалидни параметри" + NO_FILES_SENT: "Няма изпратени файлове" + EXCEEDED_FILESIZE_LIMIT: "Надхвърлен лимит за размер на PHP конфигурационен файл" + UNKNOWN_ERRORS: "Неизвестни грешки" + EXCEEDED_GRAV_FILESIZE_LIMIT: "Превишен лимит за размера на конфигурационен GRAV файл" + UNSUPPORTED_FILE_TYPE: "Този файлов формат не се поддържа" + FAILED_TO_MOVE_UPLOADED_FILE: "Преместването на качения файл не е успешно." + FILE_UPLOADED_SUCCESSFULLY: "Файлът е качен успешно" + FILE_DELETED: "Файлът е изтрит" + FILE_COULD_NOT_BE_DELETED: "Файлът не може да бъде изтрит" + FILE_NOT_FOUND: "Файлът не е намерен" + NO_FILE_FOUND: "Няма намерени файлове" + GRAV_WAS_SUCCESSFULLY_UPDATED_TO: "Grav беше успешно актуализиран до" + GRAV_UPDATE_FAILED: "Актуализацията на Grav е неуспешна" + EVERYTHING_UPDATED: "Всичко е актуализирано" + UPDATES_FAILED: "Актуализациите не бяха успшено" + AVATAR_BY: "Аватар от" + AVATAR_UPLOAD_OWN: "Или качи собствени..." + LAST_BACKUP: "Последно резервно копие" + FULL_NAME: "Пълно име" + USERNAME: "Потребителско име" + EMAIL: "Ел. поща" + USERNAME_EMAIL: "Потребителско име или инейл" + PASSWORD: "Парола" + PASSWORD_CONFIRM: "Потвърждение на паролата" + TITLE: "Титла" + LANGUAGE: "Език" + ACCOUNT: "Профил" + EMAIL_VALIDATION_MESSAGE: "Ел. поща трябва да бъде валидна" + PASSWORD_VALIDATION_MESSAGE: "Паролата трябва да съдържа поне един номер, една главна буква, една малка буква и да съдържа поне 8 или повече знака" + LANGUAGE_HELP: "Задаване на любим език" + MEDIA: "Медиа" + DEFAULTS: "По подразбиране" + SITE_TITLE: "Заглавие на сайта" + SITE_TITLE_PLACEHOLDER: "Заглавие за всички страници" + SITE_TITLE_HELP: "Подразбиращо се заглавие за вашият сайт, често се използва от темите" + SITE_DEFAULT_LANG: "Език по подразбиране" + SITE_DEFAULT_LANG_PLACEHOLDER: "Език по подразбиране, използван от тага на темите" + SITE_DEFAULT_LANG_HELP: "Език по подразбиране, използван от тага на темите" + DEFAULT_AUTHOR: "Подразбиращ се автор" + DEFAULT_AUTHOR_HELP: "Име на автор по подразбиране, често използвано в теми или страници" + DEFAULT_EMAIL: "Имейл по подразбиране" + DEFAULT_EMAIL_HELP: "Имейл по подразбиране, използван в теми или страници" + TAXONOMY_TYPES: "Видове таксономии" + TAXONOMY_TYPES_HELP: "Типовете таксономия трябва да бъдат дефинирани тук, ако искате да ги използвате в страници" + PAGE_SUMMARY: "Резюме на страницата" + ENABLED: "Включен" + 'YES': "Да" + 'NO': "Не" + SUMMARY_SIZE: "Размер на резюмето" + SUMMARY_SIZE_HELP: "Брой знаци, които да бъдат използвани при създаването на резюме за страницата" + FORMAT: "Формат" + SHORT: "Къс" + LONG: "Дълъг" + DELIMITER: "Делител" + METADATA: "Мета-данни" + NAME: "Име" + CONTENT: "Съдържание" + REDIRECTS_AND_ROUTES: "Пренасочвания и пътища" + CUSTOM_REDIRECTS: "Потребителски пренасочвания" + CUSTOM_REDIRECTS_PLACEHOLDER_KEY: "/your/alias" + CUSTOM_REDIRECTS_PLACEHOLDER_VALUE: "/your/redirect" + CUSTOM_ROUTES: "Потребителски пренасочвания" + CUSTOM_ROUTES_PLACEHOLDER_KEY: "/your/alias" + CUSTOM_ROUTES_PLACEHOLDER_VALUE: "/your/route" + DEFAULT: "По подразбиране" + OPTIONS: "Опции" + PUBLISHED: "Публикувано" + DATE: "Дата" + PUBLISHED_DATE: "Дата на публикуване" + PUBLISHED_DATE_HELP: "Дата, на която автоматично ще се публикува." + ROBOTS: "Роботи" + TAXONOMIES: "Таксономии" + TAXONOMY: "Таксономия" + ADVANCED: "Разширено" + SETTINGS: "Настройки" + FOLDER_NAME: "Име на папка" + PARENT: "Родител" + DEFAULT_OPTION_ROOT: "- Коренова папка -" + DEFAULT_OPTION_SELECT: "- Избор -" + DISPLAY_TEMPLATE: "Показване на шаблон" + ORDERING: "Подреждане" + PAGE_ORDER: "Подредба на страниците" + PROCESS: "Обработване" + CACHING: "Създаване на временни файлове" + VISIBLE: "Видим" + VISIBLE_HELP: "Определя дали една страница е видима в навигацията." + DISABLED: "Изключено" + ORDER_BY: "Подреждане по" + ORDER: "Подреждане" + FOLDER: "Папка" + ASCENDING: "Възходящо" + DESCENDING: "Низходящо" + PAGE_TITLE: "Заглавие на страницата" + PAGE_TITLE_HELP: "Заглавието на страницата" + PAGE: "Страница" + FILENAME: "Име на файла" + PARENT_PAGE: "Родителска страница" + HOME_PAGE: "Начална страница" + HOME_PAGE_HELP: "Страницата, която Grav ще използва по подразбиране за начална страница" + DEFAULT_THEME: "Тема по подразбиране" + DEFAULT_THEME_HELP: "Задаване на темата по подразбиране, която Grav ще използва (по подразбиране това е Antimatter)" + TIMEZONE: "Часова зона" + TIMEZONE_HELP: "Презаписване на времевата зона на сървъра" + EVENTS: "Събития" + EVENTS_HELP: "Пускане или спиране на специфични събития. Спирането на някои събития може да счупи определени приставки" diff --git a/user/plugins/admin/languages/br.yaml b/user/plugins/admin/languages/br.yaml new file mode 100644 index 0000000..497b447 --- /dev/null +++ b/user/plugins/admin/languages/br.yaml @@ -0,0 +1,577 @@ +--- +PLUGIN_ADMIN: + ADMIN_BETA_MSG: "Un ermaeziadenn beta an hini eo! Arverit en endro produadur gant evezh..." + ADMIN_REPORT_ISSUE: "Kavet hoc'h eus ur gudenn? Danevellit anezhi war Github." + EMAIL_FOOTER: "Lusket gant Grav - Ar CMS Restr plad modern" + LOGIN_BTN: "Anv arveriad" + LOGIN_BTN_FORGOT: "Ankouaet" + LOGIN_BTN_RESET: "Adderaouekaat ar ger-tremen" + LOGIN_BTN_SEND_INSTRUCTIONS: "Kas an ditouroù adderaouekaat" + LOGIN_BTN_CLEAR: "Skarzhañ ar furmskrid" + LOGIN_BTN_CREATE_USER: "Krouiñ an arveriad" + LOGIN_LOGGED_IN: "Kennasket oc'h gant berzh" + LOGIN_FAILED: "C'hwitadenn war ar c'hennask" + LOGGED_OUT: "Digennasket oc'h" + RESET_NEW_PASSWORD: "Enankit ur ger-tremen nevez …" + RESET_LINK_EXPIRED: "Diamzeret eo an ere adderaouekaat, klaskit en-dro" + RESET_PASSWORD_RESET: "Adderaouekaet eo bet ar ger-tremen" + RESET_INVALID_LINK: "Ere adderaouekaat didalvoudek, klaskit en-dro" + FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL: "Kaset eo bet an ditouroù da adderaouekaat ho ker-tremen d'ho chmolec'h postel" + FORGOT_FAILED_TO_EMAIL: "C'hwitadenn en ur gas an ditouroù, klaskit en-dro diwezhatoc'h" + FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL: "N'haller ket adderaouekaat ar ger-tremen evit %s, chomlec'h postel ebet arventennet" + FORGOT_USERNAME_DOES_NOT_EXIST: "N'eus ket eus an arveriad gant an anv %s" + FORGOT_EMAIL_NOT_CONFIGURED: "N'haller ket adderaouekaat ar ger-tremen. N'eo ket kefluniet al lec'hienn evit kas posteloù" + FORGOT_EMAIL_SUBJECT: "%s Goulenn adderaouekaat ar ger-tremen" + FORGOT_EMAIL_BODY: "

    Adderaouekaat ar ger-tremen/h1>

    %1$s,

    Graet eo bet un azgoulenn war %4$s evit adderaouekaat ho ker-tremen.


    Klikit amañ da adderaouekaat ho ker-tremen

    Gallout a rit ivez eilañ an URL da heul er varrenn chomlec'h en ho merdeer:

    %2$s


    A galon,

    %3$s

    " + MANAGE_PAGES: "Ardeiñ ar pajennoù" + CONFIGURATION: "Kefluniadur" + PAGES: "Pajennoù" + PLUGINS: "Enlugelladoù" + PLUGIN: "Enlugellad" + THEMES: "Neuzioù" + LOGOUT: "Digennaskañ" + BACK: "Distreiñ" + ADD_PAGE: "Ouzhpennañ ur bajenn" + ADD_MODULAR: "Ouzhpennañ ur mollad" + MOVE: "Dilec'hiañ" + DELETE: "Dilemel" + SAVE: "Enrollañ" + NORMAL: "Reoliek" + EXPERT: "Kemplezhoc'h" + EXPAND_ALL: "Astenn an holl" + COLLAPSE_ALL: "Bihanaat an holl" + ERROR: "Fazi" + CLOSE: "Serriñ" + CANCEL: "Nullañ" + CONTINUE: "Kenderc'hel" + MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_TITLE: "Kadarnadur azgoulennet" + MODAL_CHANGED_DETECTED_TITLE: "Kemmoù dinoet" + MODAL_CHANGED_DETECTED_DESC: "Kemmoù dienrollet a zo. Sur oc'h e fell deoc'h kuitaat hep enrollañ?" + MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_TITLE: "Kadarnadur azgoulennet" + MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_DESC: "Sur oc'h e fell deoc'h dilemel ar restr-mañ? N'haller ket dizober ar gwered-mañ." + ADD_FILTERS: "Ouzhpennañ siloù" + SEARCH_PAGES: "Klask pajennoù" + VERSION: "Handelv" + WAS_MADE_WITH: "Savet eo bet gant" + BY: "Gant" + UPDATE_THEME: "Hizivaat an neuz" + UPDATE_PLUGIN: "Hizivaat an enlugellad" + OF_THIS_THEME_IS_NOW_AVAILABLE: "an neuz-mañ a zo hegerz" + OF_THIS_PLUGIN_IS_NOW_AVAILABLE: "an enlugellad-mañ a zo hegerz" + AUTHOR: "Aozer" + HOMEPAGE: "Pennbajenn" + DEMO: "Tañva" + BUG_TRACKER: "Heulier beugoù" + KEYWORDS: "Gerioù-alc'hwez" + LICENSE: "Lañvaz" + DESCRIPTION: "Deskrivadur" + README: "Skoazell" + REMOVE_THEME: "Dilemel an neuz" + INSTALL_THEME: "Staliañ an neuz" + THEME: "Neuz" + BACK_TO_THEMES: "Distreiñ d'an neuzioù" + BACK_TO_PLUGINS: "Distreiñ d'an enlugelladoù" + CHECK_FOR_UPDATES: "Klask hizivadennoù" + ADD: "Ouzhpenañ" + CLEAR_CACHE: "Skarzhañ ar c'hrubuilh" + CLEAR_CACHE_ALL_CACHE: "Ar c'hrubuilh a-bezh" + CLEAR_CACHE_ASSETS_ONLY: "Loazioù nemetken" + CLEAR_CACHE_IMAGES_ONLY: "Skeudennoù nemetken" + CLEAR_CACHE_CACHE_ONLY: "Krubuilh nemetken" + CLEAR_CACHE_TMP_ONLY: "Padennek hepken" + DASHBOARD: "Taolenn labour" + UPDATES_AVAILABLE: "Hizivadennoù hegerz" + DAYS: "Devezhioù" + UPDATE: "Hizivadenn" + BACKUP: "Gwared" + STATISTICS: "Stadegoù" + TODAY: "Hiziv" + WEEK: "Sizhun" + MONTH: "Miz" + LATEST_PAGE_UPDATES: "Hizivadennoù diwezhañ ar bajenn" + MAINTENANCE: "Trezalc'h" + UPDATED: "Hizivaet" + MON: "Lun" + TUE: "Meu" + WED: "Mer" + THU: "Yao" + FRI: "Gwe" + SAT: "Sad" + SUN: "Sul" + COPY: "Eilañ" + EDIT: "Kemmañ" + CREATE: "Krouiñ" + GRAV_ADMIN: "Merour Grav" + GRAV_OFFICIAL_PLUGIN: "Enlugellad Kefridiel Grav" + GRAV_OFFICIAL_THEME: "Neuz Kefridiel Grav" + PLUGIN_SYMBOLICALLY_LINKED: "Gant un ere arouezus eo lakaet an enlugellad. Ne vo ket dinoet an hizivadennoù." + THEME_SYMBOLICALLY_LINKED: "Gant un ere arouezus eo lakaet an neuz. Ne vo ket dinoet an hizivadennoù" + REMOVE_PLUGIN: "Dilemel an enlugellad" + INSTALL_PLUGIN: "Staliañ an enlugellad" + AVAILABLE: "Hegerz" + INSTALLED: "Staliet" + INSTALL: "Staliañ" + ACTIVE_THEME: "Neuz oberiant" + SWITCHING_TO: "Kemmañ da" + SWITCHING_TO_DESCRIPTION: "En ur gemmañ d'un neuz disheñvel n'eus gwarant ebet e vo skoret an holl frammoù pajenn, ar pezh a zegasfe fazioù en ur gargañ ar pajennoù-mañ." + SWITCHING_TO_CONFIRMATION: "Fellout a ra deoc'h kenderc'hel ha kemmañ an neuz" + CREATE_NEW_USER: "Krouiñ un arveriad nevez" + REMOVE_USER: "Dilemel an arveriad" + ACCESS_DENIED: "Haeziñ nac'het" + ACCOUNT_NOT_ADMIN: "n'hoc'h eus ket an aotreoù a-zere" + PHP_INFO: "Titouroù PHP" + INSTALLER: "Stalier" + AVAILABLE_THEMES: "Neuzioù hegerz" + AVAILABLE_PLUGINS: "Enlugelladoù hegerz" + INSTALLED_THEMES: "Neuzioù staliet" + INSTALLED_PLUGINS: "Enlugelladoù staliet" + BROWSE_ERROR_LOGS: "Furchal er c'herzhlevr fazioù" + SITE: "Lec'hienn" + INFO: "Titouroù" + SYSTEM: "Reizhiad" + USER: "Arveriad" + ADD_ACCOUNT: "Ouzhpennañ ur gont" + SWITCH_LANGUAGE: "Kemmañ ar yezh" + SUCCESSFULLY_ENABLED_PLUGIN: "Gweredekaet an enlugellad gant berzh" + SUCCESSFULLY_DISABLED_PLUGIN: "Diweredekaet an enlugellad gant berzh" + SUCCESSFULLY_CHANGED_THEME: "Kemmet an neuz dre ziouer gant berzh" + INSTALLATION_FAILED: "C'hwitadenn war ar staliadur" + INSTALLATION_SUCCESSFUL: "Berzh war ar staliadur" + UNINSTALL_FAILED: "C'hwitadenn war an distaliadur" + UNINSTALL_SUCCESSFUL: "Berzh war an distaliadur" + SUCCESSFULLY_SAVED: "Enrollet gant berzh" + SUCCESSFULLY_COPIED: "Eilet gant berzh" + REORDERING_WAS_SUCCESSFUL: "Adurzhiet gant berzh" + SUCCESSFULLY_DELETED: "Dilamet gant berzh" + SUCCESSFULLY_SWITCHED_LANGUAGE: "Kemmet ar yezh gant berzh" + INSUFFICIENT_PERMISSIONS_FOR_TASK: "N'ho peus ket trawalc'h a aotreoù evit ar gwered" + CACHE_CLEARED: "Skarzhet ar c'hrubuilh" + METHOD: "Hentenn" + ERROR_CLEARING_CACHE: "Fazi en ur skarzhañ ar c'hrubuilh" + AN_ERROR_OCCURRED: "Degouezhet ez eus bet ur fazi" + YOUR_BACKUP_IS_READY_FOR_DOWNLOAD: "Prest eo ho kwared da vezañ pellgarget" + DOWNLOAD_BACKUP: "Pellgargañ ar gwared" + PAGES_FILTERED: "Pajennoù silet" + NO_PAGE_FOUND: "Pajenn ebet kavet" + INVALID_PARAMETERS: "Arventennoù didalvoudek" + NO_FILES_SENT: "Restr ebet kaset" + UNKNOWN_ERRORS: "Fazioù dianav" + UNSUPPORTED_FILE_TYPE: "Doare restr amskor" + FAILED_TO_MOVE_UPLOADED_FILE: "C'hwitadenn en ur zilec'hiañ ar restr pellgaset." + FILE_UPLOADED_SUCCESSFULLY: "Restr pellgaset gant berzh" + FILE_DELETED: "Restr dilamet" + FILE_COULD_NOT_BE_DELETED: "N'haller ket dilemel ar restr" + FILE_NOT_FOUND: "N'eus ket bet kavet ar restr" + NO_FILE_FOUND: "Restr ebet kavet" + GRAV_WAS_SUCCESSFULLY_UPDATED_TO: "Hizivaet eo bet Grav da" + GRAV_UPDATE_FAILED: "C'hwitadenn war hizivadenn Grav" + EVERYTHING_UPDATED: "Hizivaet pep tra" + UPDATES_FAILED: "C'hwitadenn war a hizivadennoù" + AVATAR_BY: "Avatar gant" + LAST_BACKUP: "Gwared diwezhañ" + FULL_NAME: "Anv klok" + USERNAME: "Anv arveriad" + EMAIL: "Chomlec'h postel" + PASSWORD: "Ger-tremen" + PASSWORD_CONFIRM: "Kadarnat ar ger-tremen" + TITLE: "Titl" + LANGUAGE: "Yezh" + ACCOUNT: "Kont" + EMAIL_VALIDATION_MESSAGE: "Ret eo reiñ ur chomlec'h postel talvoudek" + PASSWORD_VALIDATION_MESSAGE: "Ret eo d'ar ger-tremen enderc'hel ur niverenn, ul lizherenn vras hag ul lizherenn vihan hag 8 arouezenn d'an nebeutañ" + LANGUAGE_HELP: "Dibabit ar yezh" + MEDIA: "Media" + DEFAULTS: "Dre ziouer" + SITE_TITLE: "Titl al lec'hienn" + SITE_TITLE_PLACEHOLDER: "Titl ledan al lec'hienn" + SITE_TITLE_HELP: "Titl dre ziouer ho lec'hienn, arveret en neuzioù" + DEFAULT_AUTHOR: "Aozer dre ziouer" + DEFAULT_AUTHOR_HELP: "Un anv aozer dre ziouer, arveret en neuzioù pe er pajennoù" + DEFAULT_EMAIL: "Chomlec'h postel dre ziouer" + DEFAULT_EMAIL_HELP: "Ur chomlec'h postel dre ziouer, arveret en neuze pe er pajennoù" + TAXONOMY_TYPES: "Doareoù rummadoù" + TAXONOMY_TYPES_HELP: "An doareoù rummadoù a rank bezañ erspizet amañ ma fell deoc'h arverañ anezho er pajennoù" + PAGE_SUMMARY: "Berradenn ar bajenn" + ENABLED: "Gweredekaet" + ENABLED_HELP: "Gweredekaat berradenn ar bajenn (ar verradenn a zistro an hevelep tra hag endalc'had ar bajenn)" + 'YES': "Ya" + 'NO': "Ket" + SUMMARY_SIZE: "Ment ar verradenn" + SUMMARY_SIZE_HELP: "An niverenn a arouezenn da arverañ evel berradenn ur bajenn" + FORMAT: "Mentrezh" + FORMAT_HELP: "berr = arverañ degouezh kentañ an disranner pe ment; hir = laosket e vo an disranner berradenn a-gostez" + SHORT: "Berr" + LONG: "Hir" + DELIMITER: "Disranner" + DELIMITER_HELP: "Disranner ar verradenn (diouer '===')" + METADATA: "Metaroadennoù" + METADATA_HELP: "Skrammet e vo ar gwerzhioù metaroadennoù dre ziouer war an holl bajennoù war-bouez m'eo flastret gant ar bajenn" + NAME: "Anv" + CONTENT: "Endalc'had" + REDIRECTS_AND_ROUTES: "Adheñchañ ha treugoù" + CUSTOM_REDIRECTS: "Adheñchañ personelaet" + CUSTOM_REDIRECTS_HELP: "treugoù da adheñchañ davet pajennoù all. Talvoudek eo an amsaviñ regex" + CUSTOM_REDIRECTS_PLACEHOLDER_KEY: "/un/anv" + CUSTOM_REDIRECTS_PLACEHOLDER_VALUE: "/un/adeñchañ" + CUSTOM_ROUTES: "Treugoù personelaet" + CUSTOM_ROUTES_HELP: "treugoù da adheñchañ davet pajennoù all. Talvoudek eo an amsaviñ Regex" + CUSTOM_ROUTES_PLACEHOLDER_KEY: "/ho/anv" + CUSTOM_ROUTES_PLACEHOLDER_VALUE: "/ho/treug" + FILE_STREAMS: "Lanvioù restroù" + DEFAULT: "Dre ziouer" + PAGE_MEDIA: "Media ar bajenn" + OPTIONS: "Dibarzhioù" + PUBLISHED: "Embannet" + PUBLISHED_HELP: 'Dre ziouer eo embannet ur bajenn war-bouez m''eo lakaet da "Embannet: ket" pe dre un deiziad embann en dazont, pe un deiziad diembannañ tremenet' + DATE: "Deiziad" + DATE_HELP: "Ar vaezienn deiziad a laosk ac'hanoc'h da arventennañ un deiziad liammet gant ar bajenn." + PUBLISHED_DATE: "Deiziad embann" + PUBLISHED_DATE_HELP: "Gallout a rit reiñ un deiziad da embann ent emgefreek." + UNPUBLISHED_DATE: "Deiziad diembannañ" + UNPUBLISHED_DATE_HELP: "Gallout a rit reiñ un deiziad evit diembannañ ent emgefreek." + ROBOTS: "Robotoù" + TAXONOMIES: "Rummadoù" + TAXONOMY: "Rummad" + ADVANCED: "Kempleshoc'h" + SETTINGS: "Arventennoù" + FOLDER_NUMERIC_PREFIX: "Rakger niverel an teuliad" + FOLDER_NUMERIC_PREFIX_HELP: "Rakgerioù niverel evit urzhiañ gant an dorn ha emplegañ ar gwelusted" + FOLDER_NAME: "Anv an teuliad" + FOLDER_NAME_HELP: "Anv an teuliad a vo kadavet er reizhiad restroù evit ar bajenn" + PARENT: "Kar" + DEFAULT_OPTION_ROOT: "- Gwrizienn -" + DEFAULT_OPTION_SELECT: "- Diuzañ -" + DISPLAY_TEMPLATE: "Skrammañ ar patrom" + DISPLAY_TEMPLATE_HELP: "An doare pajenn a ziviz peseurt patrom twig a zeznaouo ar bajenn" + BODY_CLASSES: "Klasoù korf" + ORDERING: "Urzh" + PAGE_ORDER: "Urzh ar pajennoù" + OVERRIDES: "Flastrañ" + MENU: "Lañser" + MENU_HELP: "Ar chadennoù da arverañ el lañser. Ma n'eo ket arventennet, Titl a vo arveret." + SLUG: "Slug" + SLUG_HELP: "An argemenn slug a aotren ac'hanoc'h da arventennañ URL lodenn ar bajenn" + SLUG_VALIDATE_MESSAGE: "Lizherennoù bihan, sifroù ha tiredoù a c'hall bezañ er slug hepken" + PROCESS: "Keweriañ" + PROCESS_HELP: "Reoliañ penaos eo keweriet ar pajennoù. Gallout a ra bezañ lakaet dre bajenn kentoc'h eget en un doare hollek" + DEFAULT_CHILD_TYPE: "Doare bugel dre ziouer" + USE_GLOBAL: "Arverañ Hollek" + ROUTABLE: "Treugus" + ROUTABLE_HELP: "M'eo haezadus ar bajenn dre un URL" + CACHING: "Krubuilhiñ" + VISIBLE: "Gwelus" + VISIBLE_HELP: "Despizañ a ra gwelusted ur bajenn er merdeiñ." + DISABLED: "Diweredekaet" + ITEMS: "Ergorennoù" + ORDER_BY: "Urzhiañ dre" + ORDER: "Urzh" + FOLDER: "Teuliad" + ASCENDING: "War-gresk" + DESCENDING: "War-zigresk" + ADD_MODULAR_CONTENT: "Ouzhpennañ un endalc'had molladel" + PAGE_TITLE: "Titl ar bajenn" + PAGE_TITLE_HELP: "Titl ar bajenn" + PAGE: "Pajenn" + MODULAR_TEMPLATE: "Patrom molladel" + FRONTMATTER: "Frontmatter" + FILENAME: "Anv ar restr" + PARENT_PAGE: "Pajenn gar" + HOME_PAGE: "Pennbajenn" + HOME_PAGE_HELP: "Pajenn arveret gant Grav evel pajenn degemer dre ziouer" + DEFAULT_THEME: "Neuz dre ziouer" + DEFAULT_THEME_HELP: "Arventennañ an neuz arveret gant Grav dre ziouer (Antimatter dre ziouer)" + TIMEZONE: "Gwerzhid-eur" + TIMEZONE_HELP: "Flastrañ gwerzhid-eur dre ziouer an dafariad" + SHORT_DATE_FORMAT: "Mentrezh skrammañ an deiziad berr" + SHORT_DATE_FORMAT_HELP: "Arventennan ar mentrezh deiziad berr da arverañ gant an neuzioù" + LONG_DATE_FORMAT: "Mentrezh deiziad hir" + LONG_DATE_FORMAT_HELP: "Arventennañ ar mentrezh deiziad hir a vo arveret en neuzioù" + DEFAULT_ORDERING: "Urzh dre ziouer" + DEFAULT_ORDERING_HELP: "Pajennoù er roll a vo skrammet en urzh-mañ war-bouez m'eo flastret" + DEFAULT_ORDERING_DEFAULT: "Dre ziouer - diazezet war anv an teuliad" + DEFAULT_ORDERING_FOLDER: "Teuliad - diazezet war anv an teuliad hep rakger" + DEFAULT_ORDERING_TITLE: "Titl - diazezet war vaezienn ditl an talbenn" + DEFAULT_ORDERING_DATE: "Deiziad - diazezet war vaezienn deiziad an talbenn" + DEFAULT_ORDER_DIRECTION: "Tu an urzh dre ziouer" + DEFAULT_ORDER_DIRECTION_HELP: "Tu ar pajennoù er roll" + DEFAULT_PAGE_COUNT: "Niver a bajennoù dre ziouer" + DEFAULT_PAGE_COUNT_HELP: "Niver a bajennoù en ur roll d'ar muiañ" + DATE_BASED_PUBLISHING: "Embannadenn diazezet war un deiziad" + DATE_BASED_PUBLISHING_HELP: "(Di)embann pennadoù ent emgefreek hervez o deiziad" + EVENTS: "Darvoudoù" + EVENTS_HELP: "(Di)weredekaat darvoudoù resis. Diweredekaat anezho a c'hall terriñ enlugelladoù" + REDIRECT_DEFAULT_ROUTE: "Adheñchañ an treug dre ziouer" + REDIRECT_DEFAULT_ROUTE_HELP: "Adheñchañ ent emgefreek d'un treug pajenn dre ziouer" + LANGUAGES: "Yezhoù" + SUPPORTED: "Skoret" + SUPPORTED_HELP: "Roll bonegoù yezh 2 lizherenn ennañ disrannet gant skejoù (skouer: 'br, cy, en')" + TRANSLATIONS_ENABLED: "Troidigezhioù gweredekaet" + TRANSLATIONS_ENABLED_HELP: "Skor an troidigezhioù e Grav, an enlugelladoù hag an askouezhioù" + TRANSLATIONS_FALLBACK: "Troidigezh dre ziouer" + TRANSLATIONS_FALLBACK_HELP: "Arverañ un droidigezh all ma n'eus ket eus ar tezh oberiant" + ACTIVE_LANGUAGE_IN_SESSION: "Yezhoù oberiant en estez" + ACTIVE_LANGUAGE_IN_SESSION_HELP: "Kadaviñ ar yezh oberiant en estez" + HTTP_HEADERS: "Talbennoù HTTP" + EXPIRES: "Diamzer" + EXPIRES_HELP: "Arventennañ an talbenn diamzeriñ e eilennoù." + LAST_MODIFIED: "Kemmet da ziwezhañ" + LAST_MODIFIED_HELP: "Arventennañ an talbenn kemmet da ziwezhañ a c'hall skoazell da wellaat ar proksi ha krubuilh ar merdeer" + ETAG: "ETag" + ETAG_HELP: "Arventennañ an talbenn etag evit skoazell da c'houzout peur eo bet kemmet ur bajenn" + VARY_ACCEPT_ENCODING: "Vary accept encoding" + VARY_ACCEPT_ENCODING_HELP: 'Arventennañ a ra an talbenn `Vary: Accept Encoding` evit skoazell gant ar proksi hag ar c''hrubuilh CDN' + MARKDOWN_EXTRA_HELP: "Gweredekaat ar skor dre ziouer evit Markdown Ectra - https://michelf.ca/projects/php-markdown/extra/" + AUTO_LINE_BREAKS: "Tremen d'al linenn ent emgefreek" + AUTO_LINE_BREAKS_HELP: "Gweredekaat skor tremen al linenn ent emgefreek e Markdown" + AUTO_URL_LINKS: "Ereoù URL emgefreek" + AUTO_URL_LINKS_HELP: "Gweredekaat amdroadur emgefreek an URLoù da ereoù HTML" + ESCAPE_MARKUP: "Gwareziñ an HTML" + ESCAPE_MARKUP_HELP: "Gwareziñ ar c'hlavioù e elfennoù HTML" + CACHING_HELP: "Trec'haoler hollek evit (di)weredekaat krubuilh Grav" + CACHE_CHECK_METHOD: "Hentenn gwiriekaat ar c'hrubuilh" + CACHE_CHECK_METHOD_HELP: "Dibab an hentenn arveret gant Grav evit gwiriekaat m'eo bet kemmer ar restoù pajenn." + CACHE_DRIVER: "Sturier Krubuilh" + CACHE_DRIVER_HELP: "Dibab pe sturier krubuilh a zo arveret Grav. 'Dinoiñ emgefreek' a glask kavout pe zoare a zo an hini gwellañ" + CACHE_PREFIX: "Rakger ar c'hrubuilh" + CACHE_PREFIX_HELP: "Lodenn naoudi an alc'hwez Grav. Na gemmit anezhi ma n'ouzit ket petra rit." + CACHE_PREFIX_PLACEHOLDER: "Deveret eus an URL diazez (flastret en un enkañ ur chadenn dargouezhek)" + LIFETIME: "Padelezh buhez" + LIFETIME_HELP: "Arventennañ padelezh ar c'hrubuilh e eilennoù. 0 = anvevenn" + GZIP_COMPRESSION: "Koazhadur Gzip" + GZIP_COMPRESSION_HELP: "Gweredekaat koazhadur Gzip ar bajenn Grav evit kreskiñ an digonusted." + TWIG_TEMPLATING: "Patromiñ Twig" + TWIG_CACHING: "Krubuilh Twig" + TWIG_CACHING_HELP: "Reoliañ wikefre krubuilh Twig. Laoskit gweredekaet evit an digonusted gwellañ." + TWIG_DEBUG: "Diveugañ Twig" + TWIG_DEBUG_HELP: "Aotren an dibarzh evit chom hep kargañ an askouezh diveugañ Twig" + DETECT_CHANGES: "Dinoiñ ar c'hemmoù" + DETECT_CHANGES_HELP: "Adkempunet e vo krubuilh Twig ent emgefreek ma vez dinoet kemmoù er patromoù Twig" + AUTOESCAPE_VARIABLES: "Gwareziñ an argemennoù ent emgefreek" + AUTOESCAPE_VARIABLES_HELP: "Gwareziñ an holl argemennoù ent emgefreek. Moarvat e torro ho lec'hienn" + ASSETS: "Madoù" + CSS_PIPELINE: "Arrevellañ CSS" + CSS_PIPELINE_HELP: "Arrevellañ ar CSS a zo unvanadur meur a loaz CSS en ur restr hepken" + CSS_PIPELINE_INCLUDE_EXTERNALS: "Ebarzhiñ restroù estren en arrevellañ CSS" + CSS_PIPELINE_INCLUDE_EXTERNALS_HELP: "URLoù diavaez a zo gant daveoù restroù daveel a-wechoù ha ne rankont ket bezañ arrevellet" + CSS_PIPELINE_BEFORE_EXCLUDES: "Deoueziñ an arrevellañ CSS da gentañ" + CSS_PIPELINE_BEFORE_EXCLUDES_HELP: "Deoueziñ an arrevellañ CSS a-raok kement dave CSS all ha n'int ket enkorfet" + CSS_MINIFY: "Bihanadur CSS" + CSS_MINIFY_HELP: "Bihanaat ar CSS e-pad an arrevellañ" + CSS_MINIFY_WINDOWS_OVERRIDE: "Amsaviñ bihanadur ar CSS Windows" + CSS_MINIFY_WINDOWS_OVERRIDE_HELP: "Amsaviñ ar bihanadur evit savennoù Windows. Faos dre ziouer abalamour da ThreadStackSize" + CSS_REWRITE: "Adskrivañ CSS" + CSS_REWRITE_HELP: "Adskrivañ kement URL daveel CSS e-pad an arrevellañ" + JAVASCRIPT_PIPELINE: "Arrevellañ Javascript" + JAVASCRIPT_PIPELINE_HELP: "An arrevellañ JS a zo unvanadur meur a restr JS en ur restr hepken" + JAVASCRIPT_PIPELINE_INCLUDE_EXTERNALS: "Enkorfañ ar JS diavaez evit an arrevellañ" + JAVASCRIPT_PIPELINE_INCLUDE_EXTERNALS_HELP: "Urloù diavaez o deus daveoù restroù daveel a-wechoù ha ne rankont ket bezañ arrevellet" + JAVASCRIPT_PIPELINE_BEFORE_EXCLUDES: "Arrevellañ JS da gentañ" + JAVASCRIPT_PIPELINE_BEFORE_EXCLUDES_HELP: "Deoueziñ an arrevellañ JS a-raok kement dave JS all ha n'int ket enkorfet" + JAVASCRIPT_MINIFY: "Bihanat ar javascript" + JAVASCRIPT_MINIFY_HELP: "Bihanaat ar JS e-pad an arrevellañ" + ENABLED_TIMESTAMPS_ON_ASSETS: "Gweredekaat ar boneg-amzer war al loazioù" + ENABLED_TIMESTAMPS_ON_ASSETS_HELP: "Gweredekaat bonegoù-amzer al loazioù" + COLLECTIONS: "Dastumadegoù" + ERROR_HANDLER: "Dornataour fazioù" + DISPLAY_ERRORS: "Skrammañ ar fazioù" + DISPLAY_ERRORS_HELP: "Skrammañ ur bajenn fazi gant munudoù" + LOG_ERRORS: "Kerzhlevr ar fazioù" + LOG_ERRORS_HELP: "Lakaat kerzhlevr ar fazioù en teuliad /logs" + DEBUGGER: "Diveuger" + DEBUGGER_HELP: "Gweredekaat diveuger Grav hag an arventennoù da heul" + DEBUG_TWIG: "Diveugañ Twig" + DEBUG_TWIG_HELP: "Gweredekaat diveugañ ar patromoù Twig" + SHUTDOWN_CLOSE_CONNECTION: "Shutdown a serr ar c'hennask" + SHUTDOWN_CLOSE_CONNECTION_HELP: "Serriñ ar c'hennask a-raok gervel onShutdown(). 'false' evit diveugañ" + DEFAULT_IMAGE_QUALITY: "Perzhded skeudenn dre ziouer" + DEFAULT_IMAGE_QUALITY_HELP: "Perzhded skeudenn dre ziouer da arverañ e-pad adstandilhonañ ar skeudennoù (85%)" + CACHE_ALL: "Lakaat an holl skeudennoù er c'hrubuilh" + CACHE_ALL_HELP: "Lakaat an holl skeudennoù da dremen dre reizhiad krubuilh Grav zoken ma n'o deus dornatadur media ebet" + IMAGES_DEBUG: "Rouedigell diveugañ ar skeudenn" + IMAGES_DEBUG_HELP: "Diskouez un diflugell a-us d'ar skeudennoù a ziskouez an donder piksel pa labourer war Retina da skouer" + UPLOAD_LIMIT: "Bevenn ment ar restroù da bellgas" + UPLOAD_LIMIT_HELP: "Lakaat ar ment restroù uhelañ e eizhbitoù (0 a zo anvevenn)" + ENABLE_MEDIA_TIMESTAMP: "Gweredekaat ar boneg-amzer war ar media" + ENABLE_MEDIA_TIMESTAMP_HELP: "Ouzhpennañ ur boneg-amzer diazezet war an deiziad kemmadur evit pep elfenn media" + SESSION: "Estez" + SESSION_ENABLED_HELP: "Gweredekaat skor an estez evit Grav" + TIMEOUT: "Diamzeriñ" + TIMEOUT_HELP: "Lakaat an amzer diamzeriñ e eilennoù" + SESSION_NAME_HELP: "Un naoudi arveret da stummañ anv toupin an estez" + ABSOLUTE_URLS: "URL dizave" + ABSOLUTE_URLS_HELP: "URLoù dizave pe daveel evit 'base_url'" + PARAMETER_SEPARATOR: "Disranner arventenn" + PARAMETER_SEPARATOR_HELP: "An disranner evit an arventennoù tremenet a c'hall bezañ kemmet evit Apache war Windows" + TASK_COMPLETED: "Trevell echuet" + EVERYTHING_UP_TO_DATE: "Pep tra a zo hizivaet" + UPDATES_ARE_AVAILABLE: "hizivadennoù hegerz" + IS_AVAILABLE_FOR_UPDATE: "a zo gant un hizivadenn hegerz" + IS_NOW_AVAILABLE: "a zo hegerz" + CURRENT: "Bremanel" + UPDATE_GRAV_NOW: "Hizivaat Grav bremañ" + GRAV_SYMBOLICALLY_LINKED: "Gant un ere arouezel eo staliet Grav. Dihegerz eo an hizivadenn" + UPDATING_PLEASE_WAIT: "Oc'h hizivaat... gortozit, emañ o pellgargañ" + OF_THIS: "eus an" + OF_YOUR: "eus ho" + HAVE_AN_UPDATE_AVAILABLE: "en deus un hizivadenn hegerz" + SAVE_AS: "Enrollañ evel" + MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_DESC: "Sur oc'h e fell deoc'h dilemel ar bajenn-mañ hag holl he bugale? M'eo troet ar bajenn en ur yezh all e vo miret an troidigezhioù a rankout a reot o dilemel en un doare distag. E mod all e vo dilamet teuliad ar bajenn gant an is-pajennoù. N'haller ket dizober ar gwered-mañ." + AND: "ha" + UPDATE_AVAILABLE: "Hizivadenn hegerz" + METADATA_KEY: "Alc'hwez (sk. 'Gerioù-alc'hwez')" + METADATA_VALUE: "Gwerzh (sk. 'Blog, Grav')" + USERNAME_HELP: "Etre 3 ha 16 arouezenn e rank an anv arveriad bezañ o kontañ al lizherennoù bihan, an niverennoù, an islinennoù hag ar barrennigoù. N'eo ket aotreet al lizherennoù bras, an esaouennoù hag an arouezennoù arbennik" + FULLY_UPDATED: "Hizivaet" + SAVE_LOCATION: "Lec'hiadur enrollañ" + PAGE_FILE: "Patrom pajenn" + PAGE_FILE_HELP: "Anv restr patrom ar bajenn, ha patrom skrammañ ar bajenn dre ziouer" + NO_USER_ACCOUNTS: "Kont arveriad ebet kavet, krouit unan da gentañ..." + REDIRECT_TRAILING_SLASH: "Adheñchañ ar veskell dibenn" + REDIRECT_TRAILING_SLASH_HELP: "Ober un adheñchañ 301 e-lerc'h merañ an beskell dibenn an URI en un doare treuzwelus." + DEFAULT_DATE_FORMAT: "Mentrezh deiziad ar bajenn" + DEFAULT_DATE_FORMAT_HELP: 'Mentrezh deiziad ar bajenn arveret gant Grav. Dre ziouer, Grav a glask divinout mentrezh an deiziad met gallout a rit erspizañ unan gant kevreadur deiziad PHP (sk.: Y-m-d H:i)' + DEFAULT_DATE_FORMAT_PLACEHOLDER: "Divinout en emgefreek" + IGNORE_FILES: "Leuskel restroù a-gostez" + IGNORE_FILES_HELP: "Restroù da leuskel a-gostez e-pad keweriañ ar pajennoù" + IGNORE_FOLDERS: "Leuskel teuliadoù a-gostez" + IGNORE_FOLDERS_HELP: "Teuliadoù resis da leuskel a-gostez e-pad keweriañ ar pajennoù" + HTTP_ACCEPT_LANGUAGE: "Lakaat yezh ar merdeer" + HTTP_ACCEPT_LANGUAGE_HELP: "Gallout a rit klask arventennañ ar yezh gant hini ar talbenn `http_accept_language` ar merdeer" + OVERRIDE_LOCALE: "Flastrañ ar yezh" + OVERRIDE_LOCALE_HELP: "Flastrañ arventenn yezh PHP diazezet war ar yezh vremanel" + REDIRECT: "Adheñchañ ar bajenn" + REDIRECT_HELP: "Enankit hent ur bajenn pe un URL diavaez da adheñchañ ar bajenn. Sk. '/un/hent' pe 'http://ulload.bzh'" + PLUGIN_STATUS: "Stad an elugellad" + INCLUDE_DEFAULT_LANG: "Enkorfañ ar yezh dre ziouer" + INCLUDE_DEFAULT_LANG_HELP: "Ouzhpennañ a raio ar yezh dre ziouer en holl URLoù er yezh dre ziouer. Sk. '/br/blog/post'" + ALLOW_URL_TAXONOMY_FILTERS: "URL siloù rummad" + ALLOW_URL_TAXONOMY_FILTERS_HELP: "Dastumadegoù pajennoù a aotren ac'hanoc'h da silañ dre '/rummad:gwerzh'." + REDIRECT_DEFAULT_CODE: "Boneg adheñchan dre ziouer" + REDIRECT_DEFAULT_CODE_HELP: "Boneg stad HTTP da arverañ evit adheñchañ" + IGNORE_HIDDEN: "Leuskel ar re kuzhet a-gostez" + IGNORE_HIDDEN_HELP: "Leuskel an holl restroù ha teuliadoù a grog gant ur POENT" + WRAPPED_SITE: "Lec'hienn enkorfet" + WRAPPED_SITE_HELP: "Evit ma ouife an neuzioù/enlugelladoù m'eo enkorfet Grav en ur savenn all" + FALLBACK_TYPES: "Aotren doareoù fallback" + FALLBACK_TYPES_HELP: "Doareoù restr aotreet a c'hall bezañ kavet m'int haezet dre hent ar bajenn. An holl zoareoù media skoret dre ziouer." + INLINE_TYPES: "Doareoù fallback enkorfet" + INLINE_TYPES_HELP: "Ur roll doareoù restroù a rank bezañ skrammet en un doare enkorfet kentoc'h eget pellgarget" + APPEND_URL_EXT: "Ouzhpennañ an astenn d'an URL" + APPEND_URL_EXT_HELP: "Ouzhpennañ a raio un astenn personelaet da URL ar bajenn. Talvezout a ra e glasko Grav ur patrom anvet `..twig`" + PAGE_MODES: "Modoù pajenn" + PAGE_TYPES: "Doareoù pajenn" + ACCESS_LEVELS: "Liveoù haeziñ" + GROUPS: "Strolladoù" + GROUPS_HELP: "Roll ar strolladoù gant an arveriad enno" + ADMIN_ACCESS: "Haeziñ ardoer" + SITE_ACCESS: "Haeziñ d'al lec'hienn" + INVALID_SECURITY_TOKEN: "Reveziadenn diogelroez didalvoudek" + ACTIVATE: "Gweredekaat" + TWIG_UMASK_FIX: "Ratreadur Umask" + TWIG_UMASK_FIX_HELP: "Twig a grou ar restroù krubuilh gant 0755 dre ziouer, ar ratreañ a lak anezho da 0755" + CACHE_PERMS: "Aotreoù ar c'hrubuilh" + CACHE_PERMS_HELP: "Aotreoù dre ziouer teuliad ar c'hrubuilh. 0755 pe 0775 peurvuiañ, hervez ar c'hefluniadur" + REMOVE_SUCCESSFUL: "Dilamet gant berzh" + REMOVE_FAILED: "C'hwitadenn war an dilemel" + HIDE_HOME_IN_URLS: "Kuzhat hent ar pennbajenn en URL" + HIDE_HOME_IN_URLS_HELP: "Gwiriekaat a raio n'eo ket daveet hent skoueriek an degemer gant hentoù dre ziouer ar pajennoù dindan an degemer" + TWIG_FIRST: "Keweriañ an Twig da gentañ" + TWIG_FIRST_HELP: "M'ho peus gweredekaat keweriañ ar bajenn Twig e c'hallit kefluniañ Twig evit e geweriañ a-raok pe goude ar Markdown" + SESSION_SECURE: "Diogel" + SESSION_SECURE_HELP: 'M''eo gwir, diskouez a ra eo ret d''ar c''hehentiñ evit an toupin-mañ bezañ graet war un treuzkas diogel. DIWALLIT: Gweredekait an dra-se war lec''hiennoù e HTTPS nemetken' + SESSION_HTTPONLY: "HTTP nemetken" + SESSION_HTTPONLY_HELP: "M'eo gwir, diskouez a ra eo ret d'ar c'hehentiñ evit an toupin-mañ bezañ graet war un treuzkas HTTP ha n'eo ket aotreet kemmañ ar Javascript" + REVERSE_PROXY: "Proksi en tu-gin" + REVERSE_PROXY_HELP: "Gweredekait an dra-se m'hoc'h a-dreñv ur proksi en tu-gin hag ho peus diaesterioù gant an URLoù oc'h enderc'hel ur porzh didalvoudek" + INVALID_FRONTMATTER_COULD_NOT_SAVE: "Frontmatter didalvoudek, n'haller ket enrollan" + ADD_FOLDER: "Ouzhpennañ un teuliad" + PROXY_URL: "URL ar proksi" + PROXY_URL_HELP: "Enankit HERBERC'HIER pe IP ar proksi hag ar PORZH" + NOTHING_TO_SAVE: "Netra da enrollañ" + FILE_ERROR_ADD: "Degouezhet ez eus bet ur fazi en ur glask enrollañ ar restr" + FILE_ERROR_UPLOAD: "Degouezhet ez eus bet ur fazi en ur glask pellgas ar restr" + FILE_UNSUPPORTED: "Doare restr anskor" + ADD_ITEM: "Ouzhpennañ un elfenn" + FILE_TOO_LARGE: "Re leden eo ar restr evit bezañ pellgaset. %s eo an uhelañ aotreet hervez
    hoc'h arventennoù PHP. Kreskit an arventenn PHP`post_max_size`" + INSTALLING: "O staliañ" + LOADING: "O kargañ.." + DEPENDENCIES_NOT_MET_MESSAGE: "Ret eo deoc'h staliañ an amzalc'hoù da-heul a-raok:" + ERROR_INSTALLING_PACKAGES: "Fazi en ur staliañ ar pakad(où)" + INSTALLING_DEPENDENCIES: "O staliañ an amzalc'hoù..." + INSTALLING_PACKAGES: "O staliañ ar pakad(où).." + PACKAGES_SUCCESSFULLY_INSTALLED: "Pakad(où) staliet gant berzh." + READY_TO_INSTALL_PACKAGES: "Prest da staliañ ar pakad(où)" + PACKAGES_NOT_INSTALLED: "N'eo ket stalied ar pakadoù" + PACKAGES_NEED_UPDATE: "Staliet eo ar pakadoù endeo, met re gozh eo" + PACKAGES_SUGGESTED_UPDATE: "Staliet eo ar pakadoù endeo, dereat eo an handelv, met hizivaet e vint evit ma vefec'h en handelv diwezhañ" + REMOVE_THE: "Dilemel an %s" + CONFIRM_REMOVAL: "Sur oc'h e fell deoc'h dilemel %s?" + REMOVED_SUCCESSFULLY: "%s dilamet gant berzh" + ERROR_REMOVING_THE: "Fazi en ur zilemel %s" + ADDITIONAL_DEPENDENCIES_CAN_BE_REMOVED: "An amzalc'hoù da heul a zo azgoulennet gant %s, met n'eo ket azgoulennet gant ur pakad all. Ma ne arverit ket anezho e c'hallit o dilemel adalek amañ." + READY_TO_UPDATE_PACKAGES: "Prest da hizivaat ar pakad(où)" + ERROR_UPDATING_PACKAGES: "Fazi en ur hizivaat ar pakad(où)" + UPDATING_PACKAGES: "Oc'h hizivaat ar pakad(où).." + PACKAGES_SUCCESSFULLY_UPDATED: "Pakad(où) hizivaet gant berzh." + UPDATING: "Hizivaet" + GPM_RELEASES: "Ermaeziadennoù GPM" + GPM_RELEASES_HELP: "Dibabit 'Amprouiñ' evit staliañ an handelv beta pe amprouiñ" + STABLE: "Stabil" + TESTING: "Amprouiñ" + FRONTMATTER_PROCESS_TWIG: "Keweriañ frontmatter Twig" + FRONTMATTER_PROCESS_TWIG_HELP: "P'eo oberiant e c'hallit arverañ argemennoù kefluniañ Twig e frontmatter ar bajenn" + FRONTMATTER_IGNORE_FIELDS: "Leuskel maeziennoù Frontmatter a-gostez" + FRONTMATTER_IGNORE_FIELDS_HELP: "Maeziennoù Frontmatter a c'hall enderc'hel Twig met ne rankont ket bezañ keweriet, evel 'forms'" + PACKAGE_X_INSTALLED_SUCCESSFULLY: "Pakad %s staliet gant berzh" + NEEDS_GRAV_1_1: " Emaoc'h oc'h erounit Grav v%s. Ret eo deoc'h hizivaat d'an handelv diwezhañ: Grav v1.1.x evit bezañ sur e vo keverlec'h. Gallout a ra talvezout vo ret tremen da ermaeziadennoù amprouiñ GPM e kefluniadur ar reizhiad." + ORDERING_DISABLED_BECAUSE_PARENT_SETTING_ORDER: "Urzh ar c'har, diweredekaet eo an urzhiañ" + ORDERING_DISABLED_BECAUSE_PAGE_NOT_VISIBLE: "Diwelus eo ar bajenn, diweredekaet eo an urzhiañ" + ORDERING_DISABLED_BECAUSE_TOO_MANY_SIBLINGS: "N'eo ket skoret an urzhiañ dre an ardeiñ dre ma zo ouzhpenn 200 c'hoar" + CANNOT_ADD_MEDIA_FILES_PAGE_NOT_SAVED: 'EVEZHIADENN: n''hallit ket ouzhpennañ restroù media evit enrollañ ar bajenn. Klikit war ''Enrollañ'' a-us' + CANNOT_ADD_FILES_PAGE_NOT_SAVED: 'EVEZHIADENN: ret eo enrollañ ar bajenn a-raok pellgas restroù dezhi.' + DROP_FILES_HERE_TO_UPLOAD: "Lakait ho restroù amañ pe klikit amañ" + INSERT: "Enlakaat" + UNDO: "Dizober" + REDO: "Adober" + HEADERS: "Talbennoù" + BOLD: "Tev" + ITALIC: "Stouet" + STRIKETHROUGH: "Barrennet" + SUMMARY_DELIMITER: "Bevenner berradenn" + LINK: "Ere" + IMAGE: "Skeudenn" + BLOCKQUOTE: "Meneg" + UNORDERED_LIST: "Roll dizurzh" + ORDERED_LIST: "Roll urzhiet" + EDITOR: "Embanner" + PREVIEW: "Alberz" + FULLSCREEN: "Skramm a-bezh" + MODULAR: "Molladel" + NON_ROUTABLE: "Nann-hentus" + NON_MODULAR: "Nann-molladel" + NON_VISIBLE: "Diwelus" + NON_PUBLISHED: "Diembannet" + CHARACTERS: "arouezenn" + PUBLISHING: "Oc'h embann" + MEDIA_TYPES: "Doareoù media" + IMAGE_OPTIONS: "Dibarzhioù skeudenn" + MIME_TYPE: "Doare Mime" + THUMB: "Melvenn" + TYPE: "Doare" + FILE_EXTENSION: "Astenn restr" + LEGEND: "Alc'hwez ar bajenn" + MEMCACHE_SERVER: "Dafariad memcache" + MEMCACHE_SERVER_HELP: "Chomlec'h an dafariad memcache" + MEMCACHE_PORT: "Porzh memcache" + MEMCACHE_PORT_HELP: "Porzh an dafariad memcache" + MEMCACHED_SERVER: "Dafariad memcache" + MEMCACHED_SERVER_HELP: "Chomlec'h an dafariad memcache" + MEMCACHED_PORT: "Porzh memcache" + MEMCACHED_PORT_HELP: "Porzh an dafariad memcache" + REDIS_SERVER: "Dafariad redis" + REDIS_SERVER_HELP: "Chomlec'h an dafariad memcache" + REDIS_PORT: "Porzh redis" + REDIS_PORT_HELP: "Porzh an dafariad redis" + ALL: "Pep tra" + FROM: "eus" + TO: "da" diff --git a/user/plugins/admin/languages/ca.yaml b/user/plugins/admin/languages/ca.yaml new file mode 100644 index 0000000..5a42b31 --- /dev/null +++ b/user/plugins/admin/languages/ca.yaml @@ -0,0 +1,633 @@ +--- +PLUGIN_ADMIN: + ADMIN_BETA_MSG: "Aquesta és una versió beta! Utilitza-la en producció sota el teu propi risc..." + ADMIN_REPORT_ISSUE: "Has trobat algun problema? Sisplau, reporta'l a GitHub." + EMAIL_FOOTER: "Funcionant amb Grav - El CMS de fitxers plans modern" + LOGIN_BTN: "Inicia sessió" + LOGIN_BTN_FORGOT: "Ho he oblidat" + LOGIN_BTN_RESET: "Restablir contrasenya" + LOGIN_BTN_SEND_INSTRUCTIONS: "Envia instruccions pel reset" + LOGIN_BTN_CLEAR: "Neteja el formulari" + LOGIN_BTN_CREATE_USER: "Crea usuari" + LOGIN_LOGGED_IN: "S'ha iniciat sessió correctament" + LOGIN_FAILED: "No s'ha pogut iniciar sessió" + LOGGED_OUT: "S'ha tancat la sessió" + RESET_NEW_PASSWORD: "Sisplau introdueix una nova contasenya …" + RESET_LINK_EXPIRED: "L'enllaç per a restablir contrasenya ha expirat, torna a provar" + RESET_PASSWORD_RESET: "S'ha restablert la contrasenya" + RESET_INVALID_LINK: "L'enllaç per a restablir contrasenya invàl·lid, torna a provar" + FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL: "Les instruccions per a restablir la contrasenya s'han enviat per correu electrònic a %s" + FORGOT_FAILED_TO_EMAIL: "S'ha fallat al enviar les instruccions, sisplau torna-ho a provar" + FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL: "No es pot restablir la contrasenya per a %s, no té cap email assignat" + FORGOT_USERNAME_DOES_NOT_EXIST: "L'usuari %s no existeix" + FORGOT_EMAIL_NOT_CONFIGURED: "No es pot restablir la contrasenya. Aquest lloc no està configurat per enviar missatges de correu electrònic" + FORGOT_EMAIL_SUBJECT: "%s Petició de restabliment de contrasenya" + FORGOT_EMAIL_BODY: "

    Restabliment de contrasenya

    Benvolgut/da %1$s,

    S'ha fet una petició a %4$s per a restablir la contrasenya.


    Fes clic aquí per a restablir la contrasenya

    Altrament, copia el següent URL al teu navegador:

    %2$s


    Atentament,

    %3$s

    " + MANAGE_PAGES: "Gestiona pàgines" + CONFIGURATION: "Configuració" + PAGES: "Pàgines" + PLUGINS: "Plugins" + PLUGIN: "Plugin" + THEMES: "Temes" + LOGOUT: "Tanca sessió" + BACK: "Enrere" + ADD_PAGE: "Afegeix pàgina" + ADD_MODULAR: "Afegeix modular" + MOVE: "Mou" + DELETE: "Esborra" + SAVE: "Desa" + NORMAL: "Normal" + EXPERT: "Expert" + EXPAND_ALL: "Expandeix tot" + COLLAPSE_ALL: "Col·lapsa tot" + ERROR: "Error" + CLOSE: "Tanca" + CANCEL: "Cancel·la" + CONTINUE: "Continua" + MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_TITLE: "Confirmació requerida" + MODAL_CHANGED_DETECTED_TITLE: "Canvis detectats" + MODAL_CHANGED_DETECTED_DESC: "Tens canvis no desats. Estàs segur que vols sortir sense desar?" + MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_TITLE: "Confirmació requerida" + MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_DESC: "Estàs segur que vols eliminar aquest fitxer? Aquesta acció no es pot desfer." + ADD_FILTERS: "Afegeix filtres" + SEARCH_PAGES: "Cerca pàgines" + VERSION: "Versió" + WAS_MADE_WITH: "Es va fer amb" + BY: "Per" + UPDATE_THEME: "Actualitza tema" + UPDATE_PLUGIN: "Actualitza plugin" + OF_THIS_THEME_IS_NOW_AVAILABLE: "d'aquest tema està disponible" + OF_THIS_PLUGIN_IS_NOW_AVAILABLE: "d'aquest plugin està disponible" + AUTHOR: "Autor/a" + HOMEPAGE: "Pàgina d'inici" + DEMO: "Demo" + BUG_TRACKER: "Rastrejador d'errors" + KEYWORDS: "Paraules clau" + LICENSE: "Llicència" + DESCRIPTION: "Descripció" + README: "Llegiu-me" + REMOVE_THEME: "Elimina tema" + INSTALL_THEME: "Instal·la tema" + THEME: "Tema" + BACK_TO_THEMES: "Torna a Temes" + BACK_TO_PLUGINS: "Torna a Plugins" + CHECK_FOR_UPDATES: "Cerca actualitzacions" + ADD: "Afegeix" + CLEAR_CACHE: "Neteja la memòria cache" + CLEAR_CACHE_ALL_CACHE: "Tota la cache" + CLEAR_CACHE_ASSETS_ONLY: "Només assets" + CLEAR_CACHE_IMAGES_ONLY: "Només imatges" + CLEAR_CACHE_CACHE_ONLY: "Només cache" + CLEAR_CACHE_TMP_ONLY: "Només tmp" + DASHBOARD: "Panell de control" + UPDATES_AVAILABLE: "Hi ha actualizacions disponibles" + DAYS: "Dies" + UPDATE: "Actualitza" + BACKUP: "Còpia de seguretat" + STATISTICS: "Estadístiques" + TODAY: "Avui" + WEEK: "Setmana" + MONTH: "Mes" + LATEST_PAGE_UPDATES: "Últimes pàgines actualitzades" + MAINTENANCE: "Manteniment" + UPDATED: "Actualitzat" + MON: "Dl." + TUE: "Dt." + WED: "Dc." + THU: "Dj." + FRI: "Dv." + SAT: "Ds." + SUN: "Dg." + COPY: "Copia" + EDIT: "Edita" + CREATE: "Crea" + GRAV_ADMIN: "Administració Grav" + GRAV_OFFICIAL_PLUGIN: "Plugin oficial de Grav" + GRAV_OFFICIAL_THEME: "Tema oficial de Grav" + PLUGIN_SYMBOLICALLY_LINKED: "Aquest plugin està lligat simbòlicament. Les actualitzacions no seran detectades." + THEME_SYMBOLICALLY_LINKED: "Aquest tema està lligat simbòlicament. Les actualitzacions no seran detectades" + REMOVE_PLUGIN: "Elimina plugin" + INSTALL_PLUGIN: "Instal·la plugin" + AVAILABLE: "Disponible" + INSTALLED: "Instal·lat" + INSTALL: "Instal·la" + ACTIVE_THEME: "Tema actiu" + SWITCHING_TO: "Canviant a" + SWITCHING_TO_DESCRIPTION: "Al canviar a un tema diferent, no es garanteix que tots els estils de pàgina siguin compatibles, potencialment, pot haver-hi errors al intentar carregar aquestes pàgines." + SWITCHING_TO_CONFIRMATION: "Vols continuar i canviar de tema" + CREATE_NEW_USER: "Crea nou usuari" + REMOVE_USER: "Elimina usuari" + ACCESS_DENIED: "Accés denegat" + ACCOUNT_NOT_ADMIN: "el teu compte no té permisos d'administrador" + PHP_INFO: "Informació PHP" + INSTALLER: "Instal·lador" + AVAILABLE_THEMES: "Temes disponibles" + AVAILABLE_PLUGINS: "Plugins disponibles" + INSTALLED_THEMES: "Temes instal·lats" + INSTALLED_PLUGINS: "Plugins instal·lats" + BROWSE_ERROR_LOGS: "Examina registres d'errors" + SITE: "Lloc web" + INFO: "Info" + SYSTEM: "Sistema" + USER: "Usuari" + ADD_ACCOUNT: "Afegeix compte" + SWITCH_LANGUAGE: "Canvia l'idioma" + SUCCESSFULLY_ENABLED_PLUGIN: "El plugin s'ha activat correctament" + SUCCESSFULLY_DISABLED_PLUGIN: "El plugin s'ha desactivat correctament" + SUCCESSFULLY_CHANGED_THEME: "S'ha canviat el tema per defecte correctament" + INSTALLATION_FAILED: "La instal·lació ha fallat" + INSTALLATION_SUCCESSFUL: "Instal·lació satisfactòria" + UNINSTALL_FAILED: "Desinstal·lació fallida" + UNINSTALL_SUCCESSFUL: "Desinstal·lació satisfactòria" + SUCCESSFULLY_SAVED: "Desat satisfactòriament" + SUCCESSFULLY_COPIED: "Copiat satisfactòriament" + REORDERING_WAS_SUCCESSFUL: "Reordenació satisfactòria" + SUCCESSFULLY_DELETED: "Eliminat satisfactòriament" + SUCCESSFULLY_SWITCHED_LANGUAGE: "Idioma canviat satisfactòriament" + INSUFFICIENT_PERMISSIONS_FOR_TASK: "No tens permisos suficients per a la tasca" + CACHE_CLEARED: "Memòria cache esborrada" + METHOD: "Mètode" + ERROR_CLEARING_CACHE: "Error al esborrar cache" + AN_ERROR_OCCURRED: "S'ha produït un error" + YOUR_BACKUP_IS_READY_FOR_DOWNLOAD: "La teva còpia de seguretat està llesta per a descarregar" + DOWNLOAD_BACKUP: "Descarrega còpia de seguretat" + PAGES_FILTERED: "Pàgines filtrades" + NO_PAGE_FOUND: "No s'han trobat pàgines" + INVALID_PARAMETERS: "Els paràmetres són invàlids" + NO_FILES_SENT: "No s'han enviat fitxers" + EXCEEDED_FILESIZE_LIMIT: "S'ha excedit el límit de tamany de fitxer de la configuració de PHP" + UNKNOWN_ERRORS: "Hi ha hagut errors desconeguts" + EXCEEDED_GRAV_FILESIZE_LIMIT: "S'ha excedit el límit de tamany de fitxer de la configuració de Grav" + UNSUPPORTED_FILE_TYPE: "Tipus de fitxer no suportat" + FAILED_TO_MOVE_UPLOADED_FILE: "S'ha fallat al moure el fitxer carregat." + FILE_UPLOADED_SUCCESSFULLY: "S'ha carregat el fitxer amb èxit" + FILE_DELETED: "S'ha esborrat el fitxer" + FILE_COULD_NOT_BE_DELETED: "No s'ha pogut esborrar el fitxer" + FILE_NOT_FOUND: "No s'ha trobat el fitxer" + NO_FILE_FOUND: "No s'han trobat fitxers" + GRAV_WAS_SUCCESSFULLY_UPDATED_TO: "Grav ha estat actualitzat amb èxit a" + GRAV_UPDATE_FAILED: "Ha fallat l'actualització de Grav" + EVERYTHING_UPDATED: "Tot està actualitzat" + UPDATES_FAILED: "Han fallat les actualitzacions" + AVATAR_BY: "Avatar per" + LAST_BACKUP: "Última còpia de seguretat" + FULL_NAME: "Nom complet" + USERNAME: "Nom d'usuari" + EMAIL: "Email" + USERNAME_EMAIL: "Nom d'usuari o correu electrònic" + PASSWORD: "Contrasenya" + PASSWORD_CONFIRM: "Confirma contrasenya" + TITLE: "Títol" + LANGUAGE: "Llengua" + ACCOUNT: "Compte d'usuari" + EMAIL_VALIDATION_MESSAGE: "Ha de ser una adreça de correu electrònic vàl·lida" + PASSWORD_VALIDATION_MESSAGE: "La contrasenya ha de contenir almenys un número i una lletra majúscula i minúscula, i almenys 8 o més caràcters" + LANGUAGE_HELP: "Estableix la llengua preferida" + MEDIA: "Mèdia" + DEFAULTS: "Per defecte" + SITE_TITLE: "Títol del lloc" + SITE_TITLE_PLACEHOLDER: "Títol a tot el lloc" + SITE_TITLE_HELP: "Títol per defecte pel teu lloc, sovint utilitzat en els temes" + SITE_DEFAULT_LANG: "Llenguatge per defecte" + SITE_DEFAULT_LANG_PLACEHOLDER: "Llenguatge per defecte per a ser utilitzat per l'etiqueta del tema " + SITE_DEFAULT_LANG_HELP: "Llenguatge per defecte per a ser utilitzat per l'etiqueta del tema " + DEFAULT_AUTHOR: "Autor/a per defecte" + DEFAULT_AUTHOR_HELP: "Un nom d'autor/a per defecte, algunes vegades utilitzat en temes o contingut de les pàgines" + DEFAULT_EMAIL: "Email per defecte" + DEFAULT_EMAIL_HELP: "Un correu electrònic per referenciar en temes o pàgines" + TAXONOMY_TYPES: "Tipus de taxonomia" + TAXONOMY_TYPES_HELP: "Els tipus de taxonomia han de definir-se aquí si es desitja utilitzar-les en pàgines" + PAGE_SUMMARY: "Resum de pàgina" + ENABLED: "Habilitat" + ENABLED_HELP: "Habilita resum de pàgina (el resum retorna el mateix que el contingut de la pàgina)" + 'YES': "Sí" + 'NO': "No" + SUMMARY_SIZE: "Mida del resum" + SUMMARY_SIZE_HELP: "La quantitat de caràcters d'una pàgina a utilitzar com a resum del contingut" + FORMAT: "Format" + FORMAT_HELP: "curt = utilitza la primera ocurrència del delimitador o mida; llarg = s'ignorarà el delimitador del resum" + SHORT: "Curt" + LONG: "Llarg" + DELIMITER: "Delimitador" + DELIMITER_HELP: "El delimitador de resum (per defecte '===')" + METADATA: "Metadades" + METADATA_HELP: "Valors de metadades per defecte que es mostraran a cada pàgina excepte si es sobreescriuen a la pàgina" + NAME: "Nom" + CONTENT: "Contingut" + REDIRECTS_AND_ROUTES: "Redireccions i rutes" + CUSTOM_REDIRECTS: "Redireccions personalitzades" + CUSTOM_REDIRECTS_HELP: "rutes per redirigir a altres pàgines. Substitució de Regex estàndard és vàl·lida" + CUSTOM_REDIRECTS_PLACEHOLDER_KEY: "/el/teu/àlies" + CUSTOM_REDIRECTS_PLACEHOLDER_VALUE: "/la/teva/redirecció" + CUSTOM_ROUTES: "Rutes personalitzades" + CUSTOM_ROUTES_HELP: "rutes a àlies a altres pàgines. Substitució de Regex estàndard és vàl·lida" + CUSTOM_ROUTES_PLACEHOLDER_KEY: "/el/teu/àlies" + CUSTOM_ROUTES_PLACEHOLDER_VALUE: "/la/teva/ruta" + FILE_STREAMS: "Streams de fitxers" + DEFAULT: "Per defecte" + PAGE_MEDIA: "Contingut multimèdia de la pàgina" + OPTIONS: "Opcions" + PUBLISHED: "Publicat" + PUBLISHED_HELP: 'Per defect, una pàgina es publica excepte que estableixis explícitament ''published'': false o posant una publish_date al futur o una unpublish_date al passat' + DATE: "Data" + DATE_HELP: "La variable data permet definir específicament una data associada a aquesta pàgina." + PUBLISHED_DATE: "Data de publicació" + PUBLISHED_DATE_HELP: "Pots proporcionar una data per provocar automàticament la publicació." + UNPUBLISHED_DATE: "Data de despublicació" + UNPUBLISHED_DATE_HELP: "Pots proporcionar una data per provocar automàticament la despublicació." + ROBOTS: "Robots" + TAXONOMIES: "Taxonomies" + TAXONOMY: "Taxonomia" + ADVANCED: "Avançat" + SETTINGS: "Configuració" + FOLDER_NUMERIC_PREFIX: "Prefix numèric carpeta" + FOLDER_NUMERIC_PREFIX_HELP: "Prefix numèric que proporciona ordenació manual i implica la visibilitat" + FOLDER_NAME: "Nom de la carpeta" + FOLDER_NAME_HELP: "El nom de carpeta que s'emmagatzemarà al sistema de fitxers per a aquesta pàgina" + PARENT: "Pare" + DEFAULT_OPTION_ROOT: "-Root-" + DEFAULT_OPTION_SELECT: "- selecciona -" + DISPLAY_TEMPLATE: "Plantilla a mostrar" + DISPLAY_TEMPLATE_HELP: "El tipus de pàgina que es tradueix a la plantilla de Twig en què es renderitza la pàgina" + BODY_CLASSES: "Classes del Body" + ORDERING: "Ordenació" + PAGE_ORDER: "Ordre de pàgines" + OVERRIDES: "Sobreescriu" + MENU: "Menú" + MENU_HELP: "El text a utilitzar en un menú. Si no s'estableix, s'utilitzarà el Títol." + SLUG: "Slug" + SLUG_HELP: "La variable slug permet definir específicament la part de l'URL que correspon a la pàgina" + SLUG_VALIDATE_MESSAGE: "L'slug ha de contenir només caràcters alfanumèrics en minúscules i guions" + PROCESS: "Processa" + PROCESS_HELP: "Control de com es processen les pàgines. Configurable per a pàgina enlloc de globalment" + DEFAULT_CHILD_TYPE: "Tipus de fill per defecte" + USE_GLOBAL: "Ús global" + ROUTABLE: "Accessible" + ROUTABLE_HELP: "Si aquesta pàgina és accessible des d'una URL" + CACHING: "Caching" + VISIBLE: "Visible" + VISIBLE_HELP: "Determina si una pàgina és visible en la navegació." + DISABLED: "Deshabilitat" + ITEMS: "Ítems" + ORDER_BY: "Ordena per" + ORDER: "Ordena" + FOLDER: "Carpeta" + ASCENDING: "Ascendent" + DESCENDING: "Descendent" + ADD_MODULAR_CONTENT: "Afegeix contingut modular" + PAGE_TITLE: "Títol de pàgina" + PAGE_TITLE_HELP: "El títol de la pàgina" + PAGE: "Pàgina" + MODULAR_TEMPLATE: "Plantilla modular" + FRONTMATTER: "Frontmatter" + FILENAME: "Nom de fitxer" + PARENT_PAGE: "Pàgina pare" + HOME_PAGE: "Pàgina d'inici" + HOME_PAGE_HELP: "La pàgina que utilitzarà Grav com a destinació per defecte" + DEFAULT_THEME: "Tema per defecte" + DEFAULT_THEME_HELP: "Estableix el tema per defecte que utilitzarà Grav (per defecte és Antimatter)" + TIMEZONE: "Zona horària" + TIMEZONE_HELP: "Sobreescriu la zona horària del servidor" + SHORT_DATE_FORMAT: "Format de data curt" + SHORT_DATE_FORMAT_HELP: "Estableix el format de data curt que poden utilitzar els temes" + LONG_DATE_FORMAT: "Format de data llarg" + LONG_DATE_FORMAT_HELP: "Estableix el format de data llarg que poden utilitzar els temes" + DEFAULT_ORDERING: "Ordre per defecte" + DEFAULT_ORDERING_HELP: "Les pàgines de la llista seran generades utilitzant aquest ordre excepte que se sobreescrigui" + DEFAULT_ORDERING_DEFAULT: "Per defecte - basat en el nom de la carpeta" + DEFAULT_ORDERING_FOLDER: "Carpeta - basat en el nom de carpeta sense prefix" + DEFAULT_ORDERING_TITLE: "Títol - basat en el camp de títol de la capçalera" + DEFAULT_ORDERING_DATE: "Data - basat en el camp data de la capçalera" + DEFAULT_ORDER_DIRECTION: "Direcció d'ordre per defecte" + DEFAULT_ORDER_DIRECTION_HELP: "La direcció de les pàgines en una llista" + DEFAULT_PAGE_COUNT: "Compte de pàgina per defecte" + DEFAULT_PAGE_COUNT_HELP: "Nombre màxim de compte de pàgines en una llista" + DATE_BASED_PUBLISHING: "Publicació basada en la data" + DATE_BASED_PUBLISHING_HELP: "(Des)publicar automàticament posts basant-se en la seva data" + EVENTS: "Esdeveniments" + EVENTS_HELP: "Habilita o inhabilita esdeveniments concrets. Deshabilitant-los pot trencar plugins" + REDIRECT_DEFAULT_ROUTE: "Ruta de redirecció per defecte" + REDIRECT_DEFAULT_ROUTE_HELP: "Redirigir automàticament a la ruta per defecte d'una pàgina" + LANGUAGES: "Idiomes" + SUPPORTED: "Suportat" + SUPPORTED_HELP: "Llista separada per comes de codis d'idioma de 2 lletres (per exemple 'en,fr,de')" + TRANSLATIONS_ENABLED: "Traduccions habilitades" + TRANSLATIONS_ENABLED_HELP: "Suport a traduccions a Grav, plugins i extensions" + TRANSLATIONS_FALLBACK: "Fallback de traduccions" + TRANSLATIONS_FALLBACK_HELP: "Fallback en traduccions suportades si l'idioma actiu no existeix" + ACTIVE_LANGUAGE_IN_SESSION: "Idioma actiu a la sessió" + ACTIVE_LANGUAGE_IN_SESSION_HELP: "Emmagatzema l'idioma actiu a la sessió" + HTTP_HEADERS: "Capçaleres HTTP" + EXPIRES: "Caduca" + EXPIRES_HELP: "Estableix la capçalera d'expiració. El valor és en segons." + LAST_MODIFIED: "Darrera modificació" + LAST_MODIFIED_HELP: "Estableix la capçalera de darrera modificació que pot optimitzar el proxy i la cache del navegador" + ETAG: "ETag" + ETAG_HELP: "Estableix la capçalera d'etag per ajudar a identificar quan una pàgina ha estat modificada" + VARY_ACCEPT_ENCODING: "Variar accept encoding" + VARY_ACCEPT_ENCODING_HELP: 'Estableix la capçalera ''Vary: Accept Encoding'' per ajudar amb el proxy i la cache CDN' + MARKDOWN_EXTRA_HELP: "Habilita suport per defecte per a Markdown Extra - https://michelf.ca/projects/php-markdown/extra/" + AUTO_LINE_BREAKS: "Salts de línia automàtics" + AUTO_LINE_BREAKS_HELP: "Habilita el suport per a salts de línia automàtics a Markdown" + AUTO_URL_LINKS: "Enllaços URL automàtics" + AUTO_URL_LINKS_HELP: "Habilita l'autoconversió d'URLs a hyperlinks HTML" + ESCAPE_MARKUP: "Escape markup" + ESCAPE_MARKUP_HELP: "Escape markup tags en entitats HTML" + CACHING_HELP: "Interruptor ON/OFF global per habilitar/deshabilitar cache de Grav" + CACHE_CHECK_METHOD: "Mètode de verificació de cache" + CACHE_CHECK_METHOD_HELP: "Seleccionar el mètode que utilitza Grav per comprovar si s'han modificat arxius de pàgina." + CACHE_DRIVER: "Contolador de cache" + CACHE_DRIVER_HELP: "Selecciona quin controlador de cache de Grav cal usar. 'Auto Detect' intenta trobar el millor per a tu" + CACHE_PREFIX: "Prefix de cache" + CACHE_PREFIX_HELP: "Un identificador per part de la clau de Grav. No la canviïs excepte que sàpigues el que estàs fent." + CACHE_PREFIX_PLACEHOLDER: "Derivat de l'URL base (sobreescriu introduint strings aleatòris)" + LIFETIME: "Cicle de vida" + LIFETIME_HELP: "Defineix el cicle de vida de la cache en segons. 0 = infinit" + GZIP_COMPRESSION: "Compressió gzip" + GZIP_COMPRESSION_HELP: "Habilita la compressió GZip de la pàgina de Grav per augmentar el rendiment." + TWIG_TEMPLATING: "Plantilles de Twig" + TWIG_CACHING: "Cache de Twig" + TWIG_CACHING_HELP: "Controla el mecanisme de cache de Twig. Deixa'l habilitat per a millor rendiment." + TWIG_DEBUG: "Depuració de Twig" + TWIG_DEBUG_HELP: "Permet l'opció de no carregar l'extensió de depuració de Twig" + DETECT_CHANGES: "Detectar canvis" + DETECT_CHANGES_HELP: "Twig recompilarà automàticament la cache de Twig si detecta canvis a les plantilles de Twig" + AUTOESCAPE_VARIABLES: "Variables d'autoescape" + AUTOESCAPE_VARIABLES_HELP: "Autoescapa totes les variables. Això probablement trencarà el teu lloc" + ASSETS: "Assets" + CSS_PIPELINE: "CSS pipeline" + CSS_PIPELINE_HELP: "El CSS pipeline és l'unificació de diversos recursos CSS en un sol fitxer" + CSS_PIPELINE_INCLUDE_EXTERNALS: "Inclou fitxers externs en el CSS pipeline" + CSS_PIPELINE_INCLUDE_EXTERNALS_HELP: "A vegades, algunes URLs externes tenen referències relatives de fitxer i no s'hi hauria de fer pipelining" + CSS_PIPELINE_BEFORE_EXCLUDES: "Processar pimer el CSS pipeline" + CSS_PIPELINE_BEFORE_EXCLUDES_HELP: "Intrepreta el CSS pipeline abans de qualsevol altra referència CSS que no estigui inclosa" + CSS_MINIFY: "Minifica CSS" + CSS_MINIFY_HELP: "Minifica el CSS durant el pipelining" + CSS_MINIFY_WINDOWS_OVERRIDE: "Sobreesciu la minificació de CSS a Windows" + CSS_MINIFY_WINDOWS_OVERRIDE_HELP: "Sobreescriu la minificació en plataformes Windows. Fals per defecte degut a ThreadStackSize" + CSS_REWRITE: "Reescriptura CSS" + CSS_REWRITE_HELP: "Reescriu qualsevol URL relativa de CSS durant el pipelining" + JAVASCRIPT_PIPELINE: "JavaScript pipeline" + JAVASCRIPT_PIPELINE_HELP: "El JS pipeline és l'unificació de diversos recursos JS en un sol fitxer" + JAVASCRIPT_PIPELINE_INCLUDE_EXTERNALS: "Inclou fitxers externs en el JS pipeline" + JAVASCRIPT_PIPELINE_INCLUDE_EXTERNALS_HELP: "A vegades, les URLs externes tenen referències d'arxiu i no s'hi hauria de fer pipelining" + JAVASCRIPT_PIPELINE_BEFORE_EXCLUDES: "Interpreta primer el JS pipeline" + JAVASCRIPT_PIPELINE_BEFORE_EXCLUDES_HELP: "Interpreta el JS pipeline abans de qualsevol altra referència JS que no estigui inclosa" + JAVASCRIPT_MINIFY: "Minificació JavaScript" + JAVASCRIPT_MINIFY_HELP: "Minifica el JS durant el pipelining" + ENABLED_TIMESTAMPS_ON_ASSETS: "Habilita les marques de temps als assets" + ENABLED_TIMESTAMPS_ON_ASSETS_HELP: "Habilita les marques de temps a assets" + COLLECTIONS: "Col·leccions" + ERROR_HANDLER: "Controlador d'errors" + DISPLAY_ERRORS: "Mostra errors" + DISPLAY_ERRORS_HELP: "Mostra pàgina d'error full backstrace-style" + LOG_ERRORS: "Registre d'errors" + LOG_ERRORS_HELP: "Registre d'errors a la carpeta /logs" + DEBUGGER: "Depurador" + DEBUGGER_HELP: "Habilita depurador de Grav i les configuracions següents" + DEBUG_TWIG: "Depuració de Twig" + DEBUG_TWIG_HELP: "Habilita la depuració de plantilles de Twig" + SHUTDOWN_CLOSE_CONNECTION: "Al apagar tanca la connexió" + SHUTDOWN_CLOSE_CONNECTION_HELP: "Tanca la connexió abans de cridar onShutdown(). False per a la depuració" + DEFAULT_IMAGE_QUALITY: "Qualitat d'imatge per defecte" + DEFAULT_IMAGE_QUALITY_HELP: "Qualitat d'imatge per defecte per a ser utilitzada quan es remostri o es guardi a cache les imatges (85%)" + CACHE_ALL: "Guardar totes les imatges a cache" + CACHE_ALL_HELP: "Guarda totes les imatges al sistema cache de Grav fins i tot si no tenen cap manipulació de mèdia" + IMAGES_DEBUG: "Marca d'aigua de depuració" + IMAGES_DEBUG_HELP: "Mostra un overlay sobre les imatges indicant la profunditat de píxels quan es treballa amb retina, per exemple" + UPLOAD_LIMIT: "Límit de tamany de fitxer" + UPLOAD_LIMIT_HELP: "Defineix el tamany màxim de càrrega en bytes (0 = il·limitat)" + ENABLE_MEDIA_TIMESTAMP: "Permet timestamps en fitxers multimèdia" + ENABLE_MEDIA_TIMESTAMP_HELP: "Afegeix un timestamp basat en la data d'última modificació a cada element multimèdia" + SESSION: "Sessió" + SESSION_ENABLED_HELP: "Habilita suport de sessions a Grav" + TIMEOUT: "Temps d'espera" + TIMEOUT_HELP: "Estableix el temps d'espera de la sessió en segons" + SESSION_NAME_HELP: "Un identificador usat per formar el nom de la galeta de sessió" + ABSOLUTE_URLS: "URLs absolutes" + ABSOLUTE_URLS_HELP: "URLs absolutes o relatives per a 'base_url'" + PARAMETER_SEPARATOR: "Separador de paràmetres" + PARAMETER_SEPARATOR_HELP: "Separador per a paràmetres passats que es poden canviar d'Apache a Windows" + TASK_COMPLETED: "Tasca completada" + EVERYTHING_UP_TO_DATE: "Tot està actualitzat" + UPDATES_ARE_AVAILABLE: "hi ha actualitzacions disponibles" + IS_AVAILABLE_FOR_UPDATE: "està disponible per a l'actualització" + IS_NOW_AVAILABLE: "ja està disponible" + CURRENT: "Actual" + UPDATE_GRAV_NOW: "Actualitza Grav ara" + GRAV_SYMBOLICALLY_LINKED: "Grav està lligat simbòlicament. Les actualitzacions no estaran disponibles" + UPDATING_PLEASE_WAIT: "Actualitzant... descarregant, espera sisplau" + OF_THIS: "d'aquest/a" + OF_YOUR: "del teu" + HAVE_AN_UPDATE_AVAILABLE: "té disponible una actualització" + SAVE_AS: "Desa com a" + MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_DESC: "Esteu segur que voleu suprimir aquesta pàgina i tots els seus fills? Si la pàgina es tradueix en altres llengües, les traduccions es mantindran i han de ser esborrades per separat. En cas contrari la carpeta de la pàgina serà eliminada juntament amb les seves subpàgines. Aquesta acció no es pot desfer." + AND: "i" + UPDATE_AVAILABLE: "Actualització disponible" + METADATA_KEY: "Clau (p. ex. 'paraules clau')" + METADATA_VALUE: "Valor (per exemple, \"Blog, Grav\")" + USERNAME_HELP: "El nom d'usuari ha de tenir entre 3 i 16 caràcters, incloent minúscules, números, guions i guions baixos. Lletres majúscules, espais i caràcters especials no estan permesos" + FULLY_UPDATED: "Completament actualitzat" + SAVE_LOCATION: "Desa a la ubicació" + PAGE_FILE: "Plantilla de pàgina" + PAGE_FILE_HELP: "Nom d'arxiu de la plantilla de pàgina i plantilla de visualització per defecte" + NO_USER_ACCOUNTS: "No s'han trobat comptes d'usuari, sisplau crea'n una..." + REDIRECT_TRAILING_SLASH: "Redirigeix barra final" + REDIRECT_TRAILING_SLASH_HELP: "Realitza una redirecció 301 en lloc de manteniment transparent de barra final." + DEFAULT_DATE_FORMAT: "Format de data de pàgina" + DEFAULT_DATE_FORMAT_HELP: Format de data de pàgina utilitzat per Grav. Per defecte, Grav intenta endivinar el format de data, tot i això pots especificar un format utilitzant la sintaxi de data de PHP (p.e., Y-m-d H:i) + DEFAULT_DATE_FORMAT_PLACEHOLDER: "Endevina automàticament" + IGNORE_FILES: "Ignora fitxers" + IGNORE_FILES_HELP: "Arxius específics a ignorar al processar pàgines" + IGNORE_FOLDERS: "Ignora carpetes" + IGNORE_FOLDERS_HELP: "Carpetes específiques a ignorar al processar pàgines" + HTTP_ACCEPT_LANGUAGE: "Estableix la llengua a partir del navegador" + HTTP_ACCEPT_LANGUAGE_HELP: "Pots optar per intentar establir la llengua basant-se en l'etiqueta de la capçalera 'http_accept_language' en el navegador" + OVERRIDE_LOCALE: "Sobreescriu la configuració local" + OVERRIDE_LOCALE_HELP: "Sobreescriu la configuració local en PHP basant-se en la llengua actual" + REDIRECT: "Redirecció de pàgina" + REDIRECT_HELP: "Escriu una ruta de pàgina o URL externa per aqueta pàgina a redirigir a per exemple, '/alguna/ruta' o 'https://algunlloc.com'" + PLUGIN_STATUS: "Estat del plugin" + INCLUDE_DEFAULT_LANG: "Inclou llengua predeterminada" + INCLUDE_DEFAULT_LANG_HELP: "Això sobreposarà totes les URLs amb la llengua per defecte. Per exemple, 'ca/blog/el-meu-post'" + ALLOW_URL_TAXONOMY_FILTERS: "Filtres de taxonomia d'URL" + ALLOW_URL_TAXONOMY_FILTERS_HELP: "Col·lecions basades en pàgines que et permeten filtrar per '/taxonomia:valor'." + REDIRECT_DEFAULT_CODE: "Codi de redirecció per defecte" + REDIRECT_DEFAULT_CODE_HELP: "El codi d'estat HTTP per utilitzar en redireccions" + IGNORE_HIDDEN: "Ignora ocults" + IGNORE_HIDDEN_HELP: "Ignora tots els fitxers i carpetes que comencin amb un punt" + WRAPPED_SITE: "Lloc encapsulat" + WRAPPED_SITE_HELP: "Per a que els temes/plugins sàpiguen si Grav està encapsulat en una altra plataforma" + FALLBACK_TYPES: "Tipus de fallback permesos" + FALLBACK_TYPES_HELP: "Tipus de fitxers permesos que es poden trobar si s'accedeix per la ruta de la pàgina. Per defecte, qualsevol tipus de mèdia compatible." + INLINE_TYPES: "Tipus de fallback en línia" + INLINE_TYPES_HELP: "Una llista de tipus d'arxius que han de ser mostrats en línia enlloc de descarregats" + APPEND_URL_EXT: "Afegeix extensió de direcció URL" + APPEND_URL_EXT_HELP: "Afegirà una extensió personalitzarà a l'URL de la pàgina. Tingues en compte que això farà que Grav busqui la plantilla '