/** * @param string $in Filename without path or extension. * @param string $out Full path to the file to be written. * @return bool True if the output file was saved. */ public function compileFile($in, $out = null) { $gantry = Gantry::instance(); /** @var UniformResourceLocator $locator */ $locator = $gantry['locator']; if (!$out) { $out = $locator->findResource($this->getCssUrl($in), true, true); } $paths = $locator->mergeResources($this->paths); // Set the lookup paths. $this->compiler->setBasePath($out); $this->compiler->setImportPaths($paths); $this->compiler->setFormatter('scss_formatter_nested'); // Run the compiler. $this->compiler->setVariables($this->getVariables()); $scss = '@import "' . $in . '.scss"'; $css = $this->compiler->compile($scss); if (strpos($css, $scss) === 0) { $css = '/* ' . $scss . ' */'; } $file = File::instance($out); // Attempt to lock the file for writing. $file->lock(false); //TODO: Better way to handle double writing files at same time. if ($file->locked() === false) { // File was already locked by another process. return false; } $file->save($css); $file->unlock(); return true; }
/** * @param string $in Filename without path or extension. * @return bool True if the output file was saved. */ public function compileFile($in) { $gantry = Gantry::instance(); /** @var UniformResourceLocator $locator */ $locator = $gantry['locator']; $out = $this->getCssUrl($in); $path = $locator->findResource($out, true, true); $paths = $locator->mergeResources($this->paths); // Set the lookup paths. $this->compiler->setBasePath($path); $this->compiler->setImportDir($paths); $this->compiler->setFormatter('lessjs'); // Run the compiler. $this->compiler->setVariables($this->getVariables()); $css = $this->compiler->compileFile($in . '.less"'); $file = File::instance($path); // Attempt to lock the file for writing. $file->lock(false); //TODO: Better way to handle double writing files at same time. if ($file->locked() === false) { // File was already locked by another process. return false; } $file->save($css); $file->unlock(); $this->createMeta($out, md5($css)); return true; }
/** * Given a data file route, return the YAML content already parsed */ private function getDataFromFilename($fileRoute) { //Single item details $fileInstance = File::instance(DATA_DIR . 'comments/' . $fileRoute); if (!$fileInstance->content()) { //Item not found return; } return Yaml::parse($fileInstance->content()); }
/** * @param string $in Filename without path or extension. * @return bool True if the output file was saved. */ public function compileFile($in) { // Buy some extra time as compilation may take a lot of time in shared environments. @set_time_limit(30); ob_start(); $gantry = Gantry::instance(); /** @var UniformResourceLocator $locator */ $locator = $gantry['locator']; $out = $this->getCssUrl($in); $path = $locator->findResource($out, true, true); $file = File::instance($path); // 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, lets avoid compiling the same file twice. return false; } // Set the lookup paths. $this->compiler->setBasePath($path); $this->compiler->setImportPaths([[$this, 'findImport']]); // Run the compiler. $this->compiler->setVariables($this->getVariables()); $scss = '@import "' . $in . '.scss"'; $css = $this->compiler->compile($scss); if (strpos($css, $scss) === 0) { $css = '/* ' . $scss . ' */'; } $warnings = trim(ob_get_clean()); if ($warnings) { $this->warnings[$in] = explode("\n", $warnings); } if (!$this->production) { $warning = <<<WARN /* GANTRY5 DEVELOPMENT MODE ENABLED. WARNING: This file is automatically generated by Gantry5. Any modifications to this file will be lost! For more information on modifying CSS, please read: http://docs.gantry.org/gantry5/configure/styles http://docs.gantry.org/gantry5/tutorials/adding-a-custom-style-sheet */ WARN; $css = $warning . "\n\n" . $css; } $file->save($css); $file->unlock(); $file->free(); $this->createMeta($out, md5($css)); return true; }
private function getMessages($page = 0) { $itemsPerPage = 5; $lang = $this->grav['language']->getActive(); $filename = DATA_DIR . 'guestbook/' . $this->grav['config']->get('plugins.guestbook.filename'); $file = File::instance($filename); if (!$file->content()) { //Item not found return; } $messages = Yaml::parse($file->content()); $totalAvailable = count($messages); $messages = array_slice($messages, $page * $itemsPerPage, $itemsPerPage); $totalRetrieved = count($messages); return (object) array("messages" => $messages, "page" => $page, "itemsPerPage" => $itemsPerPage, "totalAvailable" => $totalAvailable, "totalRetrieved" => $totalRetrieved); }
/** * Handle form processing instructions. * * @param Event $event */ public function onFormProcessed(Event $event) { $form = $event['form']; $action = $event['action']; $params = $event['params']; $this->process($form); switch ($action) { case 'captcha': // Validate the captcha $query = http_build_query(['secret' => $params['recatpcha_secret'], 'response' => $this->form->value('g-recaptcha-response')]); $url = 'https://www.google.com/recaptcha/api/siteverify?' . $query; $response = json_decode(file_get_contents($url), true); if (!isset($response['success']) || $response['success'] !== true) { $this->grav->fireEvent('onFormValidationError', new Event(['form' => $form, 'message' => $this->grav['language']->translate('PLUGIN_FORM.ERROR_VALIDATING_CAPTCHA')])); $event->stopPropagation(); return; } break; case 'message': $this->form->message = (string) $params; break; case 'redirect': $this->grav->redirect((string) $params); break; case 'reset': if (Utils::isPositive($params)) { $this->form->reset(); } break; case 'display': $route = (string) $params; if (!$route || $route[0] != '/') { /** @var Uri $uri */ $uri = $this->grav['uri']; $route = $uri->route() . ($route ? '/' . $route : ''); } /** @var Twig $twig */ $twig = $this->grav['twig']; $twig->twig_vars['form'] = $form; /** @var Pages $pages */ $pages = $this->grav['pages']; $page = $pages->dispatch($route, true); if (!$page) { throw new \RuntimeException('Display page not found. Please check the page exists.', 400); } unset($this->grav['page']); $this->grav['page'] = $page; break; case 'save': $prefix = !empty($params['fileprefix']) ? $params['fileprefix'] : ''; $format = !empty($params['dateformat']) ? $params['dateformat'] : 'Ymd-His-u'; $ext = !empty($params['extension']) ? '.' . trim($params['extension'], '.') : '.txt'; $filename = !empty($params['filename']) ? $params['filename'] : ''; $operation = !empty($params['operation']) ? $params['operation'] : 'create'; if (!$filename) { $filename = $prefix . $this->udate($format) . $ext; } /** @var Twig $twig */ $twig = $this->grav['twig']; $vars = array('form' => $this->form); $locator = $this->grav['locator']; $path = $locator->findResource('user://data', true); $fullFileName = $path . DS . $this->form->name . DS . $filename; $file = File::instance($fullFileName); if ($operation == 'create') { $body = $twig->processString(!empty($params['body']) ? $params['body'] : '{% include "forms/data.txt.twig" %}', $vars); $file->save($body); } elseif ($operation == 'add') { $vars = $vars['form']->value()->toArray(); foreach ($form->fields as $field) { if (isset($field['process']) && isset($field['process']['ignore']) && $field['process']['ignore']) { unset($vars[$field['name']]); } } if (file_exists($fullFileName)) { $data = Yaml::parse($file->content()); if (count($data) > 0) { array_unshift($data, $vars); } else { $data[] = $vars; } } else { $data[] = $vars; } $file->save(Yaml::dump($data)); } break; } }
/** * 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; } // $reorder = false; $data = $this->post; $language = $data['lang']; if ($language) { $this->grav['session']->admin_lang = $language ?: 'en'; } // /** @var Page\Pages $pages */ $pages = $this->grav['pages']; $uri = $this->grav['uri']; $obj = $this->admin->page($uri->route()); $this->preparePage($obj, false, $language); $file = $obj->file(); if ($file) { $filename = substr($obj->name(), 0, -strlen('.' . $language . '.md')); if (substr($filename, -3, 1) == '.') { if (substr($filename, -2) == substr($language, 0, 2)) { $filename = str_replace(substr($filename, -2), $language, $filename); } } elseif (substr($filename, -6, 1) == '.') { if (substr($filename, -5) == substr($language, 0, 5)) { $filename = str_replace(substr($filename, -5), $language, $filename); } } else { $filename .= '.' . $language; } $path = $obj->path() . DS . $filename . '.md'; $aFile = File::instance($path); $aFile->save(); $aPage = new Page\Page(); $aPage->init(new \SplFileInfo($path), $language . '.md'); $aPage->header($obj->header()); $aPage->rawMarkdown($obj->rawMarkdown()); $aPage->validate(); $aPage->filter(); $aPage->save(); } $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info'); $this->setRedirect('/' . $language . $uri->route()); 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->route); $file = File::instance($filename); $resultRemoveMedia = false; $resultRemoveMediaMeta = true; if ($file->exists()) { $resultRemoveMedia = $file->delete(); $metaFilePath = $filename . '.meta.yaml'; $metaFilePath = str_replace('@3x', '', $metaFilePath); $metaFilePath = str_replace('@2x', '', $metaFilePath); if (is_file($metaFilePath)) { $metaFile = File::instance($metaFilePath); $resultRemoveMediaMeta = $metaFile->delete(); } } if ($resultRemoveMedia && $resultRemoveMediaMeta) { $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.REMOVE_SUCCESSFUL'), 'info'); } else { $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.REMOVE_FAILED'), 'error'); } $this->post = array('_redirect' => 'media'); return true; }
/** * 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(); return $content; }
/** * Save the current page in a different language. Automatically switches to that language. * * @return bool True if the action was performed. */ protected function taskSaveas() { if (!$this->authorizeTask('save', $this->dataPermissions())) { return false; } $data = (array) $this->data; $language = $data['lang']; if ($language) { $this->grav['session']->admin_lang = $language ?: 'en'; } $uri = $this->grav['uri']; $obj = $this->admin->page($uri->route()); $this->preparePage($obj, false, $language); $file = $obj->file(); if ($file) { $filename = $this->determineFilenameIncludingLanguage($obj->name(), $language); $path = $obj->path() . DS . $filename; $aFile = File::instance($path); $aFile->save(); $aPage = new Page(); $aPage->init(new \SplFileInfo($path), $language . '.md'); $aPage->header($obj->header()); $aPage->rawMarkdown($obj->rawMarkdown()); $aPage->validate(); $aPage->filter(); $aPage->save(); $this->grav->fireEvent('onAdminAfterSave', new Event(['page' => $obj])); } $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info'); $this->setRedirect('/' . $language . $uri->route()); return true; }
/** * Set all twig variables for generating output. */ public function onTwigSiteVariables() { $twig = $this->grav['twig']; // Dynamic type support $format = $this->uri->extension(); $ext = '.' . ($format ? $format : 'html') . TWIG_EXT; $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->config->get('plugins.admin.route'), '/'); $twig->twig_vars['base_url_relative'] .= ($twig->twig_vars['base_url_relative'] != '/' ? '/' : '') . $twig->twig_vars['admin_route']; $twig->twig_vars['theme_url'] = '/user/plugins/admin/themes/' . $this->theme; $twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative']; $twig->twig_vars['base_path'] = GRAV_ROOT; $twig->twig_vars['admin'] = $this->admin; switch ($this->template) { case 'dashboard': $twig->twig_vars['popularity'] = $this->popularity; break; case 'pages': $page = $this->admin->page(true); if ($page != null) { $twig->twig_vars['file'] = File::instance($page->filePath()); $twig->twig_vars['media_types'] = str_replace('defaults,', '', implode(',.', array_keys($this->config->get('media')))); } break; } }
public function doSubscribe() { $prefix = !empty($params['fileprefix']) ? $params['fileprefix'] : ''; $format = !empty($params['dateformat']) ? $params['dateformat'] : 'Ymd-His-u'; $ext = !empty($params['extension']) ? '.' . trim($params['extension'], '.') : '.txt'; $filename = !empty($params['filename']) ? $params['filename'] : ''; $operation = !empty($params['operation']) ? $params['operation'] : 'create'; if (!$filename) { $filename = $prefix . $this->udate($format) . $ext; } /** @var Twig $twig */ $twig = $this->grav['twig']; $vars = array('form' => $this->form); $locator = $this->grav['locator']; $path = $locator->findResource('user://data', true); $fullFileName = $path . DS . $this->form->name . DS . $filename; $file = File::instance($fullFileName); if ($operation == 'create') { $body = $twig->processString(!empty($params['body']) ? $params['body'] : '{% include "forms/subscriber.txt.twig" %}', $vars); $file->save($body); } elseif ($operation == 'add') { $vars = $vars['form']->value()->toArray(); foreach ($this->form->fields as $field) { if (isset($field['process']) && isset($field['process']['ignore']) && $field['process']['ignore']) { unset($vars[$field['name']]); } } if (file_exists($fullFileName)) { $data = Yaml::parse($file->content()); if (count($data) > 0) { array_unshift($data, $vars); } else { $data[] = $vars; } } else { $data[] = $vars; } $file->save(Yaml::dump($data)); } $this->setMessage(isset($this->params['success_message']) ? $this->params['success_message'] : 'Thank you!'); }
/** * Saves data to the log file * - creates or append not found errors url, time and HTTP_REFERER * - creates a summary and save it to file */ protected function savelog($url) { $params = $this->config->get('plugins.logerrors'); $filename = !empty($params['filename']) ? trim($params['filename']) : 'notfound.txt'; $folder = !empty($params['folder']) ? trim($params['folder']) : 'logerrors'; $locator = $this->grav['locator']; $path = $locator->findResource('user://data', true); $fullFileName = $path . DS . $folder . DS . $filename; $file = File::instance($fullFileName); $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''; $time = date("Y-m-d h:i:sa"); $vars = array('url' => $url, 'time' => $time, 'referer' => $referer); if (!file_exists($path . DS . $folder)) { mkdir($path . DS . $folder, 0755); } if (file_exists($fullFileName)) { $data = Yaml::parse($file->content()); if (count($data) > 0) { array_unshift($data, $vars); } else { $data[] = $vars; } } else { $data[] = $vars; } $file->save(Yaml::dump($data)); // // Creates a file and update summary for recurrent notfound errors // $urls = array_column($data, 'url'); asort($urls); $summary = array(); $prev_value = array('url' => null, 'count' => null); foreach ($urls as $val) { if ($prev_value['url'] != $val) { unset($prev_value); $prev_value = array('url' => $val, 'count' => 0); $summary[] =& $prev_value; } $prev_value['count']++; } $count = array(); foreach ($summary as $key => $row) { $count[$key] = $row['count']; } array_multisort($count, SORT_DESC, $summary); // create file and save summary $fullSummaryFileName = $path . DS . $folder . DS . 'summary_' . $filename; $file_summary = File::instance($fullSummaryFileName); $file_summary->save(Yaml::dump($summary)); }
/** * Handle form processing instructions. * * @param Event $event */ public function onFormProcessed(Event $event) { $form = $event['form']; $action = $event['action']; $params = $event['params']; if (!$this->active) { return; } if (!$this->validate($form)) { /** @var Language $l */ $l = $this->grav['language']; $this->form->message = $l->translate('FORM_PLUGIN.NOT_VALIDATED'); $uri = $this->grav['uri']; $route = $uri->route(); /** @var Twig $twig */ $twig = $this->grav['twig']; $twig->twig_vars['form'] = $form; /** @var Pages $pages */ $pages = $this->grav['pages']; $page = $pages->dispatch($route, true); unset($this->grav['page']); $this->grav['page'] = $page; return; } switch ($action) { case 'message': $this->form->message = (string) $params; break; case 'redirect': $this->grav->redirect((string) $params); break; case 'reset': if (in_array($params, array(true, 1, '1', 'yes', 'on', 'true'), true)) { $this->form->reset(); } break; case 'display': $route = (string) $params; if (!$route || $route[0] != '/') { /** @var Uri $uri */ $uri = $this->grav['uri']; $route = $uri->route() . ($route ? '/' . $route : ''); } /** @var Twig $twig */ $twig = $this->grav['twig']; $twig->twig_vars['form'] = $form; /** @var Pages $pages */ $pages = $this->grav['pages']; $page = $pages->dispatch($route, true); unset($this->grav['page']); $this->grav['page'] = $page; break; case 'save': $prefix = !empty($params['fileprefix']) ? $params['fileprefix'] : ''; $format = !empty($params['dateformat']) ? $params['dateformat'] : 'Ymd-His-u'; $ext = !empty($params['extension']) ? '.' . trim($params['extension'], '.') : '.txt'; $filename = $prefix . $this->udate($format) . $ext; /** @var Twig $twig */ $twig = $this->grav['twig']; $vars = array('form' => $this->form); $file = File::instance(DATA_DIR . $this->form->name . '/' . $filename); $body = $twig->processString(!empty($params['body']) ? $params['body'] : '{% include "forms/data.txt.twig" %}', $vars); $file->save($body); } }
/** * Set all twig variables for generating output. */ public function onTwigSiteVariables() { $twig = $this->grav['twig']; $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->config->get('plugins.admin.route'), '/'); $twig->twig_vars['base_url_relative'] = $twig->twig_vars['base_url_simple'] . '/' . $twig->twig_vars['admin_route']; $twig->twig_vars['theme_url'] = $this->grav['locator']->findResource('plugin://admin/themes/' . $this->theme, false); $twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative']; $twig->twig_vars['base_path'] = GRAV_ROOT; $twig->twig_vars['admin'] = $this->admin; // 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; case 'pages': $path = $this->route; if (!$path) { $path = '/'; } if (!isset($this->pages[$path])) { $page = null; } else { $page = $this->pages[$path]; } if ($page != null) { $twig->twig_vars['file'] = File::instance($page->filePath()); $twig->twig_vars['media_types'] = str_replace('defaults,', '', implode(',.', array_keys($this->config->get('media')))); } break; } }
/** * @param string $in Filename without path or extension. * @return bool True if the output file was saved. */ public function compileFile($in) { // Buy some extra time as compilation may take a lot of time in shared environments. @set_time_limit(30); $gantry = Gantry::instance(); /** @var UniformResourceLocator $locator */ $locator = $gantry['locator']; $out = $this->getCssUrl($in); $path = $locator->findResource($out, true, true); $paths = $locator->mergeResources($this->paths); // Set the lookup paths. $this->compiler->setBasePath($path); $this->compiler->setImportDir($paths); // Run the compiler. $this->compiler->setVariables($this->getVariables()); $css = $this->compiler->compileFile($in . '.less"'); if (!$this->production) { $warning = <<<WARN /* GANTRY5 DEVELOPMENT MODE ENABLED. WARNING: This file is automatically generated by Gantry5. Any modifications to this file will be lost! For more information on modifying CSS, please read: http://docs.gantry.org/gantry5/configure/styles http://docs.gantry.org/gantry5/tutorials/adding-a-custom-style-sheet */ WARN; $css = $warning . "\n\n" . $css; } $file = File::instance($path); // 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. } //TODO: Better way to handle double writing files at same time. if ($file->locked() === false) { // File was already locked by another process. return false; } $file->save($css); $file->unlock(); $this->createMeta($out, md5($css)); 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')); $file = File::instance($filename); $resultRemoveMedia = false; $resultRemoveMediaMeta = true; if ($file->exists()) { $resultRemoveMedia = $file->delete(); $metaFilePath = $filename . '.meta.yaml'; $metaFilePath = str_replace('@3x', '', $metaFilePath); $metaFilePath = str_replace('@2x', '', $metaFilePath); if (is_file($metaFilePath)) { $metaFile = File::instance($metaFilePath); $resultRemoveMediaMeta = $metaFile->delete(); } } if ($resultRemoveMedia && $resultRemoveMediaMeta) { $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.REMOVE_SUCCESSFUL')]; return true; } else { $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.REMOVE_FAILED')]; return false; } }
/** * Constructor. */ protected function __construct() { parent::__construct(); $this->extension = '.yaml'; }
/** * Handle form processing instructions. * * @param Event $event */ public function onFormProcessed(Event $event) { $form = $event['form']; $action = $event['action']; $params = $event['params']; if (!$this->active) { return; } if (!$this->validate($form)) { /** @var Language $l */ $l = $this->grav['language']; $this->form->message = $l->translate('FORM_PLUGIN.NOT_VALIDATED'); $uri = $this->grav['uri']; $route = $uri->route(); /** @var Twig $twig */ $twig = $this->grav['twig']; $twig->twig_vars['form'] = $form; /** @var Pages $pages */ $pages = $this->grav['pages']; $page = $pages->dispatch($route, true); unset($this->grav['page']); $this->grav['page'] = $page; return; } $this->process($form); switch ($action) { case 'captcha': // Validate the captcha $query = http_build_query(['secret' => $params['recatpcha_secret'], 'response' => $this->form->value('g-recaptcha-response')]); $url = 'https://www.google.com/recaptcha/api/siteverify?' . $query; $response = json_decode(file_get_contents($url), true); if (!isset($response['success']) || $response['success'] !== true) { throw new \RuntimeException('Error validating the Captcha'); } break; case 'message': $this->form->message = (string) $params; break; case 'redirect': $this->grav->redirect((string) $params); break; case 'reset': if (in_array($params, array(true, 1, '1', 'yes', 'on', 'true'), true)) { $this->form->reset(); } break; case 'display': $route = (string) $params; if (!$route || $route[0] != '/') { /** @var Uri $uri */ $uri = $this->grav['uri']; $route = $uri->route() . ($route ? '/' . $route : ''); } /** @var Twig $twig */ $twig = $this->grav['twig']; $twig->twig_vars['form'] = $form; /** @var Pages $pages */ $pages = $this->grav['pages']; $page = $pages->dispatch($route, true); unset($this->grav['page']); $this->grav['page'] = $page; break; case 'save': $prefix = !empty($params['fileprefix']) ? $params['fileprefix'] : ''; $format = !empty($params['dateformat']) ? $params['dateformat'] : 'Ymd-His-u'; $ext = !empty($params['extension']) ? '.' . trim($params['extension'], '.') : '.txt'; $filename = !empty($params['filename']) ? $params['filename'] : ''; $operation = !empty($params['operation']) ? $params['operation'] : 'create'; if (!$filename) { $filename = $prefix . $this->udate($format) . $ext; } /** @var Twig $twig */ $twig = $this->grav['twig']; $vars = array('form' => $this->form); $fullFileName = DATA_DIR . $this->form->name . '/' . $filename; $file = File::instance($fullFileName); if ($operation == 'create') { $body = $twig->processString(!empty($params['body']) ? $params['body'] : '{% include "forms/data.txt.twig" %}', $vars); $file->save($body); } elseif ($operation == 'add') { $vars = $vars['form']->value(); foreach ($form->fields as $field) { if (isset($field['process']) && isset($field['process']['ignore']) && $field['process']['ignore']) { unset($vars[$field['name']]); } } if (file_exists($fullFileName)) { $data = Yaml::parse($file->content()); if (count($data) > 0) { array_unshift($data, $vars); } else { $data[] = $vars; } } else { $data[] = $vars; } $file->save(Yaml::dump($data)); } break; } }
/** * Handle form processing instructions. * * @param Event $event */ public function onFormProcessed(Event $event) { $form = $event['form']; $action = $event['action']; $params = $event['params']; $this->process($form); switch ($action) { case 'captcha': if (isset($params['recaptcha_secret'])) { $recaptchaSecret = $params['recaptcha_secret']; } else { if (isset($params['recatpcha_secret'])) { // Included for backwards compatibility with typo (issue #51) $recaptchaSecret = $params['recatpcha_secret']; } else { $recaptchaSecret = $this->config->get('plugins.form.recaptcha.secret_key'); } } // Validate the captcha $query = http_build_query(['secret' => $recaptchaSecret, 'response' => $form->value('g-recaptcha-response', true)]); $url = 'https://www.google.com/recaptcha/api/siteverify?' . $query; $response = json_decode(file_get_contents($url), true); if (!isset($response['success']) || $response['success'] !== true) { $this->grav->fireEvent('onFormValidationError', new Event(['form' => $form, 'message' => $this->grav['language']->translate('PLUGIN_FORM.ERROR_VALIDATING_CAPTCHA')])); $event->stopPropagation(); return; } break; case 'ip': $label = isset($params['label']) ? $params['label'] : 'User IP'; $blueprint = $form->value()->blueprints(); $blueprint->set('form/fields/ip', ['name' => 'ip', 'label' => $label]); $form->setFields($blueprint->fields()); $form->setData('ip', Uri::ip()); break; case 'message': $translated_string = $this->grav['language']->translate($params); $vars = array('form' => $form); /** @var Twig $twig */ $twig = $this->grav['twig']; $processed_string = $twig->processString($translated_string, $vars); $form->message = $processed_string; break; case 'redirect': $this->grav['session']->setFlashObject('form', $form); $this->grav->redirect((string) $params); break; case 'reset': if (Utils::isPositive($params)) { $form->reset(); } break; case 'display': $route = (string) $params; if (!$route || $route[0] != '/') { /** @var Uri $uri */ $uri = $this->grav['uri']; $route = rtrim($uri->route(), '/') . '/' . ($route ?: ''); } /** @var Twig $twig */ $twig = $this->grav['twig']; $twig->twig_vars['form'] = $form; /** @var Pages $pages */ $pages = $this->grav['pages']; $page = $pages->dispatch($route, true); if (!$page) { throw new \RuntimeException('Display page not found. Please check the page exists.', 400); } unset($this->grav['page']); $this->grav['page'] = $page; break; case 'save': $prefix = !empty($params['fileprefix']) ? $params['fileprefix'] : ''; $format = !empty($params['dateformat']) ? $params['dateformat'] : 'Ymd-His-u'; $ext = !empty($params['extension']) ? '.' . trim($params['extension'], '.') : '.txt'; $filename = !empty($params['filename']) ? $params['filename'] : ''; $operation = !empty($params['operation']) ? $params['operation'] : 'create'; if (!$filename) { $filename = $prefix . $this->udate($format) . $ext; } /** @var Twig $twig */ $twig = $this->grav['twig']; $vars = ['form' => $form]; // Process with Twig $filename = $twig->processString($filename, $vars); $locator = $this->grav['locator']; $path = $locator->findResource('user://data', true); $dir = $path . DS . $form->name(); $fullFileName = $dir . DS . $filename; $file = File::instance($fullFileName); if ($operation == 'create') { $body = $twig->processString(!empty($params['body']) ? $params['body'] : '{% include "forms/data.txt.twig" %}', $vars); $file->save($body); } elseif ($operation == 'add') { if (!empty($params['body'])) { // use body similar to 'create' action and append to file as a log $body = $twig->processString($params['body'], $vars); // create folder if it doesn't exist if (!file_exists($dir)) { mkdir($dir); } // append data to existing file file_put_contents($fullFileName, $body, FILE_APPEND | LOCK_EX); } else { // serialize YAML out to file for easier parsing as data sets $vars = $vars['form']->value()->toArray(); foreach ($form->fields as $field) { if (isset($field['process']) && isset($field['process']['ignore']) && $field['process']['ignore']) { unset($vars[$field['name']]); } } if (file_exists($fullFileName)) { $data = Yaml::parse($file->content()); if (count($data) > 0) { array_unshift($data, $vars); } else { $data[] = $vars; } } else { $data[] = $vars; } $file->save(Yaml::dump($data)); } } break; } }
/** * Given a data file route, return the YAML content already parsed */ private function getFileContentFromRoute($type, $fileRoute) { //Single item details $fileInstance = File::instance(DATA_DIR . $type . '/' . $fileRoute . $this->config->get('plugins.data-manager.types.' . $type . '.file_extension', '.txt')); if (!$fileInstance->content()) { //Item not found return; } return YamlParser::parse($fileInstance->content()); }
public function delete() { /** @var UniformResourceLocator $locator */ $locator = $this->container['locator']; $path = implode('/', func_get_args()); if (base64_decode($path, true) !== false) { $path = base64_decode($path); } $stream = explode('://', $path); $scheme = $stream[0]; if (!$path) { throw new \RuntimeException('No file specified for delete', 400); } $isStream = $locator->schemeExists($scheme); if ($isStream) { $targetPath = $locator->findResource($path, true, true); } else { $targetPath = GANTRY5_ROOT . '/' . $path; } $file = File::instance($targetPath); if (!$file->exists()) { throw new \RuntimeException('File not found: ' . $targetPath, 404); } try { $file->delete(); } catch (\Exception $e) { throw new \RuntimeException('File could not be deleted: ' . $targetPath, 500); } return new JsonResponse(['success', 'File deleted: ' . $targetPath]); }
public function delete() { $path = implode('/', func_get_args()); if (!$path) { throw new \RuntimeException('No file specified for delete', 400); } // TODO: handle streams $targetPath = GANTRY5_ROOT . '/' . $path; $file = File::instance($targetPath); if (!$file->exists()) { throw new \RuntimeException('File not found: ' . $path, 404); } try { $file->delete(); } catch (\Exception $e) { throw new \RuntimeException('File could not be deleted: ' . $path, 500); } return new JsonResponse(['success', 'File deleted: ' . $path]); }