Files
Grav-Admin-Plugin/classes/controller.php

2038 lines
63 KiB
PHP
Raw Normal View History

2014-08-05 13:06:38 -07:00
<?php
namespace Grav\Plugin;
use Grav\Common\Cache;
2014-10-01 22:28:16 +03:00
use Grav\Common\Config\Config;
2014-08-05 13:06:38 -07:00
use Grav\Common\Filesystem\Folder;
use Grav\Common\GPM\Installer;
use Grav\Common\Grav;
2014-08-05 13:06:38 -07:00
use Grav\Common\Data;
2016-01-21 09:46:38 +02:00
use Grav\Common\Page\Page;
2015-10-21 19:46:51 +02:00
use Grav\Common\Page\Pages;
use Grav\Common\Page\Collection;
use Grav\Common\Plugin;
use Grav\Common\Theme;
use Grav\Common\User\User;
2015-04-27 13:37:22 +02:00
use Grav\Common\Utils;
use Grav\Common\Backup\ZipBackup;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\File\File;
2015-04-27 13:37:22 +02:00
use RocketTheme\Toolbox\File\JsonFile;
use Symfony\Component\Yaml\Exception\ParseException;
2015-08-04 19:28:42 +02:00
use Symfony\Component\Yaml\Yaml;
2014-08-05 13:06:38 -07:00
2016-02-12 10:16:28 +01:00
/**
* Class AdminController
* @package Grav\Plugin
*/
2014-08-05 13:06:38 -07:00
class AdminController
{
/**
* @var Grav
*/
public $grav;
2014-08-05 13:06:38 -07:00
/**
* @var string
*/
public $view;
/**
* @var string
*/
public $task;
/**
* @var string
*/
public $route;
/**
* @var array
*/
public $post;
/**
* @var Admin
*/
protected $admin;
/**
* @var string
*/
protected $redirect;
/**
* @var int
*/
protected $redirectCode;
/**
* @param Grav $grav
2014-08-05 13:06:38 -07:00
* @param string $view
* @param string $task
* @param string $route
* @param array $post
*/
public function __construct(Grav $grav, $view, $task, $route, $post)
2014-08-05 13:06:38 -07:00
{
$this->grav = $grav;
2014-08-05 13:06:38 -07:00
$this->view = $view;
$this->task = $task ? $task : 'display';
$this->post = $this->getPost($post);
$this->route = $route;
$this->admin = $this->grav['admin'];
2014-08-05 13:06:38 -07:00
}
/**
* Performs a task.
2015-07-30 12:20:25 +02:00
*
* @return bool True if the action was performed successfully.
2014-08-05 13:06:38 -07:00
*/
public function execute()
{
2015-11-17 11:56:21 +01:00
if (method_exists('Grav\Common\Utils', 'getNonce')) {
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')) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'), 'error');
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN')
];
return false;
}
unset($this->post['admin-nonce']);
2015-11-17 11:56:21 +01:00
} else {
if ($this->task == 'logout') {
2015-11-17 11:56:21 +01:00
$nonce = $this->grav['uri']->param('logout-nonce');
if (!isset($nonce) || !Utils::verifyNonce($nonce, 'logout-form')) {
2016-03-05 12:11:13 +01:00
$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 (!isset($nonce) || !Utils::verifyNonce($nonce, 'admin-form')) {
2016-03-05 12:11:13 +01:00
$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;
2015-11-17 11:56:21 +01:00
}
}
2015-11-10 17:53:09 +01:00
}
2015-11-06 15:32:26 +01:00
}
2014-08-05 13:06:38 -07:00
$success = false;
$method = 'task' . ucfirst($this->task);
2014-08-05 13:06:38 -07:00
if (method_exists($this, $method)) {
try {
2016-02-12 10:16:28 +01:00
$success = call_user_func([$this, $method]);
2014-08-05 13:06:38 -07:00
} catch (\RuntimeException $e) {
$success = true;
$this->admin->setMessage($e->getMessage(), 'error');
2014-08-05 13:06:38 -07:00
}
// Grab redirect parameter.
$redirect = isset($this->post['_redirect']) ? $this->post['_redirect'] : null;
unset($this->post['_redirect']);
2014-08-05 13:06:38 -07:00
// Redirect if requested.
if ($redirect) {
$this->setRedirect($redirect);
}
}
2016-03-05 12:11:13 +01:00
2014-08-05 13:06:38 -07:00
return $success;
}
2015-07-30 12:20:25 +02:00
/**
* Redirect to the route stored in $this->redirect
*/
2014-08-05 13:06:38 -07:00
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
2016-03-05 12:11:13 +01:00
if (Utils::pathPrefixedByLangCode($base) && Utils::pathPrefixedByLangCode($this->redirect) && substr($base,
0, 4) != substr($this->redirect, 0, 4)
) {
$redirect = $this->redirect;
} else {
if (!Utils::startsWith($this->redirect, $base)) {
$this->redirect = $base . $this->redirect;
}
}
} else {
if (!Utils::startsWith($this->redirect, $base)) {
$this->redirect = $base . $this->redirect;
}
}
if (!$redirect) {
$redirect = $this->redirect;
}
2014-08-05 13:06:38 -07:00
$this->grav->redirect($redirect, $this->redirectCode);
2014-08-05 13:06:38 -07:00
}
/**
* Return true if multilang is active
*
* @return bool True if multilang is active
*/
2016-01-10 17:17:04 +01:00
protected function isMultilang()
{
return count($this->grav['config']->get('system.languages.supported', [])) > 1;
}
2014-08-05 13:06:38 -07:00
/**
* Handle login.
*
* @return bool True if the action was performed.
*/
protected function taskLogin()
{
$this->post['username'] = strtolower($this->post['username']);
if ($this->admin->authenticate($this->post)) {
// should never reach here, redirects first
} else {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.LOGIN_FAILED'), 'error');
}
2014-08-05 13:06:38 -07:00
return true;
}
/**
* Handle logout.
*
* @return bool True if the action was performed.
*/
protected function taskLogout()
{
$this->admin->session()->invalidate()->start();
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.LOGGED_OUT'), 'info');
2015-08-08 11:16:04 +02:00
$this->setRedirect('/logout');
2014-08-05 13:06:38 -07:00
return true;
}
/**
* Keep alive
*/
protected function taskKeepAlive()
{
exit();
}
/**
* Handle removing a plugin
*
* @return bool
*/
protected function taskRemovePlugin()
{
if (!$this->authorizeTask('uninstall plugin', ['admin.plugin', 'admin.super'])) {
$this->admin->json_response = ['status' => 'error', 'message' => 'Unauthorized'];
return false;
}
$data = $this->post;
$plugin = isset($data['plugin']) ? $data['plugin'] : '';
require_once __DIR__ . '/gpm.php';
$dependencies = $this->admin->dependenciesThatCanBeRemovedWhenRemoving($plugin);
//TODO: uncomment to actually remove
$result = true;
// $result = \Grav\Plugin\Admin\Gpm::uninstall($plugin, []);
if ($result) {
$this->admin->json_response = ['status' => 'success', 'dependencies' => $dependencies, 'message' => $this->admin->translate('PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL')];
} else {
$this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED')];
}
return true;
}
2015-07-30 12:20:25 +02:00
/**
* Handle the email password recovery procedure.
*
* @return bool True if the action was performed.
*/
2015-04-20 16:01:20 +02:00
protected function taskForgot()
{
2015-08-17 21:34:41 +02:00
$param_sep = $this->grav['config']->get('system.param_sep', ':');
2015-04-20 16:01:20 +02:00
$data = $this->post;
$username = isset($data['username']) ? $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');
2015-04-20 16:01:20 +02:00
$this->setRedirect('/');
2016-03-05 12:11:13 +01:00
2015-04-20 16:01:20 +02:00
return true;
}
if (!$user || !$user->exists()) {
2016-03-05 12:11:13 +01:00
$this->admin->setMessage($this->admin->translate([
'PLUGIN_ADMIN.FORGOT_USERNAME_DOES_NOT_EXIST',
$username
]), 'error');
2015-04-20 16:01:20 +02:00
$this->setRedirect('/forgot');
2016-03-05 12:11:13 +01:00
2015-04-20 16:01:20 +02:00
return true;
}
if (empty($user->email)) {
2016-03-05 12:11:13 +01:00
$this->admin->setMessage($this->admin->translate([
'PLUGIN_ADMIN.FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL',
$username
]), 'error');
2015-04-20 16:01:20 +02:00
$this->setRedirect('/forgot');
2016-03-05 12:11:13 +01:00
2015-04-20 16:01:20 +02:00
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;
2016-03-05 12:11:13 +01:00
$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');
2015-04-20 16:01:20 +02:00
2015-07-21 22:02:13 -06:00
$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('/forgot');
2016-03-05 12:11:13 +01:00
return true;
}
2015-04-20 16:01:20 +02:00
$to = $user->email;
2015-07-21 22:02:13 -06:00
$subject = $this->admin->translate(['PLUGIN_ADMIN.FORGOT_EMAIL_SUBJECT', $sitename]);
2016-03-05 12:11:13 +01:00
$content = $this->admin->translate([
'PLUGIN_ADMIN.FORGOT_EMAIL_BODY',
$fullname,
$reset_link,
$author,
$sitename
]);
2015-07-21 22:02:13 -06:00
$body = $this->grav['twig']->processTemplate('email/base.html.twig', ['content' => $content]);
2015-04-20 16:01:20 +02:00
2016-03-05 12:11:13 +01:00
$message = $this->grav['Email']->message($subject, $body, 'text/html')->setFrom($from)->setTo($to);
2015-04-20 16:01:20 +02:00
$sent = $this->grav['Email']->send($message);
if ($sent < 1) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_FAILED_TO_EMAIL'), 'error');
2015-04-20 16:01:20 +02:00
} else {
2016-03-05 12:11:13 +01:00
$this->admin->setMessage($this->admin->translate(['PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL', $to]),
'info');
2015-04-20 16:01:20 +02:00
}
$this->setRedirect('/');
2016-03-05 12:11:13 +01:00
2015-04-20 16:01:20 +02:00
return true;
}
2015-07-30 12:20:25 +02:00
/**
* Handle the reset password action.
*
* @return bool True if the action was performed.
*/
2015-04-20 16:01:20 +02:00
public function taskReset()
{
$data = $this->post;
if (isset($data['password'])) {
$username = isset($data['username']) ? $data['username'] : null;
$user = !empty($username) ? User::load($username) : null;
$password = isset($data['password']) ? $data['password'] : null;
$token = isset($data['token']) ? $data['token'] : null;
if (!empty($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');
2015-04-20 16:01:20 +02:00
$this->setRedirect('/forgot');
2016-03-05 12:11:13 +01:00
2015-04-20 16:01:20 +02:00
return true;
}
unset($user->hashed_password);
unset($user->reset);
$user->password = $password;
2015-07-22 14:31:09 -06:00
$user->validate();
$user->filter();
2015-04-20 16:01:20 +02:00
$user->save();
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_PASSWORD_RESET'), 'info');
2015-04-20 16:01:20 +02:00
$this->setRedirect('/');
2016-03-05 12:11:13 +01:00
2015-04-20 16:01:20 +02:00
return true;
}
}
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_INVALID_LINK'), 'error');
2015-04-20 16:01:20 +02:00
$this->setRedirect('/forgot');
2016-03-05 12:11:13 +01:00
2015-04-20 16:01:20 +02:00
return true;
} else {
$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');
2015-04-20 16:01:20 +02:00
$this->setRedirect('/forgot');
2016-03-05 12:11:13 +01:00
2015-04-20 16:01:20 +02:00
return true;
}
2016-03-05 12:11:13 +01:00
$this->admin->forgot = ['username' => $user, 'token' => $token];
2015-04-20 16:01:20 +02:00
}
return true;
}
2015-07-30 12:20:25 +02:00
/**
* Clear the cache.
*
* @return bool True if the action was performed.
*/
protected function taskClearCache()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('clear cache', ['admin.cache', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2015-08-06 16:19:36 -06:00
// get optional cleartype param
2015-08-06 16:16:18 -06:00
$clear_type = $this->grav['uri']->param('cleartype');
2015-08-06 16:19:36 -06:00
if ($clear_type) {
2015-08-06 16:16:18 -06:00
$clear = $clear_type;
} else {
2015-08-06 16:19:36 -06:00
$clear = 'standard';
2015-08-06 16:16:18 -06:00
}
$results = Cache::clearCache($clear);
if (count($results) > 0) {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'success',
'message' => $this->admin->translate('PLUGIN_ADMIN.CACHE_CLEARED') . ' <br />' . $this->admin->translate('PLUGIN_ADMIN.METHOD') . ': ' . $clear . ''
];
} else {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.ERROR_CLEARING_CACHE')
];
}
2014-08-05 13:06:38 -07:00
return true;
}
2015-07-30 12:20:25 +02:00
/**
* Handle the backup action
*
* @return bool True if the action was performed.
*/
2015-04-27 13:37:22 +02:00
protected function taskBackup()
{
2015-08-17 21:34:41 +02:00
$param_sep = $this->grav['config']->get('system.param_sep', ':');
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('backup', ['admin.maintenance', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2015-04-27 13:37:22 +02:00
$download = $this->grav['uri']->param('download');
if ($download) {
Utils::download(base64_decode(urldecode($download)), true);
}
$log = JsonFile::instance($this->grav['locator']->findResource("log://backup.log", true, true));
2015-05-04 11:53:29 +02:00
try {
$backup = ZipBackup::backup();
} catch (\Exception $e) {
$this->admin->json_response = [
2016-03-05 12:11:13 +01:00
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.AN_ERROR_OCCURRED') . '. ' . $e->getMessage()
2015-05-04 11:53:29 +02:00
];
return true;
}
2015-04-27 13:37:22 +02:00
$download = urlencode(base64_encode($backup));
2016-03-05 12:11:13 +01:00
$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');
2015-04-27 13:37:22 +02:00
$log->content([
2016-03-05 12:11:13 +01:00
'time' => time(),
2015-04-27 13:37:22 +02:00
'location' => $backup
]);
$log->save();
$this->admin->json_response = [
2016-03-05 12:11:13 +01:00
'status' => 'success',
'message' => $this->admin->translate('PLUGIN_ADMIN.YOUR_BACKUP_IS_READY_FOR_DOWNLOAD') . '. <a href="' . $url . '" class="button">' . $this->admin->translate('PLUGIN_ADMIN.DOWNLOAD_BACKUP') . '</a>',
'toastr' => [
'timeOut' => 0,
2016-02-01 11:27:34 -08:00
'extendedTimeOut' => 0,
2016-03-05 12:11:13 +01:00
'closeButton' => true
2015-04-27 13:37:22 +02:00
]
];
return true;
}
2015-07-30 12:20:25 +02:00
/**
* Handles filtering the page by modular/visible/routable in the pages list.
*/
protected function taskFilterPages()
{
2015-09-11 15:00:03 +02:00
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']) : [];
2015-09-09 19:37:29 -06:00
/** @var Collection $collection */
$collection = $this->grav['pages']->all();
if (count($flags)) {
// Filter by state
2016-03-05 12:11:13 +01:00
$pageStates = [
'modular',
'nonmodular',
'visible',
'nonvisible',
'routable',
'nonroutable',
'published',
'nonpublished'
];
if (count(array_intersect($pageStates, $flags)) > 0) {
2016-03-05 12:11:13 +01:00
if (in_array('modular', $flags)) {
$collection = $collection->modular();
2016-03-05 12:11:13 +01:00
}
2016-03-05 12:11:13 +01:00
if (in_array('nonmodular', $flags)) {
2015-09-09 21:38:28 -06:00
$collection = $collection->nonModular();
2016-03-05 12:11:13 +01:00
}
2015-09-09 21:38:28 -06:00
2016-03-05 12:11:13 +01:00
if (in_array('visible', $flags)) {
$collection = $collection->visible();
2016-03-05 12:11:13 +01:00
}
2016-03-05 12:11:13 +01:00
if (in_array('nonvisible', $flags)) {
2015-09-09 19:37:29 -06:00
$collection = $collection->nonVisible();
2016-03-05 12:11:13 +01:00
}
2015-09-09 19:37:29 -06:00
2016-03-05 12:11:13 +01:00
if (in_array('routable', $flags)) {
$collection = $collection->routable();
2016-03-05 12:11:13 +01:00
}
2015-09-09 19:37:29 -06:00
2016-03-05 12:11:13 +01:00
if (in_array('nonroutable', $flags)) {
2015-09-09 19:37:29 -06:00
$collection = $collection->nonRoutable();
2016-03-05 12:11:13 +01:00
}
2015-09-09 19:37:29 -06:00
2016-03-05 12:11:13 +01:00
if (in_array('published', $flags)) {
2015-09-09 19:37:29 -06:00
$collection = $collection->published();
2016-03-05 12:11:13 +01:00
}
2015-09-09 19:37:29 -06:00
2016-03-05 12:11:13 +01:00
if (in_array('nonpublished', $flags)) {
2015-09-09 19:37:29 -06:00
$collection = $collection->nonPublished();
2016-03-05 12:11:13 +01:00
}
}
foreach ($pageStates as $pageState) {
if (($pageState = array_search($pageState, $flags)) !== false) {
unset($flags[$pageState]);
}
}
// Filter by page type
if (count($flags)) {
2015-10-21 19:46:51 +02:00
$types = [];
$pageTypes = Pages::pageTypes();
foreach ($pageTypes as $pageType) {
if (($pageType = array_search($pageType, $flags)) !== false) {
$types[] = $pageType;
unset($flags[$pageType]);
}
}
if (count($types)) {
$collection = $collection->ofOneOfTheseTypes($types);
}
}
// Filter by page type
if (count($flags)) {
$accessLevels = $flags;
$collection = $collection->ofOneOfTheseAccessLevels($accessLevels);
}
}
if (!empty($queries)) {
foreach ($collection as $page) {
foreach ($queries as $query) {
$query = trim($query);
2016-03-05 12:11:13 +01:00
if (stripos($page->getRawContent(), $query) === false && stripos($page->title(),
$query) === false
) {
$collection->remove($page);
}
}
}
}
$results = [];
foreach ($collection as $path => $page) {
$results[] = $page->route();
}
$this->admin->json_response = [
2016-03-05 12:11:13 +01:00
'status' => 'success',
2015-08-17 17:18:21 +02:00
'message' => $this->admin->translate('PLUGIN_ADMIN.PAGES_FILTERED'),
'results' => $results
];
$this->admin->collection = $collection;
}
2015-07-30 12:20:25 +02:00
/**
* Determines the file types allowed to be uploaded
*
* @return bool True if the action was performed.
*/
2014-09-22 15:49:53 -06:00
protected function taskListmedia()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('list media', ['admin.pages', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2014-09-22 15:49:53 -06:00
$page = $this->admin->page(true);
2014-09-22 17:13:19 -06:00
if (!$page) {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
];
2014-10-01 22:28:16 +03:00
return false;
2014-09-22 17:13:19 -06:00
}
2016-02-12 10:16:28 +01:00
$media_list = [];
2014-12-10 10:23:22 -07:00
foreach ($page->media()->all() as $name => $media) {
2015-07-30 12:20:25 +02:00
$media_list[$name] = ['url' => $media->cropZoom(150, 100)->url(), 'size' => $media->get('size')];
2014-09-22 15:49:53 -06:00
}
2016-02-01 11:27:34 -08:00
$this->admin->json_response = ['status' => 'success', 'results' => $media_list];
2014-09-22 15:49:53 -06:00
return true;
}
2015-07-30 12:20:25 +02:00
/**
* Handles adding a media file to a page
2016-01-21 09:46:38 +02:00
*
* @return bool True if the action was performed.
2015-07-30 12:20:25 +02:00
*/
2014-09-22 16:35:11 -06:00
protected function taskAddmedia()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('add media', ['admin.pages', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2014-09-22 16:35:11 -06:00
$page = $this->admin->page(true);
2014-10-01 22:28:16 +03:00
/** @var Config $config */
2014-09-22 16:35:11 -06:00
$config = $this->grav['config'];
2014-10-07 15:32:07 -06:00
if (!isset($_FILES['file']['error']) || is_array($_FILES['file']['error'])) {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_PARAMETERS')
];
2016-01-21 09:46:38 +02:00
return false;
2014-10-07 15:32:07 -06:00
}
2014-09-22 16:35:11 -06:00
2014-10-07 15:32:07 -06:00
// Check $_FILES['file']['error'] value.
switch ($_FILES['file']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.NO_FILES_SENT')
];
2016-01-21 09:46:38 +02:00
return false;
2014-10-07 15:32:07 -06:00
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT')
];
2016-01-21 09:46:38 +02:00
return false;
2014-10-07 15:32:07 -06:00
default:
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.UNKNOWN_ERRORS')
];
2016-01-21 09:46:38 +02:00
return false;
2014-10-07 15:32:07 -06:00
}
2014-09-22 16:35:11 -06:00
2015-04-27 19:33:48 +02:00
$grav_limit = $config->get('system.media.upload_limit', 0);
2014-10-07 15:32:07 -06:00
// You should also check filesize here.
if ($grav_limit > 0 && $_FILES['file']['size'] > $grav_limit) {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT')
];
2016-01-21 09:46:38 +02:00
return false;
2014-09-22 16:35:11 -06:00
}
2014-10-07 15:32:07 -06:00
// Check extension
$fileParts = pathinfo($_FILES['file']['name']);
$fileExt = '';
if (isset($fileParts['extension'])) {
$fileExt = strtolower($fileParts['extension']);
}
2014-10-07 15:32:07 -06:00
// If not a supported type, return
if (!$fileExt || !$config->get("media.{$fileExt}")) {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $fileExt
];
2016-01-21 09:46:38 +02:00
return false;
2014-10-07 15:32:07 -06:00
}
// Upload it
2016-03-05 12:11:13 +01:00
if (!move_uploaded_file($_FILES['file']['tmp_name'],
sprintf('%s/%s', $page->path(), $_FILES['file']['name']))
) {
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.FAILED_TO_MOVE_UPLOADED_FILE')
];
2016-01-21 09:46:38 +02:00
return false;
2014-10-07 15:32:07 -06:00
}
2016-02-01 11:27:34 -08:00
Cache::clearCache();
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'success',
'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_UPLOADED_SUCCESSFULLY')
];
2014-10-07 15:32:07 -06:00
2016-01-21 09:46:38 +02:00
return true;
2014-09-22 17:13:19 -06:00
}
2015-07-30 12:20:25 +02:00
/**
* Handles deleting a media file from a page
*
* @return bool True if the action was performed.
*/
2014-09-22 17:13:19 -06:00
protected function taskDelmedia()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('delete media', ['admin.pages', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2014-09-22 17:27:48 -06:00
$page = $this->admin->page(true);
if (!$page) {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
];
2014-10-01 22:28:16 +03:00
return false;
2014-09-22 17:27:48 -06:00
}
2014-09-22 17:13:19 -06:00
2014-09-22 17:27:48 -06:00
$filename = !empty($this->post['filename']) ? $this->post['filename'] : null;
if ($filename) {
$targetPath = $page->path() . '/' . $filename;
2014-09-22 17:27:48 -06:00
if (file_exists($targetPath)) {
2014-12-10 10:23:22 -07:00
if (unlink($targetPath)) {
2016-02-01 11:27:34 -08:00
Cache::clearCache();
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'success',
'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_DELETED') . ': ' . $filename
];
} else {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename
];
}
2014-09-22 17:27:48 -06:00
} else {
//Try with responsive images @1x, @2x, @3x
$ext = pathinfo($targetPath, PATHINFO_EXTENSION);
2016-03-05 12:11:13 +01:00
$fullPathFilename = $page->path() . '/' . basename($targetPath, ".$ext");
$responsiveTargetPath = $fullPathFilename . '@1x.' . $ext;
$deletedResponsiveImage = false;
if (file_exists($responsiveTargetPath) && unlink($responsiveTargetPath)) {
$deletedResponsiveImage = true;
}
$responsiveTargetPath = $fullPathFilename . '@2x.' . $ext;
if (file_exists($responsiveTargetPath) && unlink($responsiveTargetPath)) {
$deletedResponsiveImage = true;
}
$responsiveTargetPath = $fullPathFilename . '@3x.' . $ext;
if (file_exists($responsiveTargetPath) && unlink($responsiveTargetPath)) {
$deletedResponsiveImage = true;
}
if ($deletedResponsiveImage) {
2016-02-01 11:27:34 -08:00
Cache::clearCache();
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'success',
'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_DELETED') . ': ' . $filename
];
} else {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_NOT_FOUND') . ': ' . $filename
];
}
2014-09-22 17:27:48 -06:00
}
} else {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.NO_FILE_FOUND')
];
2014-09-22 17:27:48 -06:00
}
2015-07-30 12:20:25 +02:00
2014-09-22 17:27:48 -06:00
return true;
2014-09-22 16:35:11 -06:00
}
2015-07-30 12:20:25 +02:00
/**
* Process the page Markdown
2016-01-21 09:46:38 +02:00
*
* @return bool True if the action was performed.
2015-07-30 12:20:25 +02:00
*/
protected function taskProcessMarkdown()
{
2015-09-11 15:00:03 +02:00
// if (!$this->authorizeTask('process markdown', ['admin.pages', 'admin.super'])) {
// return;
// }
try {
$page = $this->admin->page(true);
if (!$page) {
2016-03-05 12:11:13 +01:00
$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');
2016-03-05 12:11:13 +01:00
$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()];
2016-01-21 09:46:38 +02:00
return false;
}
2016-01-21 09:46:38 +02:00
return true;
}
2014-08-05 13:06:38 -07:00
/**
2015-07-30 12:20:25 +02:00
* Enable a plugin.
2014-08-05 13:06:38 -07:00
*
* @return bool True if the action was performed.
*/
public function taskEnable()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('enable plugin', ['admin.plugins', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2014-08-05 13:06:38 -07:00
if ($this->view != 'plugins') {
return false;
}
// Filter value and save it.
2016-02-12 10:16:28 +01:00
$this->post = ['enabled' => true];
$obj = $this->prepareData();
$obj->save();
2016-02-12 10:16:28 +01:00
$this->post = ['_redirect' => 'plugins'];
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_ENABLED_PLUGIN'), 'info');
return true;
}
/**
2015-07-30 12:20:25 +02:00
* Disable a plugin.
*
* @return bool True if the action was performed.
*/
public function taskDisable()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('disable plugin', ['admin.plugins', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
if ($this->view != 'plugins') {
return false;
}
// Filter value and save it.
2016-03-05 12:11:13 +01:00
$this->post = ['enabled' => false];
2014-08-05 13:06:38 -07:00
$obj = $this->prepareData();
$obj->save();
2016-03-05 12:11:13 +01:00
$this->post = ['_redirect' => 'plugins'];
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_DISABLED_PLUGIN'), 'info');
2014-08-05 13:06:38 -07:00
return true;
}
/**
2015-07-30 12:20:25 +02:00
* Set the default theme.
2014-08-05 13:06:38 -07:00
*
* @return bool True if the action was performed.
*/
public function taskActivate()
2014-08-05 13:06:38 -07:00
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('activate theme', ['admin.themes', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2014-08-05 13:06:38 -07:00
if ($this->view != 'themes') {
return false;
}
2016-03-05 12:11:13 +01:00
$this->post = ['_redirect' => 'themes'];
2014-08-05 13:06:38 -07:00
// Make sure theme exists (throws exception)
$name = $this->route;
$this->grav['themes']->get($name);
2014-08-05 13:06:38 -07:00
// Store system configuration.
$system = $this->admin->data('system');
$system->set('pages.theme', $name);
$system->save();
// Force configuration reload and save.
/** @var Config $config */
$config = $this->grav['config'];
2014-08-05 13:06:38 -07:00
$config->reload()->save();
$config->set('system.pages.theme', $name);
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_CHANGED_THEME'), 'info');
2014-08-05 13:06:38 -07:00
return true;
}
/**
* Handles installing plugins and themes
*
2015-11-04 14:43:25 +01:00
* @return bool True if the action was performed
*/
public function taskInstall()
{
$type = $this->view === 'plugins' ? 'plugins' : 'themes';
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2015-04-13 21:37:12 +02:00
require_once __DIR__ . '/gpm.php';
$package = $this->route;
$result = \Grav\Plugin\Admin\Gpm::install($package, ['theme' => ($type == 'themes')]);
2015-04-13 21:37:12 +02:00
if ($result) {
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info');
2015-04-13 21:37:12 +02:00
} else {
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED'), 'error');
2015-04-13 21:37:12 +02:00
}
2016-03-05 12:11:13 +01:00
$this->post = ['_redirect' => $this->view . '/' . $this->route];
2015-04-13 21:37:12 +02:00
return true;
}
/**
* Handles updating Grav
*
2015-11-04 14:43:25 +01:00
* @return bool True if the action was performed
*/
public function taskUpdategrav()
{
require_once __DIR__ . '/gpm.php';
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('install grav', ['admin.super'])) {
return false;
2015-08-06 15:16:22 +02:00
}
$result = \Grav\Plugin\Admin\Gpm::selfupgrade();
if ($result) {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'success',
'type' => 'updategrav',
'version' => GRAV_VERSION,
'message' => $this->admin->translate('PLUGIN_ADMIN.GRAV_WAS_SUCCESSFULLY_UPDATED_TO') . ' ' . GRAV_VERSION
];
} else {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'type' => 'updategrav',
'version' => GRAV_VERSION,
'message' => $this->admin->translate('PLUGIN_ADMIN.GRAV_UPDATE_FAILED') . ' <br>' . Installer::lastErrorMsg()
];
}
return true;
}
2015-04-13 21:37:12 +02:00
/**
* Handles updating plugins and themes
*
2015-11-04 14:43:25 +01:00
* @return bool True if the action was performed
2015-04-13 21:37:12 +02:00
*/
public function taskUpdate()
{
require_once __DIR__ . '/gpm.php';
$package = $this->route;
$permissions = [];
2015-04-13 21:37:12 +02:00
$type = $this->view === 'plugins' ? 'plugins' : 'themes';
2015-04-13 21:37:12 +02:00
// Update multi mode
if (!$package) {
$package = [];
if ($this->view === 'plugins' || $this->view === 'update') {
$package = $this->admin->gpm()->getUpdatablePlugins();
$permissions['plugins'] = ['admin.super', 'admin.plugins'];
2015-04-13 21:37:12 +02:00
}
if ($this->view === 'themes' || $this->view === 'update') {
$package = array_merge($package, $this->admin->gpm()->getUpdatableThemes());
$permissions['themes'] = ['admin.super', 'admin.themes'];
}
}
foreach ($permissions as $type => $p) {
2016-03-05 12:11:13 +01:00
if (!$this->authorizeTask('update ' . $type, $p)) {
2016-01-21 09:46:38 +02:00
return false;
2015-04-13 21:37:12 +02:00
}
}
$result = \Grav\Plugin\Admin\Gpm::update($package, ['theme' => ($type == 'themes')]);
2015-04-13 21:37:12 +02:00
if ($this->view === 'update') {
if ($result) {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'success',
'type' => 'update',
'message' => $this->admin->translate('PLUGIN_ADMIN.EVERYTHING_UPDATED')
];
2015-04-13 21:37:12 +02:00
} else {
2016-03-05 12:11:13 +01:00
$this->admin->json_response = [
'status' => 'error',
'type' => 'update',
'message' => $this->admin->translate('PLUGIN_ADMIN.UPDATES_FAILED')
];
2015-04-13 21:37:12 +02:00
}
} else {
if ($result) {
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info');
2015-04-13 21:37:12 +02:00
} else {
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED'), 'error');
2015-04-13 21:37:12 +02:00
}
2016-02-12 10:16:28 +01:00
$this->post = ['_redirect' => $this->view . '/' . $this->route];
2015-04-13 21:37:12 +02:00
}
return true;
}
/**
* Handles uninstalling plugins and themes
*
2015-11-04 14:43:25 +01:00
* @return bool True if the action was performed
2015-04-13 21:37:12 +02:00
*/
public function taskUninstall()
{
$type = $this->view === 'plugins' ? 'plugins' : 'themes';
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2015-04-13 21:37:12 +02:00
require_once __DIR__ . '/gpm.php';
$package = $this->route;
2015-04-13 21:37:12 +02:00
$result = \Grav\Plugin\Admin\Gpm::uninstall($package, []);
if ($result) {
2015-08-19 16:53:21 -06:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL'), 'info');
2015-04-13 21:37:12 +02:00
} else {
2015-08-19 16:53:21 -06:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED'), 'error');
2015-04-13 21:37:12 +02:00
}
2016-03-05 12:11:13 +01:00
$this->post = ['_redirect' => $this->view];
2015-04-13 21:37:12 +02:00
return true;
}
2016-01-21 09:46:38 +02:00
/**
* @param string $key
* @param string $file
2016-03-05 12:11:13 +01:00
*
2016-01-21 09:46:38 +02:00
* @return bool
*/
private function cleanFilesData($key, $file)
{
$blueprint = isset($this->items['fields'][$key]['files']) ? $this->items['fields'][$key]['files'] : [];
/** @var Page $page */
2016-03-05 12:11:13 +01:00
$page = null;
$cleanFiles[$key] = [];
if (!isset($blueprint)) {
return false;
}
$type = trim("{$this->view}/{$this->admin->route}", '/');
$data = $this->admin->data($type, $this->post);
$fields = $data->blueprints()->fields();
$blueprint = isset($fields[$key]) ? $fields[$key] : [];
$cleanFiles = [$key => []];
foreach ((array)$file['error'] as $index => $error) {
if ($error == UPLOAD_ERR_OK) {
2016-03-05 12:11:13 +01:00
$tmp_name = $file['tmp_name'][$index];
$name = $file['name'][$index];
$type = $file['type'][$index];
$destination = Folder::getRelativePath(rtrim($blueprint['destination'], '/'));
if (!$this->match_in_array($type, $blueprint['accept'])) {
throw new \RuntimeException('File "' . $name . '" is not an accepted MIME type.');
}
if (Utils::startsWith($destination, '@page:')) {
$parts = explode(':', $destination);
$route = $parts[1];
2016-03-05 12:11:13 +01:00
$page = $this->grav['page']->find($route);
if (!$page) {
throw new \RuntimeException('Unable to upload file to destination. Page route not found.');
}
$destination = $page->relativePagePath();
} else {
2016-03-05 12:11:13 +01:00
if ($destination == '@self') {
$page = $this->admin->page(true);
$destination = $page->relativePagePath();
} else {
Folder::mkdir($destination);
}
}
if (move_uploaded_file($tmp_name, "$destination/$name")) {
2016-03-05 12:11:13 +01:00
$path = $page ? $this->grav['uri']->convertUrl($page,
$page->route() . '/' . $name) : $destination . '/' . $name;
$cleanFiles[$key][] = $path;
} else {
throw new \RuntimeException("Unable to upload file(s) to $destination/$name");
}
}
}
return $cleanFiles[$key];
}
2016-01-21 09:46:38 +02:00
/**
2016-03-05 12:11:13 +01:00
* @param string $needle
2016-01-21 09:46:38 +02:00
* @param array|string $haystack
2016-03-05 12:11:13 +01:00
*
2016-01-21 09:46:38 +02:00
* @return bool
*/
private function match_in_array($needle, $haystack)
{
foreach ((array)$haystack as $item) {
2016-03-05 12:11:13 +01:00
if (true == preg_match("#^" . strtr(preg_quote($item, '#'), ['\*' => '.*', '\?' => '.']) . "$#i",
$needle)
) {
return true;
}
}
return false;
}
2016-01-21 09:46:38 +02:00
/**
* @param mixed $obj
2016-03-05 12:11:13 +01:00
*
2016-01-21 09:46:38 +02:00
* @return mixed
*/
private function processFiles($obj)
{
foreach ((array)$_FILES as $key => $file) {
$cleanFiles = $this->cleanFilesData($key, $file);
if ($cleanFiles) {
$obj->set($key, $cleanFiles);
}
}
return $obj;
}
/**
2016-01-15 12:57:09 +01:00
* 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())) {
2016-03-05 12:11:13 +01:00
return false;
2016-01-15 12:57:09 +01:00
}
$data = $this->post;
if ($data['route'] == '/') {
$path = $this->grav['locator']->findResource('page://');
} else {
$path = $page = $this->grav['page']->find($data['route'])->path();
}
$files = Folder::all($path, ['recursive' => false]);
2016-01-15 12:57:09 +01:00
$highestOrder = 0;
foreach ($files as $file) {
preg_match(PAGE_ORDER_PREFIX_REGEX, $file, $order);
if (isset($order[0])) {
$theOrder = intval(trim($order[0], '.'));
} else {
$theOrder = 0;
2016-01-15 12:57:09 +01:00
}
if ($theOrder >= $highestOrder) {
$highestOrder = $theOrder;
}
}
$orderOfNewFolder = $highestOrder + 1;
if ($orderOfNewFolder < 10) {
$orderOfNewFolder = '0' . $orderOfNewFolder;
}
Folder::mkdir($path . '/' . $orderOfNewFolder . '.' . $data['folder']);
Cache::clearCache('standard');
2016-01-15 12:57:09 +01:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
$multilang = $this->isMultilang();
$admin_route = $this->grav['config']->get('plugins.admin.route');
$redirect_url = '/' . ($multilang ? ($this->grav['session']->admin_lang) : '') . $admin_route . '/' . $this->view;
$this->setRedirect($redirect_url);
return true;
}
2016-02-12 10:16:28 +01:00
/**
* @param string $frontmatter
2016-02-12 10:16:28 +01:00
*
* @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;
}
2014-08-05 13:06:38 -07:00
/**
* Handles form and saves the input data if its valid.
*
* @return bool True if the action was performed.
*/
public function taskSave()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('save', $this->dataPermissions())) {
2016-01-21 09:46:38 +02:00
return false;
}
2014-08-05 13:06:38 -07:00
$data = $this->post;
2016-01-21 09:46:38 +02:00
$config = $this->grav['config'];
2014-08-05 13:06:38 -07:00
// Special handler for pages data.
if ($this->view == 'pages') {
2016-01-21 09:46:38 +02:00
/** @var Pages $pages */
$pages = $this->grav['pages'];
2014-08-05 13:06:38 -07:00
// Find new parent page in order to build the path.
$route = !isset($data['route']) ? dirname($this->admin->route) : $data['route'];
2015-08-05 18:10:15 -06:00
$obj = $this->admin->page(true);
// Ensure route is prefixed with a forward slash.
$route = '/' . ltrim($route, '/');
if (isset($data['frontmatter']) && !$this->checkValidFrontmatter($data['frontmatter'])) {
2016-03-05 12:11:13 +01:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_FRONTMATTER_COULD_NOT_SAVE'),
'error');
return false;
}
2015-12-29 19:31:02 +01:00
//Handle system.home.hide_in_urls
$hide_home_route = $config->get('system.home.hide_in_urls', false);
if ($hide_home_route) {
$home_route = $config->get('system.home.alias');
$topParent = $obj->topParent();
if (isset($topParent)) {
if ($topParent->route() == $home_route) {
2016-03-05 12:11:13 +01:00
$baseRoute = (string)$topParent->route();
if ($obj->parent() != $topParent) {
$baseRoute .= $obj->parent()->route();
}
$route = isset($baseRoute) ? $baseRoute : null;
}
}
}
$parent = $route && $route != '/' && $route != '.' ? $pages->dispatch($route, true) : $pages->root();
2015-05-13 14:29:17 +02:00
$original_slug = $obj->slug();
2015-08-14 06:23:16 -06:00
$original_order = intval(trim($obj->order(), '.'));
2015-05-13 14:29:17 +02:00
2014-08-05 13:06:38 -07:00
// 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());
2014-08-05 13:06:38 -07:00
// Reset slug and route. For now we do not support slug twig variable on save.
2015-05-13 14:29:17 +02:00
$obj->slug($original_slug);
2014-08-05 13:06:38 -07:00
$obj->validate();
$obj->filter();
2015-08-05 18:10:15 -06:00
// rename folder based on visible
2015-08-14 06:23:16 -06:00
if ($original_order == 1000) {
// increment order to force reshuffle
$obj->order($original_order + 1);
}
2015-08-14 14:28:24 -06:00
// add or remove numeric prefix based on ordering value
if (isset($data['ordering'])) {
if ($data['ordering'] && !$obj->order()) {
$obj->order(1001);
} elseif (!$data['ordering'] && $obj->order()) {
$obj->folder($obj->slug());
}
}
2015-08-14 14:28:24 -06:00
2014-08-05 13:06:38 -07:00
} else {
// Handle standard data types.
$obj = $this->prepareData();
$obj = $this->processFiles($obj);
2014-08-05 13:06:38 -07:00
$obj->validate();
$obj->filter();
2015-08-05 18:10:15 -06:00
}
2015-08-05 18:10:15 -06:00
if ($obj) {
// Event to manipulate data before saving the object
$this->grav->fireEvent('onAdminSave', new Event(['object' => &$obj]));
2015-08-14 06:23:16 -06:00
$obj->save(true);
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
2014-08-05 13:06:38 -07:00
}
2014-10-07 12:12:21 +03:00
if ($this->view != 'pages') {
// Force configuration reload.
/** @var Config $config */
$config = $this->grav['config'];
$config->reload();
if ($this->view === 'users') {
$this->grav['user']->merge(User::load($this->admin->route)->toArray());
}
2014-10-07 12:12:21 +03:00
}
2015-08-03 11:46:55 +02:00
// Always redirect if a page route was changed, to refresh it
2016-01-21 09:46:38 +02:00
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);
}
2015-08-20 16:03:54 +02:00
}
$admin_route = $this->grav['config']->get('plugins.admin.route');
2015-12-29 19:31:02 +01:00
//Handle system.home.hide_in_urls
$route = $obj->route();
$hide_home_route = $config->get('system.home.hide_in_urls', false);
if ($hide_home_route) {
$home_route = $config->get('system.home.alias');
$topParent = $obj->topParent();
if (isset($topParent)) {
if ($topParent->route() == $home_route) {
2016-03-05 12:11:13 +01:00
$route = (string)$topParent->route() . $route;
2015-12-29 19:31:02 +01:00
}
}
}
$redirect_url = '/' . ($multilang ? ($obj->language()) : '') . $admin_route . '/' . $this->view . $route;
$this->setRedirect($redirect_url);
2014-08-05 13:06:38 -07:00
}
return true;
}
/**
* Continue to the new page.
*
* @return bool True if the action was performed.
*/
public function taskContinue()
{
2014-10-10 15:25:07 +03:00
if ($this->view == 'users') {
$this->setRedirect("{$this->view}/{$this->post['username']}");
2016-03-05 12:11:13 +01:00
2014-10-10 15:25:07 +03:00
return true;
}
2015-10-20 16:36:39 +02:00
if ($this->view == 'groups') {
$this->setRedirect("{$this->view}/{$this->post['groupname']}");
2016-03-05 12:11:13 +01:00
2015-10-20 16:36:39 +02:00
return true;
}
2014-08-05 13:06:38 -07:00
if ($this->view != 'pages') {
return false;
}
$data = $this->post;
2014-09-17 11:54:57 +03:00
$route = $data['route'] != '/' ? $data['route'] : '';
2014-10-10 11:57:57 +03:00
$folder = ltrim($data['folder'], '_');
if (!empty($data['modular'])) {
$folder = '_' . $folder;
}
2014-08-05 13:06:38 -07:00
$path = $route . '/' . $folder;
2014-09-17 11:54:57 +03:00
$this->admin->session()->{$path} = $data;
// Store the name and route of a page, to be used prefilled defaults of the form in the future
$this->admin->session()->lastPageName = $data['name'];
$this->admin->session()->lastPageRoute = $data['route'];
2016-03-05 12:11:13 +01:00
$this->setRedirect("{$this->view}/" . ltrim($path, '/'));
2014-08-05 13:06:38 -07:00
return true;
}
/**
* Save page as a new copy.
*
* @return bool True if the action was performed.
* @throws \RuntimeException
*/
protected function taskCopy()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('copy page', ['admin.pages', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2014-08-05 13:06:38 -07:00
// Only applies to pages.
if ($this->view != 'pages') {
return false;
}
try {
2016-01-21 09:46:38 +02:00
/** @var Pages $pages */
$pages = $this->grav['pages'];
2014-08-05 13:06:38 -07:00
// And then get the current page.
$page = $this->admin->page(true);
// Find new parent page in order to build the path.
$parent = $page->parent() ?: $pages->root();
2014-08-05 13:06:38 -07:00
// Make a copy of the current page and fill the updated information into it.
$page = $page->copy($parent);
$this->preparePage($page);
2015-04-27 17:43:58 +02:00
// Make sure the header is loaded in case content was set through raw() (expert mode)
$page->header();
2014-08-05 13:06:38 -07:00
// Deal with folder naming conflicts, but limit number of searches to 99.
$break = 99;
while ($break > 0 && file_exists($page->filePath())) {
$break--;
$match = preg_split('/-(\d+)$/', $page->path(), 2, PREG_SPLIT_DELIM_CAPTURE);
2016-03-05 12:11:13 +01:00
$page->path($match[0] . '-' . (isset($match[1]) ? (int)$match[1] + 1 : 2));
2014-08-05 13:06:38 -07:00
// Reset slug and route. For now we do not support slug twig variable on save.
$page->slug('');
}
$page->save();
// Enqueue message and redirect to new location.
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_COPIED'), 'info');
2015-08-19 16:54:30 -06:00
$parent_route = $parent->route() ? '/' . ltrim($parent->route(), '/') : '';
2016-03-05 12:11:13 +01:00
$this->setRedirect($this->view . $parent_route . '/' . $page->slug());
2014-08-05 13:06:38 -07:00
} catch (\Exception $e) {
throw new \RuntimeException('Copying page failed on error: ' . $e->getMessage());
}
return true;
}
/**
* Reorder pages.
*
* @return bool True if the action was performed.
*/
protected function taskReorder()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('reorder pages', ['admin.pages', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2014-08-05 13:06:38 -07:00
// Only applies to pages.
if ($this->view != 'pages') {
return false;
}
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.REORDERING_WAS_SUCCESSFUL'), 'info');
2016-03-05 12:11:13 +01:00
2014-08-05 13:06:38 -07:00
return true;
}
/**
* Delete page.
*
* @return bool True if the action was performed.
* @throws \RuntimeException
*/
protected function taskDelete()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('delete page', ['admin.pages', 'admin.super'])) {
2016-01-21 09:46:38 +02:00
return false;
}
2014-08-05 13:06:38 -07:00
// 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());
}
2016-02-12 10:16:28 +01:00
Cache::clearCache('standard');
2015-08-05 19:11:09 -06:00
2014-09-30 17:41:45 -06:00
// Set redirect to either referrer or pages list.
2015-08-21 15:54:21 +02:00
$redirect = 'pages';
2014-08-05 13:06:38 -07:00
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_DELETED'), 'info');
2014-08-05 13:06:38 -07:00
$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.
*
* @return bool True if the action was performed.
*/
2016-01-10 17:17:04 +01:00
protected function taskSwitchlanguage()
{
2015-08-21 18:01:20 +02:00
$data = $this->post;
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';
}
2015-08-17 10:26:35 +02:00
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
$admin_route = $this->grav['config']->get('plugins.admin.route');
$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.
*/
2016-01-10 17:17:04 +01:00
protected function taskSaveas()
{
2015-09-11 15:00:03 +02:00
if (!$this->authorizeTask('save', $this->dataPermissions())) {
2016-01-21 09:46:38 +02:00
return false;
}
$data = $this->post;
$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 = 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();
2016-01-21 09:46:38 +02:00
$aPage = new Page();
2016-03-05 12:11:13 +01:00
$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;
}
/**
* Determine if the user can edit media
*
* @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;
}
2016-03-05 12:11:13 +01:00
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');
}
2016-03-05 12:11:13 +01:00
$this->post = ['_redirect' => 'media'];
return true;
}
/**
* Handle deleting a file from a blueprint
*
* @return bool True if the action was performed.
*/
protected function taskRemoveFileFromBlueprint()
{
$uri = $this->grav['uri'];
$this->taskRemoveMedia();
$field = $uri->param('field');
$blueprint = $uri->param('blueprint');
$this->grav['config']->set($blueprint . '.' . $field, '');
if (substr($blueprint, 0, 7) == 'plugins') {
Plugin::saveConfig(substr($blueprint, 8));
}
if (substr($blueprint, 0, 6) == 'themes') {
Theme::saveConfig(substr($blueprint, 7));
}
$redirect = base64_decode($uri->param('redirect'));
$route = $this->grav['config']->get('plugins.admin.route');
if (substr($redirect, 0, strlen($route)) == $route) {
$redirect = substr($redirect, strlen($route) + 1);
}
2016-03-05 12:11:13 +01:00
$this->post = ['_redirect' => $redirect];
return true;
}
2014-08-05 13:06:38 -07:00
/**
* Prepare and return POST data.
*
* @param array $post
2016-03-05 12:11:13 +01:00
*
2014-08-05 13:06:38 -07:00
* @return array
*/
protected function &getPost($post)
{
unset($post['task']);
// Decode JSON encoded fields and merge them to data.
if (isset($post['_json'])) {
$post = array_merge_recursive($post, $this->jsonDecode($post['_json']));
unset($post['_json']);
}
2016-03-05 12:11:13 +01:00
2014-08-05 13:06:38 -07:00
return $post;
}
/**
* Recursively JSON decode data.
*
* @param array $data
2016-03-05 12:11:13 +01:00
*
2014-08-05 13:06:38 -07:00
* @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);
}
}
2016-03-05 12:11:13 +01:00
2014-08-05 13:06:38 -07:00
return $data;
}
2015-07-30 12:20:25 +02:00
/**
* Sets the page redirect.
*
* @param string $path The path to redirect to
2016-03-05 12:11:13 +01:00
* @param int $code The HTTP redirect code
2015-07-30 12:20:25 +02:00
*/
2014-12-10 10:23:22 -07:00
protected function setRedirect($path, $code = 303)
{
2014-08-05 13:06:38 -07:00
$this->redirect = $path;
2016-03-05 12:11:13 +01:00
$this->redirectCode = $code;
2014-08-05 13:06:38 -07:00
}
2015-07-30 12:20:25 +02:00
/**
* Gets the configuration data for a given view & post
*
* @return object
*/
2014-08-05 13:06:38 -07:00
protected function prepareData()
{
$type = trim("{$this->view}/{$this->admin->route}", '/');
$data = $this->admin->data($type, $this->post);
return $data;
}
2015-07-30 12:20:25 +02:00
/**
* 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 '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 'pages':
$permissions[] = 'admin.pages';
break;
}
return $permissions;
}
2015-07-30 12:20:25 +02:00
/**
* Prepare a page to be stored: update its folder, name, template, header and content
*
* @param \Grav\Common\Page\Page $page
* @param bool $clean_header
2016-03-05 12:11:13 +01:00
* @param string $language
2015-07-30 12:20:25 +02:00
*/
2016-03-05 12:11:13 +01:00
protected function preparePage(Page $page, $clean_header = false, $language = '')
2014-08-05 13:06:38 -07:00
{
$input = $this->post;
2015-08-14 14:28:24 -06:00
if (isset($input['order'])) {
2016-03-05 12:11:13 +01:00
$order = max(0, (int)isset($input['order']) ? $input['order'] : $page->value('order'));
2015-08-14 14:28:24 -06:00
$ordering = $order ? sprintf('%02d.', $order) : '';
2016-03-05 12:11:13 +01:00
$slug = empty($input['folder']) ? $page->value('folder') : (string)$input['folder'];
2015-08-14 14:28:24 -06:00
$page->folder($ordering . $slug);
}
if (isset($input['name']) && !empty($input['name'])) {
2016-03-05 12:11:13 +01:00
$type = (string)strtolower($input['name']);
$name = preg_replace('|.*/|', '', $type);
if ($language) {
$name .= '.' . $language;
} else {
$language = $this->grav['language'];
if ($language->enabled()) {
$name .= '.' . $language->getLanguage();
}
}
$name .= '.md';
2014-10-08 19:55:50 +03:00
$page->name($name);
$page->template($type);
// unset some header things, template for now as we've just set that
if (isset($input['header']['template'])) {
unset($input['header']['template']);
}
2014-10-08 15:14:46 +03:00
}
2015-07-30 12:20:25 +02:00
// Special case for Expert mode: build the raw, unset content
2014-09-20 15:34:35 -06:00
if (isset($input['frontmatter']) && isset($input['content'])) {
2016-03-05 12:11:13 +01:00
$page->raw("---\n" . (string)$input['frontmatter'] . "\n---\n" . (string)$input['content']);
2014-09-20 15:34:35 -06:00
unset($input['content']);
2014-08-05 13:06:38 -07:00
}
if (isset($input['header'])) {
$header = $input['header'];
2015-08-04 19:28:42 +02:00
2016-03-05 12:11:13 +01:00
foreach ($header as $key => $value) {
2015-08-04 19:28:42 +02:00
if ($key == 'metadata') {
2015-08-14 06:41:43 -06:00
foreach ($header['metadata'] as $key2 => $value2) {
2015-08-04 19:28:42 +02:00
if (isset($input['toggleable_header']['metadata'][$key2]) && !$input['toggleable_header']['metadata'][$key2]) {
$header['metadata'][$key2] = '';
}
}
2015-08-14 06:41:43 -06:00
} elseif ($key == 'taxonomy') {
foreach ($header[$key] as $taxkey => $taxonomy) {
2015-08-14 14:28:24 -06:00
if (is_array($taxonomy) && count($taxonomy) == 1 && trim($taxonomy[0]) == '') {
2015-08-14 06:41:43 -06:00
unset($header[$key][$taxkey]);
}
}
2015-08-04 19:28:42 +02:00
} else {
if (isset($input['toggleable_header'][$key]) && !$input['toggleable_header'][$key]) {
2015-08-14 06:23:16 -06:00
$header[$key] = null;
2015-08-04 19:28:42 +02:00
}
}
}
if ($clean_header) {
2016-03-05 12:11:13 +01:00
$header = Utils::arrayFilterRecursive($header, function ($k, $v) {
2015-08-03 17:04:48 -06:00
return !(is_null($v) || $v === '');
});
}
2016-03-05 12:11:13 +01:00
$page->header((object)$header);
$page->frontmatter(Yaml::dump((array)$page->header()));
2014-08-05 13:06:38 -07:00
}
2015-07-30 12:20:25 +02:00
// Fill content last because it also renders the output.
2014-08-05 13:06:38 -07:00
if (isset($input['content'])) {
2016-03-05 12:11:13 +01:00
$page->rawMarkdown((string)$input['content']);
2014-08-05 13:06:38 -07:00
}
}
2015-07-30 12:20:25 +02:00
/**
* Checks if the user is allowed to perform the given task with its associated permissions
*
2016-03-05 12:11:13 +01:00
* @param string $task The task to execute
* @param array $permissions The permissions given
*
2015-07-30 12:20:25 +02:00
* @return bool True if authorized. False if not.
*/
2015-09-11 15:00:03 +02:00
protected function authorizeTask($task = '', $permissions = [])
{
2015-09-11 15:00:03 +02:00
if (!$this->admin->authorize($permissions)) {
2016-03-05 12:11:13 +01:00
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;
}
2014-08-05 13:06:38 -07:00
}