"There is no error, the file uploaded with success",
1 => "The uploaded file exceeds the max upload size",
2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML",
3 => "The uploaded file was only partially uploaded",
4 => "No file was uploaded",
6 => "Missing a temporary folder",
7 => "Failed to write file to disk",
8 => "A PHP extension stopped the file upload"
];
/**
* @param Grav $grav
* @param string $view
* @param string $task
* @param string $route
* @param array $post
*/
public function initialize(Grav $grav = null, $view = null, $task = null, $route = null, $post = null)
{
$this->grav = $grav;
$this->view = $view;
$this->task = $task ? $task : 'display';
if (isset($post['data'])) {
$this->data = $this->getPost($post['data']);
unset($post['data']);
} else {
// Backwards compatibility for Form plugin <= 1.2
$this->data = $this->getPost($post);
}
$this->post = $this->getPost($post);
$this->route = $route;
$this->admin = $this->grav['admin'];
$this->grav->fireEvent('onAdminControllerInit', new Event(['controller' => &$this]));
}
/**
* Handle login.
*
* @return bool True if the action was performed.
* @todo LOGIN
*/
protected function taskLogin()
{
$this->data['username'] = strip_tags(strtolower($this->data['username']));
if ($this->admin->authenticate($this->data, $this->post)) {
// should never reach here, redirects first
} else {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.LOGIN_FAILED'), 'error');
}
return true;
}
/**
* @return bool
* @todo LOGIN
*/
protected function task2faverify()
{
/** @var TwoFactorAuth $twoFa */
$twoFa = $this->grav['login']->twoFactorAuth();
$user = $this->grav['user'];
$secret = isset($user->twofa_secret) ? $user->twofa_secret : null;
if (!(isset($this->data['2fa_code']) && $secret && $twoFa->verifyCode($secret, $this->data['2fa_code']))) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.2FA_FAILED'), 'error');
return true;
}
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.LOGIN_LOGGED_IN'), 'info');
$user->authenticated = true;
$this->grav->redirect($this->post['redirect']);
return true;
}
/**
* @param null $secret
* @return bool
* @todo LOGIN
*/
public function taskRegenerate2FASecret()
{
if (!$this->authorizeTask('regenerate 2FA Secret', ['admin.login'])) {
return false;
}
try {
/** @var User $user */
$user = $this->grav['user'];
/** @var TwoFactorAuth $twoFa */
$twoFa = $this->grav['login']->twoFactorAuth();
$secret = $twoFa->createSecret(160);
$image = $twoFa->getQrImageData($user->username, $secret);
// Save secret into the user file.
$file = $user->file();
if ($file->exists()) {
$content = $file->content();
$content['twofa_secret'] = $secret;
$file->save($content);
$file->free();
}
// Change secret in the session.
$user->twofa_secret = $secret;
$this->admin->json_response = ['status' => 'success', 'image' => $image, 'secret' => preg_replace('|(\w{4})|', '\\1 ', $secret)];
} catch (\Exception $e) {
$this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
return false;
}
return true;
}
/**
* Handle logout.
*
* @return bool True if the action was performed.
* @todo LOGIN
*/
protected function taskLogout()
{
$message = $this->admin->translate('PLUGIN_ADMIN.LOGGED_OUT');
$this->admin->session()->invalidate()->start();
$this->grav['session']->setFlashCookieObject(Admin::TMP_COOKIE_NAME, ['message' => $message, 'status' => 'info']);
$this->setRedirect('/');
return true;
}
/**
* Handle the reset password action.
*
* @return bool True if the action was performed.
* @todo LOGIN
*/
public function taskReset()
{
$data = $this->data;
if (isset($data['password'])) {
$username = isset($data['username']) ? strip_tags(strtolower($data['username'])) : null;
$user = $username ? User::load($username) : null;
$password = isset($data['password']) ? $data['password'] : null;
$token = isset($data['token']) ? $data['token'] : null;
if ($user && $user->exists() && !empty($user->reset)) {
list($good_token, $expire) = explode('::', $user->reset);
if ($good_token === $token) {
if (time() > $expire) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_LINK_EXPIRED'), 'error');
$this->setRedirect('/forgot');
return true;
}
unset($user->hashed_password, $user->reset);
$user->password = $password;
$user->validate();
$user->filter();
$user->save();
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_PASSWORD_RESET'), 'info');
$this->setRedirect('/');
return true;
}
}
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_INVALID_LINK'), 'error');
$this->setRedirect('/forgot');
return true;
}
$user = $this->grav['uri']->param('user');
$token = $this->grav['uri']->param('token');
if (empty($user) || empty($token)) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_INVALID_LINK'), 'error');
$this->setRedirect('/forgot');
return true;
}
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_NEW_PASSWORD'), 'info');
$this->admin->forgot = ['username' => $user, 'token' => $token];
return true;
}
/**
* Handle the email password recovery procedure.
*
* @return bool True if the action was performed.
* @todo LOGIN
*/
protected function taskForgot()
{
$param_sep = $this->grav['config']->get('system.param_sep', ':');
$post = $this->post;
$data = $this->data;
$login = $this->grav['login'];
$username = isset($data['username']) ? strip_tags(strtolower($data['username'])) : '';
$user = !empty($username) ? User::load($username) : null;
if (!isset($this->grav['Email'])) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error');
$this->setRedirect($post['redirect']);
return true;
}
if (!$user || !$user->exists()) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'),
'info');
$this->setRedirect($post['redirect']);
return true;
}
if (empty($user->email)) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'),
'info');
$this->setRedirect($post['redirect']);
return true;
}
$count = $this->grav['config']->get('plugins.login.max_pw_resets_count', 0);
$interval =$this->grav['config']->get('plugins.login.max_pw_resets_interval', 2);
if ($login->isUserRateLimited($user, 'pw_resets', $count, $interval)) {
$this->admin->setMessage($this->admin->translate(['PLUGIN_LOGIN.FORGOT_CANNOT_RESET_IT_IS_BLOCKED', $user->email, $interval]), 'error');
$this->setRedirect($post['redirect']);
return true;
}
$token = md5(uniqid(mt_rand(), true));
$expire = time() + 604800; // next week
$user->reset = $token . '::' . $expire;
$user->save();
$author = $this->grav['config']->get('site.author.name', '');
$fullname = $user->fullname ?: $username;
$reset_link = rtrim($this->grav['uri']->rootUrl(true), '/') . '/' . trim($this->admin->base,
'/') . '/reset/task' . $param_sep . 'reset/user' . $param_sep . $username . '/token' . $param_sep . $token . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form');
$sitename = $this->grav['config']->get('site.title', 'Website');
$from = $this->grav['config']->get('plugins.email.from');
if (empty($from)) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error');
$this->setRedirect($post['redirect']);
return true;
}
$to = $user->email;
$subject = $this->admin->translate(['PLUGIN_ADMIN.FORGOT_EMAIL_SUBJECT', $sitename]);
$content = $this->admin->translate([
'PLUGIN_ADMIN.FORGOT_EMAIL_BODY',
$fullname,
$reset_link,
$author,
$sitename
]);
$body = $this->grav['twig']->processTemplate('email/base.html.twig', ['content' => $content]);
$message = $this->grav['Email']->message($subject, $body, 'text/html')->setFrom($from)->setTo($to);
$sent = $this->grav['Email']->send($message);
if ($sent < 1) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_FAILED_TO_EMAIL'), 'error');
} else {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'),
'info');
}
$this->setRedirect('/');
return true;
}
/**
* Enable a plugin.
*
* @return bool True if the action was performed.
*/
public function taskEnable()
{
if (!$this->authorizeTask('enable plugin', ['admin.plugins', 'admin.super'])) {
return false;
}
if ($this->view !== 'plugins') {
return false;
}
// Filter value and save it.
$this->post = ['enabled' => true];
$obj = $this->prepareData($this->post);
$obj->save();
$this->post = ['_redirect' => 'plugins'];
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_ENABLED_PLUGIN'), 'info');
return true;
}
/**
* Gets the configuration data for a given view & post
*
* @param array $data
*
* @return object
*/
protected function prepareData(array $data)
{
$type = trim("{$this->view}/{$this->admin->route}", '/');
$data = $this->admin->data($type, $data);
return $data;
}
/**
* Disable a plugin.
*
* @return bool True if the action was performed.
*/
public function taskDisable()
{
if (!$this->authorizeTask('disable plugin', ['admin.plugins', 'admin.super'])) {
return false;
}
if ($this->view !== 'plugins') {
return false;
}
// Filter value and save it.
$this->post = ['enabled' => false];
$obj = $this->prepareData($this->post);
$obj->save();
$this->post = ['_redirect' => 'plugins'];
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_DISABLED_PLUGIN'), 'info');
return true;
}
/**
* Set the default theme.
*
* @return bool True if the action was performed.
*/
public function taskActivate()
{
if (!$this->authorizeTask('activate theme', ['admin.themes', 'admin.super'])) {
return false;
}
if ($this->view !== 'themes') {
return false;
}
$this->post = ['_redirect' => 'themes'];
// Make sure theme exists (throws exception)
$name = $this->route;
$this->grav['themes']->get($name);
// Store system configuration.
$system = $this->admin->data('config/system');
$system->set('pages.theme', $name);
$system->save();
// Force configuration reload and save.
/** @var Config $config */
$config = $this->grav['config'];
$config->reload()->save();
$config->set('system.pages.theme', $name);
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_CHANGED_THEME'), 'info');
return true;
}
/**
* Handles updating Grav
*
* @return bool True if the action was performed
*/
public function taskUpdategrav()
{
if (!$this->authorizeTask('install grav', ['admin.super'])) {
return false;
}
$gpm = Gpm::GPM();
$version = $gpm->grav->getVersion();
$result = Gpm::selfupgrade();
if ($result) {
$this->admin->json_response = [
'status' => 'success',
'type' => 'updategrav',
'version' => $version,
'message' => $this->admin->translate('PLUGIN_ADMIN.GRAV_WAS_SUCCESSFULLY_UPDATED_TO') . ' ' . $version
];
} else {
$this->admin->json_response = [
'status' => 'error',
'type' => 'updategrav',
'version' => GRAV_VERSION,
'message' => $this->admin->translate('PLUGIN_ADMIN.GRAV_UPDATE_FAILED') . '
' . Installer::lastErrorMsg()
];
}
return true;
}
/**
* Handles uninstalling plugins and themes
*
* @deprecated
*
* @return bool True if the action was performed
*/
public function taskUninstall()
{
$type = $this->view === 'plugins' ? 'plugins' : 'themes';
if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) {
return false;
}
$package = $this->route;
$result = Gpm::uninstall($package, []);
if ($result) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL'), 'info');
} else {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED'), 'error');
}
$this->post = ['_redirect' => $this->view];
return true;
}
/**
* Handles creating an empty page folder (without markdown file)
*
* @return bool True if the action was performed.
*/
public function taskSaveNewFolder()
{
if (!$this->authorizeTask('save', $this->dataPermissions())) {
return false;
}
$data = (array)$this->data;
if ($data['route'] === '/') {
$path = $this->grav['locator']->findResource('page://');
} else {
$path = $this->grav['page']->find($data['route'])->path();
}
$orderOfNewFolder = $this->getNextOrderInFolder($path);
$new_path = $path . '/' . $orderOfNewFolder . '.' . $data['folder'];
Folder::create($new_path);
Cache::clearCache('standard');
$this->grav->fireEvent('onAdminAfterSaveAs', new Event(['path' => $new_path]));
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
$multilang = $this->isMultilang();
$admin_route = $this->admin->base;
$redirect_url = '/' . ($multilang ? ($this->grav['session']->admin_lang) : '') . $admin_route . '/' . $this->view;
$this->setRedirect($redirect_url);
return true;
}
/**
* Get the next available ordering number in a folder
*
* @param $path
*
* @return string the correct order string to prepend
*/
public static function getNextOrderInFolder($path)
{
$files = Folder::all($path, ['recursive' => false]);
$highestOrder = 0;
foreach ($files as $file) {
preg_match(PAGE_ORDER_PREFIX_REGEX, $file, $order);
if (isset($order[0])) {
$theOrder = (int)trim($order[0], '.');
} else {
$theOrder = 0;
}
if ($theOrder >= $highestOrder) {
$highestOrder = $theOrder;
}
}
$orderOfNewFolder = $highestOrder + 1;
if ($orderOfNewFolder < 10) {
$orderOfNewFolder = '0' . $orderOfNewFolder;
}
return $orderOfNewFolder;
}
/**
* Handles form and saves the input data if its valid.
*
* @return bool True if the action was performed.
*/
public function taskSave()
{
if (!$this->authorizeTask('save', $this->dataPermissions())) {
return false;
}
$reorder = true;
$data = (array)$this->data;
// Special handler for user data.
if ($this->view === 'user') {
if (!$this->admin->authorize(['admin.super', 'admin.users'])) {
//not admin.super or admin.users
if ($this->prepareData($data)->username !== $this->grav['user']->username) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' save.',
'error');
return false;
}
}
}
// Special handler for pages data.
if ($this->view === 'pages') {
/** @var Pages $pages */
$pages = $this->grav['pages'];
// Find new parent page in order to build the path.
$route = !isset($data['route']) ? dirname($this->admin->route) : $data['route'];
/** @var Page $obj */
$obj = $this->admin->page(true);
if (!isset($data['folder']) || !$data['folder']) {
$data['folder'] = $obj->slug();
$this->data['folder'] = $obj->slug();
}
// Ensure route is prefixed with a forward slash.
$route = '/' . ltrim($route, '/');
if (isset($data['frontmatter']) && !$this->checkValidFrontmatter($data['frontmatter'])) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_FRONTMATTER_COULD_NOT_SAVE'),
'error');
return false;
}
$parent = $route && $route !== '/' && $route !== '.' && $route !== '/.' ? $pages->dispatch($route, true) : $pages->root();
$original_order = (int)trim($obj->order(), '.');
try {
// Change parent if needed and initialize move (might be needed also on ordering/folder change).
$obj = $obj->move($parent);
$this->preparePage($obj, false, $obj->language());
$obj->validate();
} catch (\Exception $e) {
$this->admin->setMessage($e->getMessage(), 'error');
return false;
}
$obj->filter();
// rename folder based on visible
if ($original_order === 1000) {
// increment order to force reshuffle
$obj->order($original_order + 1);
}
if (isset($data['order']) && !empty($data['order'])) {
$reorder = explode(',', $data['order']);
}
// add or remove numeric prefix based on ordering value
if (isset($data['ordering'])) {
if ($data['ordering'] && !$obj->order()) {
$obj->order($this->getNextOrderInFolder($obj->parent()->path()));
$reorder = false;
} elseif (!$data['ordering'] && $obj->order()) {
$obj->folder($obj->slug());
}
}
} else {
// Handle standard data types.
$obj = $this->prepareData($data);
try {
$obj->validate();
} catch (\Exception $e) {
$this->admin->setMessage($e->getMessage(), 'error');
return false;
}
$obj->filter();
}
$obj = $this->storeFiles($obj);
if ($obj) {
// Event to manipulate data before saving the object
$this->grav->fireEvent('onAdminSave', new Event(['object' => &$obj]));
$obj->save($reorder);
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
$this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $obj]));
}
if ($this->view !== 'pages') {
// Force configuration reload.
/** @var Config $config */
$config = $this->grav['config'];
$config->reload();
if ($this->view === 'user') {
if ($obj->username === $this->grav['user']->username) {
//Editing current user. Reload user object
unset($this->grav['user']->avatar);
$this->grav['user']->merge(User::load($this->admin->route)->toArray());
}
}
}
// Always redirect if a page route was changed, to refresh it
if ($obj instanceof Page) {
if (method_exists($obj, 'unsetRouteSlug')) {
$obj->unsetRouteSlug();
}
$multilang = $this->isMultilang();
if ($multilang) {
if (!$obj->language()) {
$obj->language($this->grav['session']->admin_lang);
}
}
$admin_route = $this->admin->base;
$route = $obj->rawRoute();
$redirect_url = ($multilang ? '/' . $obj->language() : '') . $admin_route . '/' . $this->view . $route;
$this->setRedirect($redirect_url);
}
return true;
}
/**
* @param string $frontmatter
*
* @return bool
*/
public function checkValidFrontmatter($frontmatter)
{
try {
// Try native PECL YAML PHP extension first if available.
if (function_exists('yaml_parse')) {
$saved = @ini_get('yaml.decode_php');
@ini_set('yaml.decode_php', 0);
@yaml_parse("---\n" . $frontmatter . "\n...");
@ini_set('yaml.decode_php', $saved);
} else {
Yaml::parse($frontmatter);
}
} catch (ParseException $e) {
return false;
}
return true;
}
/**
* Continue to the new page.
*
* @return bool True if the action was performed.
*/
public function taskContinue()
{
$data = (array)$this->data;
if ($this->view === 'users') {
$username = strip_tags(strtolower($data['username']));
$this->setRedirect("{$this->view}/{$username}");
return true;
}
if ($this->view === 'groups') {
$this->setRedirect("{$this->view}/{$data['groupname']}");
return true;
}
if ($this->view !== 'pages') {
return false;
}
$route = $data['route'] !== '/' ? $data['route'] : '';
$folder = $data['folder'];
// Handle @slugify-{field} value, automatically slugifies the specified field
if (0 === strpos($folder, '@slugify-')) {
$folder = \Grav\Plugin\Admin\Utils::slug($data[substr($folder, 9)]);
}
$folder = ltrim($folder, '_');
if (!empty($data['modular'])) {
$folder = '_' . $folder;
}
$path = $route . '/' . $folder;
$this->admin->session()->{$path} = $data;
// Store the name and route of a page, to be used pre-filled defaults of the form in the future
$this->admin->session()->lastPageName = $data['name'];
$this->admin->session()->lastPageRoute = $data['route'];
$this->setRedirect("{$this->view}/" . ltrim($path, '/'));
return true;
}
/**
* Toggle the gpm.releases setting
*/
protected function taskGpmRelease()
{
if (!$this->authorizeTask('configuration', ['admin.configuration', 'admin.super'])) {
return false;
}
// Default release state
$release = 'stable';
$reload = false;
// Get the testing release value if set
if ($this->post['release'] === 'testing') {
$release = 'testing';
}
$config = $this->grav['config'];
$current_release = $config->get('system.gpm.releases');
// If the releases setting is different, save it in the system config
if ($current_release !== $release) {
$data = new Data\Data($config->get('system'));
$data->set('gpm.releases', $release);
// Get the file location
$file = CompiledYamlFile::instance($this->grav['locator']->findResource('config://system.yaml'));
$data->file($file);
// Save the configuration
$data->save();
$config->reload();
$reload = true;
}
$this->admin->json_response = ['status' => 'success', 'reload' => $reload];
return true;
}
/**
* Keep alive
*/
protected function taskKeepAlive()
{
exit();
}
protected function taskGetNewsFeed()
{
$cache = $this->grav['cache'];
if ($this->post['refresh'] === 'true') {
$cache->delete('news-feed');
}
$feed_data = $cache->fetch('news-feed');
if (!$feed_data) {
try {
$feed = $this->admin->getFeed();
if (is_object($feed)) {
require_once __DIR__ . '/../classes/Twig/AdminTwigExtension.php';
$adminTwigExtension = new AdminTwigExtension;
$feed_items = $feed->getItems();
// Feed should only every contain 10, but just in case!
if (count($feed_items) > 10) {
$feed_items = array_slice($feed_items, 0, 10);
}
foreach ($feed_items as $item) {
$datetime = $adminTwigExtension->adminNicetimeFilter($item->getDate()->getTimestamp());
$feed_data[] = '