modif comtabilite

This commit is contained in:
2019-01-16 16:23:31 +01:00
parent 6b741a9666
commit 9312edc3ae
1844 changed files with 158848 additions and 55874 deletions
@@ -2,10 +2,9 @@
namespace Grav\Plugin\Admin\Twig;
use Grav\Common\Grav;
use Grav\Common\Yaml;
use Grav\Common\Language\Language;
use Grav\Common\Page\Page;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Parser;
class AdminTwigExtension extends \Twig_Extension
{
@@ -32,6 +31,7 @@ class AdminTwigExtension extends \Twig_Extension
new \Twig_SimpleFilter('toYaml', [$this, 'toYamlFilter']),
new \Twig_SimpleFilter('fromYaml', [$this, 'fromYamlFilter']),
new \Twig_SimpleFilter('adminNicetime', [$this, 'adminNicetimeFilter']),
new \Twig_SimpleFilter('nested', [$this, 'nestedFilter']),
];
}
@@ -43,6 +43,23 @@ class AdminTwigExtension extends \Twig_Extension
];
}
public function nestedFilter($current, $name)
{
$path = explode('.', trim($name, '.'));
foreach ($path as $field) {
if (is_object($current) && isset($current->{$field})) {
$current = $current->{$field};
} elseif (is_array($current) && isset($current[$field])) {
$current = $current[$field];
} else {
return null;
}
}
return $current;
}
public function cloneFunc($obj)
{
return clone $obj;
@@ -81,7 +98,7 @@ class AdminTwigExtension extends \Twig_Extension
return $this->grav['admin']->translate($args, $lang);
}
public function toYamlFilter($value, $inline = true)
public function toYamlFilter($value, $inline = null)
{
return Yaml::dump($value, $inline);
@@ -89,8 +106,7 @@ class AdminTwigExtension extends \Twig_Extension
public function fromYamlFilter($value)
{
$yaml = new Parser();
return $yaml->parse($value);
return Yaml::parse($value);
}
public function adminNicetimeFilter($date, $long_strings = true)
+16 -14
View File
@@ -27,7 +27,7 @@ use RocketTheme\Toolbox\ResourceLocator\UniformResourceIterator;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RocketTheme\Toolbox\Session\Message;
use RocketTheme\Toolbox\Session\Session;
use Symfony\Component\Yaml\Yaml;
use Grav\Common\Yaml;
use Composer\Semver\Semver;
use PicoFeed\Reader\Reader;
@@ -170,11 +170,11 @@ class Admin
/** @var \DirectoryIterator $directory */
foreach (new \DirectoryIterator($path) as $file) {
if ($file->isDir() || $file->isDot() || Utils::startsWith($file->getBasename(), '.')) {
if ($file->isDir() || $file->isDot() || Utils::startsWith($file->getFilename(), '.')) {
continue;
}
$lang = basename($file->getBasename(), '.yaml');
$lang = $file->getBasename('.yaml');
$languages[$lang] = LanguageCodes::getNativeName($lang);
@@ -202,7 +202,7 @@ class Admin
if ($file->isDir() || !preg_match('/^[^.].*.yaml$/', $file->getFilename())) {
continue;
}
$configurations[] = basename($file->getBasename(), '.yaml');
$configurations[] = $file->getBasename('.yaml');
}
return $configurations;
@@ -365,7 +365,7 @@ class Admin
$userKey = isset($credentials['username']) ? (string)$credentials['username'] : '';
$ipKey = Uri::ip();
$redirect = isset($post['redirect']) ? $post['redirect'] : $this->uri->route();
$redirect = isset($post['redirect']) ? $post['redirect'] : $this->base . $this->route;
// Check if the current IP has been used in failed login attempts.
$attempts = count($rateLimiter->getAttempts($ipKey, 'ip'));
@@ -392,11 +392,9 @@ class Admin
if ($user->authorized) {
$event->defMessage('PLUGIN_ADMIN.LOGIN_LOGGED_IN', 'info');
$event->defRedirect($redirect);
$event->defRedirect(isset($post['redirect']) ? $post['redirect'] : $redirect);
} else {
$this->session->redirect = $redirect;
$event->defRedirect($this->uri->route());
}
} else {
if ($user->authorized) {
@@ -406,7 +404,7 @@ class Admin
}
}
$event->defRedirect($this->uri->route());
$event->defRedirect($redirect);
$message = $event->getMessage();
if ($message) {
@@ -597,7 +595,8 @@ class Admin
}
if (!$post) {
$post = isset($_POST['data']) ? $_POST['data'] : [];
$post = $this->grav['uri']->post();
$post = isset($post['data']) ? $post['data'] : [];
}
// Check to see if a data type is plugin-provided, before looking into core ones
@@ -671,10 +670,10 @@ class Admin
$obj->file = $file;
$obj->page = $this->grav['pages']->get(dirname($obj->path));
$filename = pathinfo($obj->title)['filename'];
$filename = str_replace(['@3x', '@2x'], '', $filename);
if (isset(pathinfo($obj->title)['extension'])) {
$filename .= '.' . pathinfo($obj->title)['extension'];
$fileInfo = pathinfo($obj->title);
$filename = str_replace(['@3x', '@2x'], '', $fileInfo['filename']);
if (isset($fileInfo['extension'])) {
$filename .= '.' . $fileInfo['extension'];
}
if ($obj->page && isset($obj->page->media()[$filename])) {
@@ -1420,6 +1419,9 @@ class Admin
$path = "/{$path}";
}
// Fix for entities in path causing looping...
$path = urldecode($path);
$page = $path ? $pages->dispatch($path, true) : $pages->root();
if (!$page) {
@@ -2,9 +2,12 @@
namespace Grav\Plugin\Admin;
use Grav\Common\Config\Config;
use Grav\Common\Data\Data;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Media\Interfaces\MediaInterface;
use Grav\Common\Page\Media;
use Grav\Common\Page\Pages;
use Grav\Common\Utils;
use Grav\Common\Plugin;
use Grav\Common\Theme;
@@ -199,6 +202,29 @@ class AdminBaseController
$this->redirectCode = $code;
}
/**
* Sends JSON response and terminates the call.
*
* @param array $response
* @param int $code
* @return bool
*/
protected function sendJsonResponse(array $response, $code = 200)
{
// Make sure nothing extra gets written to the response.
while (ob_get_level()) {
ob_end_clean();
}
// JSON response.
http_response_code($code);
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
echo json_encode($response);
exit();
}
/**
* Handles ajax upload for files.
* Stores in a flash object the temporary file and deals with potential file errors.
@@ -225,10 +251,10 @@ class AdminBaseController
$upload = $this->normalizeFiles($_FILES['data'], $settings->name);
$filename = trim($upload->file->name);
$filename = $upload->file->name;
// Handle bad filenames.
if (strtr($filename, "\t\n\r\0\x0b", '_____') !== $filename || rtrim($filename, '. ') !== $filename || preg_match('|\.php|', $filename)) {
if (!Utils::checkFilename($filename)) {
$this->admin->json_response = [
'status' => 'error',
'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD', null),
@@ -259,7 +285,7 @@ class AdminBaseController
}
// Handle errors and breaks without proceeding further
if ($upload->file->error != UPLOAD_ERR_OK) {
if ($upload->file->error !== UPLOAD_ERR_OK) {
$this->admin->json_response = [
'status' => 'error',
'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD', null),
@@ -285,6 +311,9 @@ class AdminBaseController
$accepted = false;
$errors = [];
// Do not trust mimetype sent by the browser
$mime = Utils::getMimeByFilename($upload->file->name);
foreach ((array)$settings->accept as $type) {
// Force acceptance of any file when star notation
if ($type === '*') {
@@ -293,15 +322,24 @@ class AdminBaseController
}
$isMime = strstr($type, '/');
$find = str_replace('*', '.*', $type);
$find = str_replace(['.', '*'], ['\.', '.*'], $type);
$match = preg_match('#' . $find . '$#', $isMime ? $upload->file->type : $upload->file->name);
if (!$match) {
$message = $isMime ? 'The MIME type "' . $upload->file->type . '"' : 'The File Extension';
$errors[] = $message . ' for the file "' . $upload->file->name . '" is not an accepted.';
$accepted |= false;
if ($isMime) {
$match = preg_match('#' . $find . '$#', $mime);
if (!$match) {
$errors[] = 'The MIME type "' . $mime . '" for the file "' . $upload->file->name . '" is not an accepted.';
} else {
$accepted = true;
break;
}
} else {
$accepted |= true;
$match = preg_match('#' . $find . '$#', $upload->file->name);
if (!$match) {
$errors[] = 'The File Extension for the file "' . $upload->file->name . '" is not an accepted.';
} else {
$accepted = true;
break;
}
}
}
@@ -366,7 +404,7 @@ class AdminBaseController
// Generate random name if required
if ($settings->random_name) { // TODO: document
$extension = pathinfo($upload->file->name)['extension'];
$extension = pathinfo($upload->file->name, PATHINFO_EXTENSION);
$upload->file->name = Utils::generateRandomString(15) . '.' . $extension;
}
@@ -717,9 +755,9 @@ class AdminBaseController
} else {
$new_data = $files;
}
if (isset($data['header'][$init_key])) {
if (isset($obj->header()->{$init_key})) {
$obj->modifyHeader($init_key,
array_replace_recursive([], $data['header'][$init_key], $new_data));
array_replace_recursive([], $obj->header()->{$init_key}, $new_data));
} else {
$obj->modifyHeader($init_key, $new_data);
}
@@ -743,30 +781,44 @@ class AdminBaseController
return false;
}
$data = $this->view === 'pages' ? $this->admin->page(true) : $this->prepareData([]);
$settings = $data->blueprints()->schema()->getProperty($this->post['name']);
$data = $this->view === 'pages' ? $this->admin->page(true) : $this->prepareData([]);
if (null === $data) {
return false;
}
if (method_exists($data, 'blueprints')) {
$settings = $data->blueprints()->schema()->getProperty($this->post['name']);
} elseif (method_exists($data, 'getBlueprint')) {
$settings = $data->getBlueprint()->schema()->getProperty($this->post['name']);
}
if (isset($settings['folder'])) {
$folder = $settings['folder'];
} else {
$folder = '@self';
$folder = 'self@';
}
// Do not use self@ outside of pages
if ($this->view !== 'pages' && in_array($folder, ['@self', 'self@', '@self@'])) {
$this->admin->json_response = [
'status' => 'error',
'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_PREVENT_SELF', null), $folder)
];
if (!$data instanceof MediaInterface) {
$this->admin->json_response = [
'status' => 'error',
'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_PREVENT_SELF', null), $folder)
];
return false;
return false;
}
$media = $data->getMedia();
} else {
// Set destination
$folder = Folder::getRelativePath(rtrim($folder, '/'));
$folder = $this->admin->getPagePathFromToken($folder);
$media = new Media($folder);
}
// Set destination
$folder = Folder::getRelativePath(rtrim($folder, '/'));
$folder = $this->admin->getPagePathFromToken($folder);
$media = new Media($folder);
$available_files = [];
$metadata = [];
$thumbs = [];
@@ -859,7 +911,29 @@ class AdminBaseController
$type = $uri->param('type');
$field = $uri->param('field');
$this->taskRemoveMedia();
// Get Blueprint
$settings = (object) $this->admin->blueprints($blueprint)->schema()->getProperty($field);
// Get destination
if ($this->grav['locator']->isStream($settings->destination)) {
$destination = $this->grav['locator']->findResource($settings->destination, false, true);
} else {
$destination = Folder::getRelativePath(rtrim($settings->destination, '/'));
$destination = $this->admin->getPagePathFromToken($destination);
}
// Not in path
if (!Utils::startsWith($path, $destination)) {
$this->admin->json_response = [
'status' => 'error',
'message' => 'Path not valid for this data type'
];
return false;
}
// Only remove files from correct destination...
$this->taskRemoveMedia($destination . '/' . basename($path));
if ($type === 'pages') {
$page = $this->admin->page(true, $proute);
@@ -876,9 +950,11 @@ class AdminBaseController
$page->save();
} else {
$blueprint_prefix = $type === 'config' ? '' : $type . '.';
$blueprint_name = str_replace(['config/', '/blueprints'], '', $blueprint);
$blueprint_field = $blueprint_prefix . $blueprint_name . '.' . $field;
$files = $this->grav['config']->get($blueprint_field);
if ($files) {
@@ -919,15 +995,17 @@ class AdminBaseController
*
* @return bool True if the action was performed
*/
public function taskRemoveMedia()
public function taskRemoveMedia($filename = null)
{
if (!$this->canEditMedia()) {
return false;
}
$filename = base64_decode($this->grav['uri']->param('route'));
if (!$filename) {
$filename = base64_decode($this->route);
if (is_null($filename)) {
$filename = base64_decode($this->grav['uri']->param('route'));
if (!$filename) {
$filename = base64_decode($this->route);
}
}
$file = File::instance($filename);
+199 -97
View File
@@ -14,17 +14,18 @@ use Grav\Common\Page\Medium\Medium;
use Grav\Common\Page\Page;
use Grav\Common\Page\Pages;
use Grav\Common\Page\Collection;
use Grav\Common\Security;
use Grav\Common\User\User;
use Grav\Common\Utils;
use Grav\Common\Backup\ZipBackup;
use Grav\Plugin\Admin\Twig\AdminTwigExtension;
use Grav\Plugin\Login\TwoFactorAuth\TwoFactorAuth;
use Grav\Common\Yaml;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\File\File;
use RocketTheme\Toolbox\File\JsonFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
/**
* Class AdminController
@@ -465,7 +466,7 @@ class AdminController extends AdminBaseController
/**
* Handles updating Grav
*
* @return bool True if the action was performed
* @return bool False if user has no permissions.
*/
public function taskUpdategrav()
{
@@ -478,14 +479,14 @@ class AdminController extends AdminBaseController
$result = Gpm::selfupgrade();
if ($result) {
$this->admin->json_response = [
$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 = [
$json_response = [
'status' => 'error',
'type' => 'updategrav',
'version' => GRAV_VERSION,
@@ -493,7 +494,7 @@ class AdminController extends AdminBaseController
];
}
return true;
return $this->sendJsonResponse($json_response);
}
/**
@@ -611,14 +612,18 @@ class AdminController extends AdminBaseController
$reorder = true;
$data = (array)$this->data;
$this->grav['twig']->twig_vars['current_form_data'] = $data;
// Special handler for user data.
if ($this->view === 'user') {
if (!$this->grav['user']->exists()) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.NO_USER_EXISTS'),'error');
return false;
}
if (!$this->admin->authorize(['admin.super', 'admin.users'])) {
//not admin.super or admin.users
// no user file or 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');
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' save.','error');
return false;
}
}
@@ -643,13 +648,25 @@ class AdminController extends AdminBaseController
// Ensure route is prefixed with a forward slash.
$route = '/' . ltrim($route, '/');
// Check for valid frontmatter
if (isset($data['frontmatter']) && !$this->checkValidFrontmatter($data['frontmatter'])) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_FRONTMATTER_COULD_NOT_SAVE'),
'error');
return false;
}
// XSS Checks for page content
$xss_whitelist = $this->grav['config']->get('security.xss_whitelist', 'admin.super');
if (!$this->admin->authorize($xss_whitelist)) {
$check_what = ['header' => isset($data['header']) ? $data['header'] : '', 'frontmatter' => isset($data['frontmatter']) ? $data['frontmatter'] : '', 'content' => isset($data['content']) ? $data['content'] : ''];
$results = Security::detectXssFromArray($check_what);
if (!empty($results)) {
$this->admin->setMessage('<i class="fa fa-ban"></i> ' . $this->admin->translate('PLUGIN_ADMIN.XSS_ONSAVE_ISSUE'),
'error');
return false;
}
}
$parent = $route && $route !== '/' && $route !== '.' && $route !== '/.' ? $pages->dispatch($route, true) : $pages->root();
$original_order = (int)trim($obj->order(), '.');
@@ -758,16 +775,8 @@ class AdminController extends AdminBaseController
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) {
Yaml::parse($frontmatter);
} catch (\RuntimeException $e) {
return false;
}
@@ -874,6 +883,10 @@ class AdminController extends AdminBaseController
protected function taskGetNewsFeed()
{
if (!$this->authorizeTask('dashboard', ['admin.login', 'admin.super'])) {
return false;
}
$cache = $this->grav['cache'];
if ($this->post['refresh'] === 'true') {
@@ -910,11 +923,13 @@ class AdminController extends AdminBaseController
} catch (\Exception $e) {
$this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
return;
return false;
}
}
$this->admin->json_response = ['status' => 'success', 'feed_data' => $feed_data];
return true;
}
/**
@@ -922,6 +937,10 @@ class AdminController extends AdminBaseController
*/
protected function taskGetUpdates()
{
if (!$this->authorizeTask('dashboard', ['admin.login', 'admin.super'])) {
return false;
}
$data = $this->post;
$flush = (isset($data['flush']) && $data['flush'] == true) ? true : false;
@@ -954,12 +973,17 @@ class AdminController extends AdminBaseController
];
} else {
$this->admin->json_response = ['status' => 'error', 'message' => 'Cannot connect to the GPM'];
return false;
}
} catch (\Exception $e) {
$this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
return false;
}
return true;
}
/**
@@ -968,12 +992,16 @@ class AdminController extends AdminBaseController
*/
protected function taskGetNotifications()
{
if (!$this->authorizeTask('dashboard', ['admin.login', 'admin.super'])) {
return false;
}
$cache = $this->grav['cache'];
if (!(bool)$this->grav['config']->get('system.cache.enabled') || !$notifications = $cache->fetch('notifications')) {
//No notifications cache (first time)
$this->admin->json_response = ['status' => 'success', 'notifications' => [], 'need_update' => true];
return;
return true;
}
$need_update = false;
@@ -990,7 +1018,7 @@ class AdminController extends AdminBaseController
} catch (\Exception $e) {
$this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
return;
return false;
}
$this->admin->json_response = [
@@ -998,6 +1026,8 @@ class AdminController extends AdminBaseController
'notifications' => $notifications,
'need_update' => $need_update
];
return true;
}
/**
@@ -1007,6 +1037,10 @@ class AdminController extends AdminBaseController
*/
protected function taskProcessNotifications()
{
if (!$this->authorizeTask('notifications', ['admin.login', 'admin.super'])) {
return false;
}
$cache = $this->grav['cache'];
$data = $this->post;
@@ -1156,8 +1190,8 @@ class AdminController extends AdminBaseController
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
];
echo json_encode($json_response);
exit;
return $this->sendJsonResponse($json_response, 403);
}
//check if there are packages that have this as a dependency. Abort and show which ones
@@ -1172,8 +1206,8 @@ class AdminController extends AdminBaseController
}
$json_response = ['status' => 'error', 'message' => $message];
echo json_encode($json_response);
exit;
return $this->sendJsonResponse($json_response, 200);
}
try {
@@ -1181,8 +1215,8 @@ class AdminController extends AdminBaseController
$result = Gpm::uninstall($package, []);
} catch (\Exception $e) {
$json_response = ['status' => 'error', 'message' => $e->getMessage()];
echo json_encode($json_response);
exit;
return $this->sendJsonResponse($json_response, 200);
}
if ($result) {
@@ -1191,16 +1225,16 @@ class AdminController extends AdminBaseController
'dependencies' => $dependencies,
'message' => $this->admin->translate(is_string($result) ? $result : 'PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL')
];
echo json_encode($json_response);
exit;
return $this->sendJsonResponse($json_response, 200);
}
$json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED')
];
echo json_encode($json_response);
exit;
return $this->sendJsonResponse($json_response, 200);
}
/**
@@ -1215,6 +1249,15 @@ class AdminController extends AdminBaseController
$package_name = isset($data['package_name']) ? $data['package_name'] : '';
$current_version = isset($data['current_version']) ? $data['current_version'] : '';
if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) {
$json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
];
$this->sendJsonResponse($json_response, 403);
}
$url = "https://getgrav.org/download/{$type}s/$slug/$current_version";
$result = Gpm::directInstall($url);
@@ -1344,7 +1387,7 @@ class AdminController extends AdminBaseController
}
$download = urlencode(base64_encode($backup));
$url = rtrim($this->grav['uri']->rootUrl(true), '/') . '/' . trim($this->admin->base,
$url = rtrim($this->grav['uri']->rootUrl(false), '/') . '/' . trim($this->admin->base,
'/') . '/task' . $param_sep . 'backup/download' . $param_sep . $download . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form');
$log->content([
@@ -1574,6 +1617,8 @@ class AdminController extends AdminBaseController
{
$this->uri = $this->uri ?: $this->grav['uri'];
$uri = $this->uri->post('uri');
$order = $this->uri->post('order') ?: null;
if ($uri) {
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
@@ -1584,8 +1629,11 @@ class AdminController extends AdminBaseController
$media_path = $page ? $page->path() : null;
}
if ($order) {
$order = array_map('trim', explode(',', $order));
}
return $media_path ? new Media($media_path) : null;
return $media_path ? new Media($media_path, $order) : null;
}
/**
@@ -1646,6 +1694,19 @@ class AdminController extends AdminBaseController
return false;
}
$filename = $_FILES['file']['name'];
// Handle bad filenames.
if (!Utils::checkFilename($filename)) {
$this->admin->json_response = [
'status' => 'error',
'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD'),
$filename, 'Bad filename')
];
return false;
}
$grav_limit = $config->get('system.media.upload_limit', 0);
// You should also check filesize here.
if ($grav_limit > 0 && $_FILES['file']['size'] > $grav_limit) {
@@ -1659,18 +1720,13 @@ class AdminController extends AdminBaseController
// Check extension
$fileParts = pathinfo($_FILES['file']['name']);
$fileExt = '';
if (isset($fileParts['extension'])) {
$fileExt = strtolower($fileParts['extension']);
}
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
// If not a supported type, return
if (!$fileExt || !$config->get("media.types.{$fileExt}")) {
if (!$extension || !$config->get("media.types.{$extension}")) {
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $fileExt
'message' => $this->admin->translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $extension
];
return false;
@@ -1687,9 +1743,16 @@ class AdminController extends AdminBaseController
return false;
}
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$path = $media->path();
if ($locator->isStream($path)) {
$path = $locator->findResource($path, true, true);
}
// Upload it
if (!move_uploaded_file($_FILES['file']['tmp_name'],
sprintf('%s/%s', $media->path(), $_FILES['file']['name']))
sprintf('%s/%s', $path, $filename))
) {
$this->admin->json_response = [
'status' => 'error',
@@ -1701,13 +1764,12 @@ class AdminController extends AdminBaseController
// Add metadata if needed
$include_metadata = Grav::instance()['config']->get('system.media.auto_metadata_exif', false);
$filename = $fileParts['basename'];
$filename = str_replace(['@3x', '@2x'], '', $filename);
$basename = str_replace(['@3x', '@2x'], '', pathinfo($filename, PATHINFO_BASENAME));
$metadata = [];
if ($include_metadata && isset($media[$filename])) {
$img_metadata = $media[$filename]->metadata();
if ($include_metadata && isset($media[$basename])) {
$img_metadata = $media[$basename]->metadata();
if ($img_metadata) {
$metadata = $img_metadata;
}
@@ -1750,6 +1812,11 @@ class AdminController extends AdminBaseController
$filename = !empty($this->post['filename']) ? $this->post['filename'] : null;
// Handle bad filenames.
if (!Utils::checkFilename($filename)) {
$filename = null;
}
if (!$filename) {
$this->admin->json_response = [
'status' => 'error',
@@ -1759,7 +1826,13 @@ class AdminController extends AdminBaseController
return false;
}
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$targetPath = $media->path() . '/' . $filename;
if ($locator->isStream($targetPath)) {
$targetPath = $locator->findResource($targetPath, true, true);
}
$fileParts = pathinfo($filename);
$found = false;
@@ -1781,7 +1854,13 @@ class AdminController extends AdminBaseController
// Remove Extra Files
foreach (scandir($media->path(), SCANDIR_SORT_NONE) as $file) {
if (preg_match("/{$fileParts['filename']}@\d+x\.{$fileParts['extension']}(?:\.meta\.yaml)?$|{$filename}\.meta\.yaml$/", $file)) {
$result = unlink($media->path() . '/' . $file);
$targetPath = $media->path() . '/' . $file;
if ($locator->isStream($targetPath)) {
$targetPath = $locator->findResource($targetPath, true, true);
}
$result = unlink($targetPath);
if (!$result) {
$this->admin->json_response = [
@@ -1825,9 +1904,9 @@ class AdminController extends AdminBaseController
*/
protected function taskProcessMarkdown()
{
/*if (!$this->authorizeTask('process markdown', ['admin.pages', 'admin.super'])) {
return;
}*/
if (!$this->authorizeTask('process markdown', ['admin.pages', 'admin.super'])) {
return false;
}
try {
$page = $this->admin->page(true);
@@ -1843,6 +1922,7 @@ class AdminController extends AdminBaseController
$this->preparePage($page, true);
$page->header();
$page->templateFormat('html');
// Add theme template paths to Twig loader
$template_paths = $this->grav['locator']->findResources('theme://templates');
@@ -2153,6 +2233,10 @@ class AdminController extends AdminBaseController
*/
protected function taskSwitchlanguage()
{
if (!$this->authorizeTask('switch language', ['admin.pages', 'admin.super'])) {
return false;
}
$data = (array)$this->data;
if (isset($data['lang'])) {
@@ -2176,6 +2260,68 @@ class AdminController extends AdminBaseController
$admin_route = $this->admin->base;
$this->setRedirect('/' . $language . $admin_route . '/' . $redirect);
return true;
}
/**
* Handle direct install.
*/
protected function taskDirectInstall()
{
if (!$this->authorizeTask('install', ['admin.super'])) {
return false;
}
$file_path = isset($this->data['file_path']) ? $this->data['file_path'] : null ;
if (isset($_FILES['uploaded_file'])) {
// Check $_FILES['file']['error'] value.
switch ($_FILES['uploaded_file']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.NO_FILES_SENT'), 'error');
return false;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT'), 'error');
return false;
case UPLOAD_ERR_NO_TMP_DIR:
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR'), 'error');
return false;
default:
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNKNOWN_ERRORS'), 'error');
return false;
}
$file_path = $_FILES['uploaded_file']['tmp_name'];
// Handle bad filenames.
if (!Utils::checkFilename(basename($file_path))) {
$this->admin->json_response = [
'status' => 'error',
'message' => $this->admin->translate('PLUGIN_ADMIN.UNKNOWN_ERRORS')
];
return false;
}
}
$result = Gpm::directInstall($file_path);
if ($result === true) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info');
} else {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED') . ': ' . $result,
'error');
}
$this->setRedirect('/tools');
return true;
}
/**
@@ -2249,49 +2395,5 @@ class AdminController extends AdminBaseController
return $filename . '.md';
}
/**
* Handle direct install.
*/
protected function taskDirectInstall()
{
$file_path = isset($this->data['file_path']) ? $this->data['file_path'] : null ;
if (isset($_FILES['uploaded_file'])) {
// Check $_FILES['file']['error'] value.
switch ($_FILES['uploaded_file']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.NO_FILES_SENT'), 'error');
return false;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT'), 'error');
return false;
case UPLOAD_ERR_NO_TMP_DIR:
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR'), 'error');
return false;
default:
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNKNOWN_ERRORS'), 'error');
return false;
}
$file_path = $_FILES['uploaded_file']['tmp_name'];
}
$result = Gpm::directInstall($file_path);
if ($result === true) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info');
} else {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED') . ': ' . $result,
'error');
}
$this->setRedirect('/tools');
return true;
}
}