From 1602f2c8703667f85f89c37b8b0aca4873c52121 Mon Sep 17 00:00:00 2001 From: Flavio Copes Date: Sat, 16 Jan 2016 16:24:38 +0100 Subject: [PATCH] Fix #396 Check frontmatter for validity prior to saving If saving in Expert mode and the frontmatter field contained invalid yaml, the page content was changed to the error description. Instead, avoid saving the page and return an error in the Admin interface. --- classes/controller.php | 24 ++++++++++++++++++++++++ languages/en.yaml | 1 + 2 files changed, 25 insertions(+) diff --git a/classes/controller.php b/classes/controller.php index 9c4de280..9f4f4b56 100644 --- a/classes/controller.php +++ b/classes/controller.php @@ -21,6 +21,7 @@ use Grav\Common\Markdown\ParsedownExtra; use RocketTheme\Toolbox\Event\Event; use RocketTheme\Toolbox\File\File; use RocketTheme\Toolbox\File\JsonFile; +use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Yaml; class AdminController @@ -1055,6 +1056,24 @@ class AdminController return $obj; } + 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; + } + /** * Handles form and saves the input data if its valid. * @@ -1079,6 +1098,11 @@ class AdminController $route = !isset($data['route']) ? dirname($this->admin->route) : $data['route']; $obj = $this->admin->page(true); + if (isset($data['frontmatter']) && !$this->checkValidFrontmatter($data['frontmatter'])) { + $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_FRONTMATTER_COULD_NOT_SAVE'), 'error'); + return false; + } + //Handle system.home.hide_in_urls $hide_home_route = $config->get('system.home.hide_in_urls', false); if ($hide_home_route) { diff --git a/languages/en.yaml b/languages/en.yaml index 91646f93..5d76495b 100644 --- a/languages/en.yaml +++ b/languages/en.yaml @@ -474,3 +474,4 @@ PLUGIN_ADMIN: SESSION_HTTPONLY_HELP: "If true, indicates that cookies should be used only over HTTP, and JavaScript modification is not allowed" REVERSE_PROXY: "Reverse Proxy" REVERSE_PROXY_HELP: "Enable this if you are behind a reverse proxy and you are having trouble with URLs containing incorrect ports" + INVALID_FRONTMATTER_COULD_NOT_SAVE: "Invalid frontmatter, could not save" \ No newline at end of file