diff --git a/admin.php b/admin.php index 50615262..e4710b91 100644 --- a/admin.php +++ b/admin.php @@ -16,6 +16,7 @@ use Grav\Plugin\Admin\AdminTwigExtension; use Grav\Plugin\Admin\Popularity; use Grav\Plugin\Admin\Themes; use Grav\Plugin\Admin\AdminController; +use Grav\Plugin\Admin\Twig\AdminTwigExtension; use Grav\Plugin\Login\Login; use RocketTheme\Toolbox\Event\Event; use RocketTheme\Toolbox\Session\Session; @@ -118,7 +119,7 @@ class AdminPlugin extends Plugin // Autoloader spl_autoload_register(function ($class) { if (Utils::startsWith($class, 'Grav\Plugin\Admin')) { - require_once __DIR__ .'/classes/' . strtolower(basename(str_replace("\\", "/", $class))) . '.php'; + require_once __DIR__ .'/classes/' . strtolower(basename(str_replace("\\", '/', $class))) . '.php'; } }); @@ -220,7 +221,7 @@ class AdminPlugin extends Plugin $data = []; $username = $form->value('username'); - if ($form->value('password1') != $form->value('password2')) { + if ($form->value('password1') !== $form->value('password2')) { $this->grav->fireEvent('onFormValidationError', new Event([ 'form' => $form, 'message' => $this->grav['language']->translate('PLUGIN_LOGIN.PASSWORDS_DO_NOT_MATCH') @@ -245,11 +246,8 @@ class AdminPlugin extends Plugin } } - unset($data['password1']); - unset($data['password2']); - - // Don't store the username: that is part of the filename - unset($data['username']); + // Don't store plain text password or username (part of the filename). + unset($data['password1'], $data['password2'], $data['username']); // Extra lowercase to ensure file is saved lowercase $username = strtolower($username); @@ -313,7 +311,7 @@ class AdminPlugin extends Plugin } // Turn on Twig autoescaping - if (method_exists($this->grav['twig'], 'setAutoescape') && $this->grav['uri']->param('task') != 'processmarkdown') { + if (method_exists($this->grav['twig'], 'setAutoescape') && $this->grav['uri']->param('task') !== 'processmarkdown') { $this->grav['twig']->setAutoescape(true); } @@ -361,9 +359,9 @@ class AdminPlugin extends Plugin $this->session->expert = $this->session->expert ?: false; // set session variable if it's passed via the url - if ($this->uri->param('mode') == 'expert') { + if ($this->uri->param('mode') === 'expert') { $this->session->expert = true; - } elseif ($this->uri->param('mode') == 'normal') { + } elseif ($this->uri->param('mode') === 'normal') { $this->session->expert = false; } @@ -391,7 +389,7 @@ class AdminPlugin extends Plugin $this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task'); if ($task) { $this->initializeController($task, $post); - } elseif ($this->template == 'logs' && $this->route) { + } elseif ($this->template === 'logs' && $this->route) { // Display RAW error message. echo $this->admin->logEntry(); exit(); @@ -637,7 +635,7 @@ class AdminPlugin extends Plugin } // Can't access path directly... - if ($path && $path != 'register') { + if ($path && $path !== 'register') { $array = explode('/', $path, 2); $this->template = array_shift($array); $this->route = array_shift($array); @@ -768,8 +766,9 @@ class AdminPlugin extends Plugin */ public function onTwigExtensions() { - require_once(__DIR__ . '/twig/AdminTwigExtension.php'); - $this->grav['twig']->twig->addExtension(new AdminTwigExtension()); + require_once __DIR__ . '/classes/Twig/AdminTwigExtension.php'; + + $this->grav['twig']->twig->addExtension(new AdminTwigExtension); } /** @@ -779,23 +778,19 @@ class AdminPlugin extends Plugin */ public function isAdminPath() { - if ($this->uri->route() == $this->base || substr($this->uri->route(), 0, - strlen($this->base) + 1) == $this->base . '/' - ) { - return true; - } + $route = $this->uri->route(); - return false; + return $route === $this->base || 0 === strpos($route, $this->base . '/'); } public function onAdminAfterSave(Event $event) { // Special case to redirect after changing the admin route to avoid 'breaking' $obj = $event['object']; - if (!is_null($event['object'])) { + if (null !== $obj) { $blueprint = $obj->blueprints()->getFilename(); - if ($blueprint == 'admin/blueprints' && isset($obj->route) && $this->admin_route !== $obj->route) { + if ($blueprint === 'admin/blueprints' && isset($obj->route) && $this->admin_route !== $obj->route) { $redirect = preg_replace('/^' . str_replace('/','\/',$this->admin_route) . '/',$obj->route,$this->uri->path()); $this->grav->redirect($redirect); } @@ -827,7 +822,7 @@ class AdminPlugin extends Plugin // Clear flash objects for previously uploaded files // whenever the user switches page / reloads // ignoring any JSON / extension call - if (is_null($this->uri->extension()) && $this->admin->task !== 'save') { + if ($this->admin->task !== 'save' && empty($this->uri->extension())) { // Discard any previously uploaded files session. // and if there were any uploaded file, remove them from the filesystem if ($flash = $this->session->getFlashObject('files-upload')) { @@ -884,7 +879,7 @@ class AdminPlugin extends Plugin // First filter by configuration $hideTypes = Grav::instance()['config']->get('plugins.admin.hide_page_types', []); - foreach ($hideTypes as $type) { + foreach ((array) $hideTypes as $type) { unset($types[$type]); } @@ -908,7 +903,7 @@ class AdminPlugin extends Plugin $types = Pages::modularTypes(); // First filter by configuration - $hideTypes = Grav::instance()['config']->get('plugins.admin.hide_modular_page_types', []); + $hideTypes = (array) Grav::instance()['config']->get('plugins.admin.hide_modular_page_types', []); foreach ($hideTypes as $type) { unset($types[$type]); } diff --git a/classes/Twig/AdminTwigExtension.php b/classes/Twig/AdminTwigExtension.php new file mode 100644 index 00000000..838c3e0d --- /dev/null +++ b/classes/Twig/AdminTwigExtension.php @@ -0,0 +1,175 @@ +grav = Grav::instance(); + $this->lang = $this->grav['user']->language; + } + + public function getFilters() + { + return [ + new \Twig_SimpleFilter('tu', [$this, 'tuFilter']), + new \Twig_SimpleFilter('toYaml', [$this, 'toYamlFilter']), + new \Twig_SimpleFilter('fromYaml', [$this, 'fromYamlFilter']), + new \Twig_SimpleFilter('adminNicetime', [$this, 'adminNicetimeFilter']), + ]; + } + + public function getFunctions() + { + return [ + new \Twig_SimpleFunction('getPageUrl', [$this, 'getPageUrl'], ['needs_context' => true]), + new \Twig_SimpleFunction('clone', [$this, 'cloneFunc']), + ]; + } + + public function cloneFunc($obj) + { + return clone $obj; + } + + public function getPageUrl($context, $page) + { + $page_route = trim($page->rawRoute(), '/'); + $page_lang = $page->language(); + $base_url = $context['base_url']; + $base_url_simple = $context['base_url_simple']; + $admin_lang = Grav::instance()['session']->admin_lang ?: 'en'; + + if ($page_lang && $page_lang != $admin_lang) { + $page_url = $base_url_simple . '/' . $page_lang . '/' . $context['admin_route'] . '/pages/' . $page_route; + } else { + $page_url = $base_url . '/pages/' . $page_route; + } + + return $page_url; + } + + public function tuFilter() + { + $args = func_get_args(); + $numargs = count($args); + $lang = null; + + if (($numargs === 3 && is_array($args[1])) || ($numargs === 2 && !is_array($args[1]))) { + $lang = array_pop($args); + } elseif ($numargs === 2 && is_array($args[1])) { + $subs = array_pop($args); + $args = array_merge($args, $subs); + } + + return $this->grav['admin']->translate($args, $lang); + } + + public function toYamlFilter($value, $inline = true) + { + return Yaml::dump($value, $inline); + + } + + public function fromYamlFilter($value) + { + $yaml = new Parser(); + return $yaml->parse($value); + } + + public function adminNicetimeFilter($date, $long_strings = true) + { + if (empty($date)) { + return $this->grav['admin']->translate('NICETIME.NO_DATE_PROVIDED', null, true); + } + + if ($long_strings) { + $periods = [ + 'NICETIME.SECOND', + 'NICETIME.MINUTE', + 'NICETIME.HOUR', + 'NICETIME.DAY', + 'NICETIME.WEEK', + 'NICETIME.MONTH', + 'NICETIME.YEAR', + 'NICETIME.DECADE' + ]; + } else { + $periods = [ + 'NICETIME.SEC', + 'NICETIME.MIN', + 'NICETIME.HR', + 'NICETIME.DAY', + 'NICETIME.WK', + 'NICETIME.MO', + 'NICETIME.YR', + 'NICETIME.DEC' + ]; + } + + $lengths = ['60', '60', '24', '7', '4.35', '12', '10']; + + $now = time(); + + // check if unix timestamp + if ((string)(int)$date === (string)$date) { + $unix_date = $date; + } else { + $unix_date = strtotime($date); + } + + // check validity of date + if (empty($unix_date)) { + return $this->grav['admin']->translate('NICETIME.BAD_DATE', null, true); + } + + // is it future date or past date + if ($now > $unix_date) { + $difference = $now - $unix_date; + $tense = $this->grav['admin']->translate('NICETIME.AGO', null, true); + + } else { + $difference = $unix_date - $now; + $tense = $this->grav['admin']->translate('NICETIME.FROM_NOW', null, true); + } + + $len = count($lengths) - 1; + for ($j = 0; $difference >= $lengths[$j] && $j < $len; $j++) { + $difference /= $lengths[$j]; + } + + $difference = round($difference); + + if ($difference !== 1) { + $periods[$j] .= '_PLURAL'; + } + + if ($this->grav['language']->getTranslation($this->grav['user']->language, + $periods[$j] . '_MORE_THAN_TWO') + ) { + if ($difference > 2) { + $periods[$j] .= '_MORE_THAN_TWO'; + } + } + + $periods[$j] = $this->grav['admin']->translate($periods[$j], null, true); + + return "$difference $periods[$j] {$tense}"; + } + +} diff --git a/classes/admin.php b/classes/admin.php index bcc9ac0e..04c7681f 100644 --- a/classes/admin.php +++ b/classes/admin.php @@ -9,6 +9,7 @@ use Grav\Common\GPM\Licenses; use Grav\Common\GPM\Response; use Grav\Common\Grav; use Grav\Common\Language\LanguageCodes; +use Grav\Common\Page\Collection; use Grav\Common\Page\Page; use Grav\Common\Page\Pages; use Grav\Common\Plugins; @@ -16,6 +17,7 @@ use Grav\Common\Themes; use Grav\Common\Uri; use Grav\Common\User\User; use Grav\Common\Utils; +use Grav\Plugin\Admin\Twig\AdminTwigExtension; use Grav\Plugin\Admin\Utils as AdminUtils; use RocketTheme\Toolbox\Event\Event; use RocketTheme\Toolbox\File\File; @@ -214,7 +216,7 @@ class Admin public static function tools() { $tools = []; - $event = Grav::instance()->fireEvent('onAdminTools', new Event(['tools' => &$tools])); + Grav::instance()->fireEvent('onAdminTools', new Event(['tools' => &$tools])); return $tools; } @@ -227,7 +229,7 @@ class Admin public static function siteLanguages() { $languages = []; - $lang_data = Grav::instance()['config']->get('system.languages.supported', []); + $lang_data = (array) Grav::instance()['config']->get('system.languages.supported', []); foreach ($lang_data as $index => $lang) { $languages[$lang] = LanguageCodes::getNativeName($lang); @@ -282,6 +284,7 @@ class Admin $page = $pages->dispatch($route); $parent_route = null; if ($page) { + /** @var Page $parent */ $parent = $page->parent(); $parent_route = $parent->rawRoute(); } @@ -351,6 +354,7 @@ class Admin * @param array $post Additional form fields. * * @return bool + * @TODO LOGIN */ public function authenticate($data, $post) { @@ -365,7 +369,7 @@ class Admin } - if (!$this->user->authenticated && isset($data['username']) && isset($data['password'])) { + if (!$this->user->authenticated && isset($data['username'], $data['password'])) { // Perform RegEX check on submitted username to check for emails if (filter_var($data['username'], FILTER_VALIDATE_EMAIL)) { $user = AdminUtils::findUserByEmail($data['username']); @@ -420,6 +424,19 @@ class Admin return false; } + /** + * @return bool + * @todo LOGIN + */ + public static function doAnyUsersExist() + { + // check for existence of a user account + $account_dir = $file_path = Grav::instance()['locator']->findResource('account://'); + $user_check = glob($account_dir . '/*.yaml'); + + return $user_check ? true : false; + } + /** * Add message into the session queue. * @@ -490,9 +507,9 @@ class Admin if ($translation) { if (count($args) >= 1) { return vsprintf($translation, $args); - } else { - return $translation; } + + return $translation; } } @@ -502,7 +519,7 @@ class Admin /** * Checks user authorisation to the action. * - * @param string $action + * @param string|string[] $action * * @return bool */ @@ -734,9 +751,9 @@ class Admin { if (method_exists($this->grav['pages'], 'accessLevels')) { return $this->grav['pages']->accessLevels(); - } else { - return []; } + + return []; } public function license($package_slug) @@ -773,7 +790,7 @@ class Admin $dependency = $dependency['name']; } - if (!in_array($dependency, $dependencies)) { + if (!in_array($dependency, $dependencies, true)) { if (!in_array($dependency, ['admin', 'form', 'login', 'email', 'php'])) { $dependencies[] = $dependency; } @@ -829,19 +846,16 @@ class Admin if ($local) { return $gpm->getInstalledPlugins(); - } else { - $plugins = $gpm->getRepositoryPlugins(); - if ($plugins) { - return $plugins->filter(function ( - $package, - $slug - ) use ($gpm) { - return !$gpm->isPluginInstalled($slug); - }); - } else { - return []; - } } + + $plugins = $gpm->getRepositoryPlugins(); + if ($plugins) { + return $plugins->filter(function ($package, $slug) use ($gpm) { + return !$gpm->isPluginInstalled($slug); + }); + } + + return []; } /** @@ -861,19 +875,16 @@ class Admin if ($local) { return $gpm->getInstalledThemes(); - } else { - $themes = $gpm->getRepositoryThemes(); - if ($themes) { - return $themes->filter(function ( - $package, - $slug - ) use ($gpm) { - return !$gpm->isThemeInstalled($slug); - }); - } else { - return []; - } } + + $themes = $gpm->getRepositoryThemes(); + if ($themes) { + return $themes->filter(function ($package, $slug) use ($gpm) { + return !$gpm->isThemeInstalled($slug); + }); + } + + return []; } /** @@ -928,9 +939,7 @@ class Admin return false; } - $dependencies = $this->gpm->getDependencies($packages); - - return $dependencies; + return $this->gpm->getDependencies($packages); } /** @@ -948,7 +957,7 @@ class Admin $latest = []; - if (is_null($pages->routes())) { + if (null === $pages->routes()) { return null; } @@ -986,6 +995,7 @@ class Admin { $file = File::instance($this->grav['locator']->findResource("log://{$this->route}.html")); $content = $file->content(); + $file->free(); return $content; } @@ -1030,11 +1040,7 @@ class Admin */ public function isTeamGrav($info) { - if (isset($info['author']['name']) && ($info['author']['name'] == 'Team Grav' || Utils::contains($info['author']['name'], 'Trilby Media'))) { - return true; - } else { - return false; - } + return isset($info['author']['name']) && ($info['author']['name'] === 'Team Grav' || Utils::contains($info['author']['name'], 'Trilby Media')); } /** @@ -1046,11 +1052,7 @@ class Admin */ public function isPremiumProduct($info) { - if (isset($info['premium'])) { - return true; - } else { - return false; - } + return isset($info['premium']); } /** @@ -1069,9 +1071,9 @@ class Admin $pinfo = preg_replace('%^.*(.*).*$%ms', '$1', $pinfo); return $pinfo; - } else { - return 'phpinfo() method is not available on this server.'; } + + return 'phpinfo() method is not available on this server.'; } /** @@ -1107,7 +1109,8 @@ class Admin if ($this->validateDate($date, "$date_format $time_format")) { $guess[$date] = "$date_format $time_format"; break 2; - } elseif ($this->validateDate($date, "$time_format $date_format")) { + } + if ($this->validateDate($date, "$time_format $date_format")) { $guess[$date] = "$time_format $date_format"; break 2; } @@ -1182,9 +1185,10 @@ class Admin 'r' => 'llll ZZ', 'U' => 'X' ]; - $js_format = ""; + $js_format = ''; $escaping = false; - for ($i = 0; $i < strlen($php_format); $i++) { + $len = strlen($php_format); + for ($i = 0; $i < $len; $i++) { $char = $php_format[$i]; if ($char === '\\') // PHP date format escaping character { @@ -1251,18 +1255,18 @@ class Admin $notifications = array_reverse($notifications); // Make adminNicetimeFilter available - require_once(__DIR__ . '/../twig/AdminTwigExtension.php'); - $adminTwigExtension = new AdminTwigExtension(); + require_once __DIR__ . '/../classes/Twig/AdminTwigExtension.php'; + $adminTwigExtension = new AdminTwigExtension; $filename = $this->grav['locator']->findResource('user://data/notifications/' . $this->grav['user']->username . YAML_EXT, true, true); - $read_notifications = CompiledYamlFile::instance($filename)->content(); + $read_notifications = (array)CompiledYamlFile::instance($filename)->content(); $notifications_processed = []; foreach ($notifications as $key => $notification) { $is_valid = true; - if (in_array($notification->id, $read_notifications)) { + if (in_array($notification->id, $read_notifications, true)) { $notification->read = true; } @@ -1272,7 +1276,7 @@ class Admin if ($is_valid && isset($notification->dependencies)) { foreach ($notification->dependencies as $dependency => $constraints) { - if ($dependency == 'grav') { + if ($dependency === 'grav') { if (!Semver::satisfies(GRAV_VERSION, $constraints)) { $is_valid = false; } @@ -1369,7 +1373,7 @@ class Admin /** @var Pages $pages */ $pages = $this->grav['pages']; - if ($path && $path[0] != '/') { + if ($path && $path[0] !== '/') { $path = "/{$path}"; } @@ -1378,14 +1382,14 @@ class Admin if (!$page) { $slug = basename($path); - if ($slug == '') { + if ($slug === '') { return null; } $ppath = str_replace('\\', '/', dirname($path)); // Find or create parent(s). - $parent = $this->getPage($ppath != '/' ? $ppath : ''); + $parent = $this->getPage($ppath !== '/' ? $ppath : ''); // Create page. $page = new Page; @@ -1396,7 +1400,7 @@ class Admin $pages->addPage($page, $path); // Set if Modular - $page->modularTwig($slug[0] == '_'); + $page->modularTwig($slug[0] === '_'); // Determine page type. if (isset($this->session->{$page->route()})) { @@ -1407,13 +1411,14 @@ class Admin $header = ['title' => $data['title']]; if (isset($data['visible'])) { - if ($data['visible'] == '' || $data['visible']) { + if ($data['visible'] === '' || $data['visible']) { // if auto (ie '') - $children = $page->parent()->children(); + $pageParent = $page->parent(); + $children = $pageParent ? $pageParent->children() : []; foreach ($children as $child) { if ($child->order()) { // set page order - $page->order(AdminController::getNextOrderInFolder($page->parent()->path())); + $page->order(AdminController::getNextOrderInFolder($pageParent->path())); break; } } @@ -1424,7 +1429,7 @@ class Admin } - if ($data['name'] == 'modular') { + if ($data['name'] === 'modular') { $header['body_classes'] = 'modular'; } @@ -1446,7 +1451,7 @@ class Admin $page->name($type . CONTENT_EXT); $page->header(); } - $page->modularTwig($slug[0] == '_'); + $page->modularTwig($slug[0] === '_'); } return $page; @@ -1466,9 +1471,7 @@ class Admin $reader = new Reader(); $parser = $reader->getParser($feed_url, $body, 'utf-8'); - $feed = $parser->execute(); - - return $feed; + return $parser->execute(); } @@ -1593,20 +1596,19 @@ class Admin * Get all the media of a type ('images' | 'audios' | 'videos' | 'files') * * @param string $type - * @param Page\Page $page + * @param Page|null $page * @param array $files * * @return array */ - private function getMediaOfType($type, $page, $page_files) { + private function getMediaOfType($type, Page $page = null, array $files) + { if ($page) { - -// $path = $page->path(); $media = $page->media(); $mediaOfType = $media->$type(); foreach($mediaOfType as $title => $file) { - $page_files[] = [ + $files[] = [ 'title' => $title, 'type' => $type, 'page_route' => $page->route(), @@ -1614,10 +1616,10 @@ class Admin ]; } - return $page_files; - } else { - return []; + return $files; } + + return []; } /** @@ -1722,10 +1724,11 @@ class Admin */ public function pages() { + /** @var Collection $pages */ $pages = $this->grav['pages']->all(); $pagesWithFiles = []; - if ($pages) foreach ($pages as $page) { + foreach ($pages as $page) { if (count($page->media()->all())) { $pagesWithFiles[] = $page; } @@ -1799,7 +1802,6 @@ class Admin */ public function getReferrer() { - $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null; - return $referrer; + return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null; } } diff --git a/classes/admincontroller.php b/classes/admincontroller.php index 12db0401..69aca93f 100644 --- a/classes/admincontroller.php +++ b/classes/admincontroller.php @@ -10,6 +10,7 @@ use Grav\Common\GPM\Installer; use Grav\Common\Grav; use Grav\Common\Data; use Grav\Common\Page\Media; +use Grav\Common\Page\Medium\Medium; use Grav\Common\Page\Page; use Grav\Common\Page\Pages; use Grav\Common\Page\Collection; @@ -193,7 +194,7 @@ class AdminController extends AdminBaseController return false; } - if ($this->view != 'plugins') { + if ($this->view !== 'plugins') { return false; } @@ -234,7 +235,7 @@ class AdminController extends AdminBaseController return false; } - if ($this->view != 'plugins') { + if ($this->view !== 'plugins') { return false; } @@ -260,7 +261,7 @@ class AdminController extends AdminBaseController return false; } - if ($this->view != 'themes') { + if ($this->view !== 'themes') { return false; } @@ -363,7 +364,7 @@ class AdminController extends AdminBaseController $data = (array)$this->data; - if ($data['route'] == '/') { + if ($data['route'] === '/') { $path = $this->grav['locator']->findResource('page://'); } else { $path = $this->grav['page']->find($data['route'])->path(); @@ -403,7 +404,7 @@ class AdminController extends AdminBaseController preg_match(PAGE_ORDER_PREFIX_REGEX, $file, $order); if (isset($order[0])) { - $theOrder = intval(trim($order[0], '.')); + $theOrder = (int)trim($order[0], '.'); } else { $theOrder = 0; } @@ -436,10 +437,8 @@ class AdminController extends AdminBaseController $reorder = true; $data = (array)$this->data; - $config = $this->grav['config']; - // Special handler for user data. - if ($this->view == 'user') { + 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) { @@ -452,7 +451,7 @@ class AdminController extends AdminBaseController } // Special handler for pages data. - if ($this->view == 'pages') { + if ($this->view === 'pages') { /** @var Pages $pages */ $pages = $this->grav['pages']; @@ -478,8 +477,8 @@ class AdminController extends AdminBaseController } - $parent = $route && $route != '/' && $route != '.' && $route != '/.' ? $pages->dispatch($route, true) : $pages->root(); - $original_order = intval(trim($obj->order(), '.')); + $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). @@ -495,7 +494,7 @@ class AdminController extends AdminBaseController $obj->filter(); // rename folder based on visible - if ($original_order == 1000) { + if ($original_order === 1000) { // increment order to force reshuffle $obj->order($original_order + 1); } @@ -539,14 +538,14 @@ class AdminController extends AdminBaseController $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $obj])); } - if ($this->view != 'pages') { + 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) { + 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()); @@ -610,27 +609,27 @@ class AdminController extends AdminBaseController { $data = (array)$this->data; - if ($this->view == 'users') { + if ($this->view === 'users') { $username = strip_tags(strtolower($data['username'])); $this->setRedirect("{$this->view}/{$username}"); return true; } - if ($this->view == 'groups') { + if ($this->view === 'groups') { $this->setRedirect("{$this->view}/{$data['groupname']}"); return true; } - if ($this->view != 'pages') { + if ($this->view !== 'pages') { return false; } - $route = $data['route'] != '/' ? $data['route'] : ''; + $route = $data['route'] !== '/' ? $data['route'] : ''; $folder = $data['folder']; // Handle @slugify-{field} value, automatically slugifies the specified field - if (substr($folder, 0, 9) == '@slugify-') { + if (0 === strpos($folder, '@slugify-')) { $folder = \Grav\Plugin\Admin\Utils::slug($data[substr($folder, 9)]); } $folder = ltrim($folder, '_'); @@ -716,7 +715,7 @@ class AdminController extends AdminBaseController $reload = false; // Get the testing release value if set - if ($this->post['release'] == 'testing') { + if ($this->post['release'] === 'testing') { $release = 'testing'; } @@ -724,12 +723,12 @@ class AdminController extends AdminBaseController $current_release = $config->get('system.gpm.releases'); // If the releases setting is different, save it in the system config - if ($current_release != $release) { + 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")); + $file = CompiledYamlFile::instance($this->grav['locator']->findResource('config://system.yaml')); $data->file($file); // Save the configuration @@ -755,7 +754,7 @@ class AdminController extends AdminBaseController { $cache = $this->grav['cache']; - if ($this->post['refresh'] == 'true') { + if ($this->post['refresh'] === 'true') { $cache->delete('news-feed'); } @@ -766,8 +765,8 @@ class AdminController extends AdminBaseController $feed = $this->admin->getFeed(); if (is_object($feed)) { - require_once(__DIR__ . '/../twig/AdminTwigExtension.php'); - $adminTwigExtension = new AdminTwigExtension(); + require_once __DIR__ . '/../classes/Twig/AdminTwigExtension.php'; + $adminTwigExtension = new AdminTwigExtension; $feed_items = $feed->getItems(); @@ -802,7 +801,7 @@ class AdminController extends AdminBaseController protected function taskGetUpdates() { $data = $this->post; - $flush = isset($data['flush']) && $data['flush'] == true ? true : false; + $flush = (isset($data['flush']) && $data['flush'] == true) ? true : false; if (isset($this->grav['session'])) { $this->grav['session']->close(); @@ -814,29 +813,29 @@ class AdminController extends AdminBaseController $resources_updates = $gpm->getUpdatable(); if ($gpm->grav != null) { $grav_updates = [ - "isUpdatable" => $gpm->grav->isUpdatable(), - "assets" => $gpm->grav->getAssets(), - "version" => GRAV_VERSION, - "available" => $gpm->grav->getVersion(), - "date" => $gpm->grav->getDate(), - "isSymlink" => $gpm->grav->isSymlink() + 'isUpdatable' => $gpm->grav->isUpdatable(), + 'assets' => $gpm->grav->getAssets(), + 'version' => GRAV_VERSION, + 'available' => $gpm->grav->getVersion(), + 'date' => $gpm->grav->getDate(), + 'isSymlink' => $gpm->grav->isSymlink() ]; $this->admin->json_response = [ - "status" => "success", - "payload" => [ - "resources" => $resources_updates, - "grav" => $grav_updates, - "installed" => $gpm->countInstalled(), + 'status' => 'success', + 'payload' => [ + 'resources' => $resources_updates, + 'grav' => $grav_updates, + 'installed' => $gpm->countInstalled(), 'flushed' => $flush ] ]; } else { - $this->admin->json_response = ["status" => "error", "message" => "Cannot connect to the GPM"]; + $this->admin->json_response = ['status' => 'error', 'message' => 'Cannot connect to the GPM']; } } catch (\Exception $e) { - $this->admin->json_response = ["status" => "error", "message" => $e->getMessage()]; + $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; } } @@ -966,7 +965,7 @@ class AdminController extends AdminBaseController return false; } - $result = Gpm::install(array_keys($dependencies), ['theme' => ($type == 'theme')]); + $result = Gpm::install(array_keys($dependencies), ['theme' => $type === 'theme']); if ($result) { $this->admin->json_response = ['status' => 'success', 'message' => 'Dependencies installed successfully']; @@ -996,7 +995,7 @@ class AdminController extends AdminBaseController } try { - $result = Gpm::install($package, ['theme' => ($type == 'theme')]); + $result = Gpm::install($package, ['theme' => $type === 'theme']); } catch (\Exception $e) { $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; @@ -1043,11 +1042,11 @@ class AdminController extends AdminBaseController $dependent_packages = $this->admin->getPackagesThatDependOnPackage($package); if (count($dependent_packages) > 0) { if (count($dependent_packages) > 1) { - $message = "The installed packages " . implode(', ', - $dependent_packages) . " depends on this package. Please remove those first."; + $message = 'The installed packages ' . implode(', ', + $dependent_packages) . ' depends on this package. Please remove those first.'; } else { - $message = "The installed package " . implode(', ', - $dependent_packages) . " depends on this package. Please remove it first."; + $message = 'The installed package ' . implode(', ', + $dependent_packages) . ' depends on this package. Please remove it first.'; } $json_response = ['status' => 'error', 'message' => $message]; @@ -1072,16 +1071,14 @@ class AdminController extends AdminBaseController ]; echo json_encode($json_response); exit; - } else { - $json_response = [ - 'status' => 'error', - 'message' => $this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED') - ]; - echo json_encode($json_response); - exit; } - return true; + $json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED') + ]; + echo json_encode($json_response); + exit; } /** @@ -1301,7 +1298,7 @@ class AdminController extends AdminBaseController $file = base64_decode(urldecode($download)); $backups_root_dir = $this->grav['locator']->findResource('backup://', true); - if (substr($file, 0, strlen($backups_root_dir)) !== $backups_root_dir) { + if (0 !== strpos($file, $backups_root_dir)) { header('HTTP/1.1 401 Unauthorized'); exit(); } @@ -1348,7 +1345,7 @@ class AdminController extends AdminBaseController protected function taskGetChildTypes() { if (!$this->authorizeTask('get childtypes', ['admin.pages', 'admin.super'])) { - return; + return false; } $data = $this->post; @@ -1356,6 +1353,7 @@ class AdminController extends AdminBaseController $rawroute = !empty($data['rawroute']) ? $data['rawroute'] : null; if ($rawroute) { + /** @var Page $page */ $page = $this->grav['pages']->dispatch($rawroute); if ($page) { @@ -1411,46 +1409,46 @@ class AdminController extends AdminBaseController ]; if (count(array_intersect($pageStates, $flags)) > 0) { - if (in_array('modular', $flags)) { + if (in_array('modular', $flags, true)) { $collection = $collection->modular(); } - if (in_array('nonmodular', $flags)) { + if (in_array('nonmodular', $flags, true)) { $collection = $collection->nonModular(); } - if (in_array('visible', $flags)) { + if (in_array('visible', $flags, true)) { $collection = $collection->visible(); } - if (in_array('nonvisible', $flags)) { + if (in_array('nonvisible', $flags, true)) { $collection = $collection->nonVisible(); } - if (in_array('routable', $flags)) { + if (in_array('routable', $flags, true)) { $collection = $collection->routable(); } - if (in_array('nonroutable', $flags)) { + if (in_array('nonroutable', $flags, true)) { $collection = $collection->nonRoutable(); } - if (in_array('published', $flags)) { + if (in_array('published', $flags, true)) { $collection = $collection->published(); } - if (in_array('nonpublished', $flags)) { + if (in_array('nonpublished', $flags, true)) { $collection = $collection->nonPublished(); } } foreach ($pageStates as $pageState) { - if (($pageState = array_search($pageState, $flags)) !== false) { + if (($pageState = array_search($pageState, $flags, true)) !== false) { unset($flags[$pageState]); } } // Filter by page type - if (count($flags)) { + if ($flags) { $types = []; $pageTypes = array_keys(Pages::pageTypes()); @@ -1467,7 +1465,7 @@ class AdminController extends AdminBaseController } // Filter by page type - if (count($flags)) { + if ($flags) { $accessLevels = $flags; $collection = $collection->ofOneOfTheseAccessLevels($accessLevels); } @@ -1522,6 +1520,10 @@ class AdminController extends AdminBaseController } $media_list = []; + /** + * @var string $name + * @var Medium $medium + */ foreach ($media->all() as $name => $medium) { $metadata = []; @@ -1542,7 +1544,7 @@ class AdminController extends AdminBaseController } /** - * @return bool + * @return Media */ protected function getMedia() { @@ -1845,14 +1847,14 @@ class AdminController extends AdminBaseController { $input = (array)$this->data; - if (isset($input['folder']) && $input['folder'] != $page->value('folder')) { + if (isset($input['folder']) && $input['folder'] !== $page->value('folder')) { $order = $page->value('order'); $ordering = $order ? sprintf('%02d.', $order) : ''; $page->folder($ordering . $input['folder']); } if (isset($input['name']) && !empty($input['name'])) { - $type = (string)strtolower($input['name']); + $type = strtolower($input['name']); $name = preg_replace('|.*/|', '', $type); if ($language) { $name .= '.' . $language; @@ -1868,7 +1870,7 @@ class AdminController extends AdminBaseController } // Special case for Expert mode: build the raw, unset content - if (isset($input['frontmatter']) && isset($input['content'])) { + if (isset($input['frontmatter'], $input['content'])) { $page->raw("---\n" . (string)$input['frontmatter'] . "\n---\n" . (string)$input['content']); unset($input['content']); // Handle header normally @@ -1876,13 +1878,13 @@ class AdminController extends AdminBaseController $header = $input['header']; foreach ($header as $key => $value) { - if ($key == 'metadata' && is_array($header[$key])) { + if ($key === 'metadata' && is_array($header[$key])) { foreach ($header['metadata'] as $key2 => $value2) { if (isset($input['toggleable_header']['metadata'][$key2]) && !$input['toggleable_header']['metadata'][$key2]) { $header['metadata'][$key2] = ''; } } - } elseif ($key == 'taxonomy' && is_array($header[$key])) { + } elseif ($key === 'taxonomy' && is_array($header[$key])) { foreach ($header[$key] as $taxkey => $taxonomy) { if (is_array($taxonomy) && count($taxonomy) == 1 && trim($taxonomy[0]) == '') { unset($header[$key][$taxkey]); @@ -1896,7 +1898,7 @@ class AdminController extends AdminBaseController } if ($clean_header) { $header = Utils::arrayFilterRecursive($header, function ($k, $v) { - return !(is_null($v) || $v === ''); + return !(null === $v || $v === ''); }); } $page->header((object)$header); @@ -1921,7 +1923,7 @@ class AdminController extends AdminBaseController } // Only applies to pages. - if ($this->view != 'pages') { + if ($this->view !== 'pages') { return false; } @@ -2069,7 +2071,7 @@ class AdminController extends AdminBaseController } // Only applies to pages. - if ($this->view != 'pages') { + if ($this->view !== 'pages') { return false; } @@ -2091,7 +2093,7 @@ class AdminController extends AdminBaseController } // Only applies to pages. - if ($this->view != 'pages') { + if ($this->view !== 'pages') { return false; } @@ -2210,11 +2212,11 @@ class AdminController extends AdminBaseController */ public function determineFilenameIncludingLanguage($current_filename, $language) { - $filename = substr($current_filename, 0, -(strlen('.md'))); + $filename = substr($current_filename, 0, -strlen('.md')); - if (substr($filename, -3, 1) == '.') { + if (substr($filename, -3, 1) === '.') { $filename = str_replace(substr($filename, -2), $language, $filename); - } elseif (substr($filename, -6, 1) == '.') { + } elseif (substr($filename, -6, 1) === '.') { $filename = str_replace(substr($filename, -5), $language, $filename); } else { $filename .= '.' . $language; diff --git a/twig/AdminTwigExtension.php b/twig/AdminTwigExtension.php index 9ca85c78..bee710f3 100644 --- a/twig/AdminTwigExtension.php +++ b/twig/AdminTwigExtension.php @@ -1,184 +1,4 @@ grav = Grav::instance(); - $this->lang = $this->grav['user']->language; - } - - /** - * Returns extension name. - * - * @return string - */ - public function getName() - { - return 'AdminTwigExtension'; - } - - public function getFilters() - { - return [ - new \Twig_SimpleFilter('tu', [$this, 'tuFilter']), - new \Twig_SimpleFilter('toYaml', [$this, 'toYamlFilter']), - new \Twig_SimpleFilter('fromYaml', [$this, 'fromYamlFilter']), - new \Twig_SimpleFilter('adminNicetime', [$this, 'adminNicetimeFilter']), - ]; - } - - public function getFunctions() - { - return [ - new \Twig_SimpleFunction('getPageUrl', [$this, 'getPageUrl'], ['needs_context' => true]), - new \Twig_SimpleFunction('clone', [$this, 'cloneFunc']), - ]; - } - - public function cloneFunc($obj) - { - return clone $obj; - } - - public function getPageUrl($context, $page) - { - $page_route = trim($page->rawRoute(), '/'); - $page_lang = $page->language(); - $base_url = $context['base_url']; - $base_url_simple = $context['base_url_simple']; - $admin_lang = Grav::instance()['session']->admin_lang ?: 'en'; - - if ($page_lang && $page_lang != $admin_lang) { - $page_url = $base_url_simple . '/' . $page_lang . '/' . $context['admin_route'] . '/pages/' . $page_route; - } else { - $page_url = $base_url . '/pages/' . $page_route; - } - - return $page_url; - } - - public function tuFilter() - { - $args = func_get_args(); - $numargs = count($args); - $lang = null; - - if (($numargs == 3 && is_array($args[1])) || ($numargs == 2 && !is_array($args[1]))) { - $lang = array_pop($args); - } elseif ($numargs == 2 && is_array($args[1])) { - $subs = array_pop($args); - $args = array_merge($args, $subs); - } - - return $this->grav['admin']->translate($args, $lang); - } - - public function toYamlFilter($value, $inline = true) - { - return Yaml::dump($value, $inline); - - } - - public function fromYamlFilter($value) - { - $yaml = new Parser(); - return $yaml->parse($value); - } - - public function adminNicetimeFilter($date, $long_strings = true) - { - if (empty($date)) { - return $this->grav['admin']->translate('NICETIME.NO_DATE_PROVIDED', null, true); - } - - if ($long_strings) { - $periods = [ - "NICETIME.SECOND", - "NICETIME.MINUTE", - "NICETIME.HOUR", - "NICETIME.DAY", - "NICETIME.WEEK", - "NICETIME.MONTH", - "NICETIME.YEAR", - "NICETIME.DECADE" - ]; - } else { - $periods = [ - "NICETIME.SEC", - "NICETIME.MIN", - "NICETIME.HR", - "NICETIME.DAY", - "NICETIME.WK", - "NICETIME.MO", - "NICETIME.YR", - "NICETIME.DEC" - ]; - } - - $lengths = ["60", "60", "24", "7", "4.35", "12", "10"]; - - $now = time(); - - // check if unix timestamp - if ((string)(int)$date == $date) { - $unix_date = $date; - } else { - $unix_date = strtotime($date); - } - - // check validity of date - if (empty($unix_date)) { - return $this->grav['admin']->translate('NICETIME.BAD_DATE', null, true); - } - - // is it future date or past date - if ($now > $unix_date) { - $difference = $now - $unix_date; - $tense = $this->grav['admin']->translate('NICETIME.AGO', null, true); - - } else { - $difference = $unix_date - $now; - $tense = $this->grav['admin']->translate('NICETIME.FROM_NOW', null, true); - } - - for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) { - $difference /= $lengths[$j]; - } - - $difference = round($difference); - - if ($difference != 1) { - $periods[$j] .= '_PLURAL'; - } - - if ($this->grav['language']->getTranslation($this->grav['user']->language, - $periods[$j] . '_MORE_THAN_TWO') - ) { - if ($difference > 2) { - $periods[$j] .= '_MORE_THAN_TWO'; - } - } - - $periods[$j] = $this->grav['admin']->translate($periods[$j], null, true); - - return "$difference $periods[$j] {$tense}"; - } - -} +class_alias(\Grav\Plugin\Admin\AdminTwigExtension::class, 'Grav\\Plugin\\Admin\\AdminTwigExtension');