From 1c1919092967f968494cfa79d9e550a6d677bb62 Mon Sep 17 00:00:00 2001 From: Flavio Copes Date: Thu, 7 Jul 2016 18:55:52 +0200 Subject: [PATCH] Lint --- admin.php | 142 +++++++++++++++++-------------- classes/admin.php | 77 +++++++++++------ classes/controller.php | 187 ++++++++++++++++++++++++++--------------- classes/gpm.php | 28 ++++-- classes/popularity.php | 42 +++++---- classes/themes.php | 2 +- 6 files changed, 292 insertions(+), 186 deletions(-) diff --git a/admin.php b/admin.php index 53b41434..4d0896f4 100644 --- a/admin.php +++ b/admin.php @@ -75,12 +75,13 @@ class AdminPlugin extends Plugin { if (!Grav::instance()['config']->get('plugins.admin-pro.enabled')) { return [ - 'onPluginsInitialized' => [['setup', 100000], ['onPluginsInitialized', 1001]], - 'onShutdown' => ['onShutdown', 1000], - 'onFormProcessed' => ['onFormProcessed', 0], - 'onAdminDashboard' => ['onAdminDashboard', 0], + 'onPluginsInitialized' => [['setup', 100000], ['onPluginsInitialized', 1001]], + 'onShutdown' => ['onShutdown', 1000], + 'onFormProcessed' => ['onFormProcessed', 0], + 'onAdminDashboard' => ['onAdminDashboard', 0], ]; } + return []; } @@ -123,9 +124,9 @@ class AdminPlugin extends Plugin * - 'password1' for password format * - 'password2' for equality to password1 * - * @param string $type The field type - * @param string $value The field value - * @param string $extra Any extra value required + * @param string $type The field type + * @param string $value The field value + * @param string $extra Any extra value required * * @return bool */ @@ -136,18 +137,21 @@ class AdminPlugin extends Plugin if (!preg_match('/^[a-z0-9_-]{3,16}$/', $value)) { return false; } + return true; case 'password1': if (!preg_match('/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/', $value)) { return false; } + return true; case 'password2': if (strcmp($value, $extra)) { return false; } + return true; } @@ -176,12 +180,12 @@ class AdminPlugin extends Plugin $username = $form->value('username'); if ($form->value('password1') != $form->value('password2')) { - $this->grav->fireEvent('onFormValidationError', - new Event([ - 'form' => $form, + $this->grav->fireEvent('onFormValidationError', new Event([ + 'form' => $form, 'message' => $this->grav['language']->translate('PLUGIN_LOGIN.PASSWORDS_DO_NOT_MATCH') ])); $event->stopPropagation(); + return; } @@ -193,7 +197,7 @@ class AdminPlugin extends Plugin 'title' ]; - foreach($fields as $field) { + foreach ($fields as $field) { // Process value of field if set in the page process.register_user if (!isset($data[$field]) && $form->value($field)) { $data[$field] = $form->value($field); @@ -216,9 +220,10 @@ class AdminPlugin extends Plugin $data['state'] = 'enabled'; $data['access'] = ['admin' => ['login' => true, 'super' => true], 'site' => ['login' => true]]; - // Create user object and save it + // Create user object and save it $user = new User($data); - $file = CompiledYamlFile::instance($this->grav['locator']->findResource('user://accounts/' . $username . YAML_EXT, true, true)); + $file = CompiledYamlFile::instance($this->grav['locator']->findResource('user://accounts/' . $username . YAML_EXT, + true, true)); $user->file($file); $user->save(); $user = User::load($username); @@ -255,11 +260,12 @@ class AdminPlugin extends Plugin // Test for correct Grav 1.1 version if (version_compare(GRAV_VERSION, '1.1.0-beta.1', '<')) { $messages = $this->grav['messages']; - $messages->add($this->grav['language']->translate(['PLUGIN_ADMIN.NEEDS_GRAV_1_1', GRAV_VERSION]), 'error'); + $messages->add($this->grav['language']->translate(['PLUGIN_ADMIN.NEEDS_GRAV_1_1', GRAV_VERSION]), + 'error'); } // Have a unique Admin-only Cache key - if (method_exists($this->grav['cache'], 'setKey')){ + if (method_exists($this->grav['cache'], 'setKey')) { $cache = $this->grav['cache']; $cache_key = $cache->getKey(); $cache->setKey($cache_key . '$'); @@ -272,13 +278,14 @@ class AdminPlugin extends Plugin if (php_sapi_name() == 'cli-server') { - throw new \RuntimeException('The Admin Plugin cannot run on the PHP built-in webserver. It needs Apache, Nginx or another full-featured web server.', 500); + throw new \RuntimeException('The Admin Plugin cannot run on the PHP built-in webserver. It needs Apache, Nginx or another full-featured web server.', + 500); } $this->grav['debugger']->addMessage("Admin Basic"); $this->initializeAdmin(); // Disable Asset pipelining (old method - remove this after Grav is updated) - if (!method_exists($this->grav['assets'],'setJsPipeline')) { + if (!method_exists($this->grav['assets'], 'setJsPipeline')) { $this->config->set('system.assets.css_pipeline', false); $this->config->set('system.assets.js_pipeline', false); } @@ -286,6 +293,7 @@ class AdminPlugin extends Plugin // Replace themes service with admin. $this->grav['themes'] = function () { require_once __DIR__ . '/classes/themes.php'; + return new Themes($this->grav); }; } @@ -298,7 +306,8 @@ class AdminPlugin extends Plugin $this->grav->fireEvent('onAdminRegisterPermissions', new Event(['admin' => $this->admin])); } - protected function initializeController($task, $post) { + protected function initializeController($task, $post) + { require_once __DIR__ . '/classes/controller.php'; $controller = new AdminController($this->grav, $this->template, $task, $this->route, $post); $controller->execute(); @@ -343,7 +352,7 @@ class AdminPlugin extends Plugin } // Make local copy of POST. - $post = !empty($_POST) ? $_POST : array(); + $post = !empty($_POST) ? $_POST : []; // Handle tasks. $this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task'); @@ -370,6 +379,7 @@ class AdminPlugin extends Plugin if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) { $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md")); $page->slug(basename($self->template)); + return $page; } @@ -377,13 +387,13 @@ class AdminPlugin extends Plugin $plugins = $this->grav['plugins']; $locator = $this->grav['locator']; - foreach($plugins as $plugin) { - $path = $locator->findResource( - "user://plugins/{$plugin->name}/admin/pages/{$self->template}.md"); + foreach ($plugins as $plugin) { + $path = $locator->findResource("user://plugins/{$plugin->name}/admin/pages/{$self->template}.md"); if ($path) { $page->init(new \SplFileInfo($path)); $page->slug(basename($self->template)); + return $page; } } @@ -407,7 +417,7 @@ class AdminPlugin extends Plugin } // Explicitly set a timestamp on assets - $this->grav['assets']->setTimestamp(substr(md5(GRAV_VERSION . $this->grav['config']->checksum()),0,10)); + $this->grav['assets']->setTimestamp(substr(md5(GRAV_VERSION . $this->grav['config']->checksum()), 0, 10)); } /** @@ -445,9 +455,9 @@ class AdminPlugin extends Plugin $twig->twig_vars['location'] = $this->template; $twig->twig_vars['base_url_relative_frontend'] = $twig->twig_vars['base_url_relative'] ?: '/'; $twig->twig_vars['admin_route'] = trim($this->config->get('plugins.admin.route'), '/'); - $twig->twig_vars['base_url_relative'] = - $twig->twig_vars['base_url_simple'] . '/' . $twig->twig_vars['admin_route']; - $twig->twig_vars['theme_url'] = $this->grav['locator']->findResource('plugin://admin/themes/' . $this->theme, false); + $twig->twig_vars['base_url_relative'] = $twig->twig_vars['base_url_simple'] . '/' . $twig->twig_vars['admin_route']; + $twig->twig_vars['theme_url'] = $this->grav['locator']->findResource('plugin://admin/themes/' . $this->theme, + false); $twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative']; $twig->twig_vars['base_path'] = GRAV_ROOT; $twig->twig_vars['admin'] = $this->admin; @@ -498,7 +508,7 @@ class AdminPlugin extends Plugin } $action = $_POST['action']; // getUpdatable | getUpdatablePlugins | getUpdatableThemes | gravUpdates - $flush = isset($_POST['flush']) && $_POST['flush'] == true ? true : false; + $flush = isset($_POST['flush']) && $_POST['flush'] == true ? true : false; if (isset($this->grav['session'])) { $this->grav['session']->close(); @@ -521,8 +531,13 @@ class AdminPlugin extends Plugin ]; echo json_encode([ - "status" => "success", - "payload" => ["resources" => $resources_updates, "grav" => $grav_updates, "installed" => $gpm->countInstalled(), 'flushed' => $flush] + "status" => "success", + "payload" => [ + "resources" => $resources_updates, + "grav" => $grav_updates, + "installed" => $gpm->countInstalled(), + 'flushed' => $flush + ] ]); } else { echo json_encode(["status" => "error", "message" => "Cannot connect to the GPM"]); @@ -544,28 +559,28 @@ class AdminPlugin extends Plugin public function getFormFieldTypes() { return [ - 'column' => [ + 'column' => [ 'input@' => false ], - 'columns' => [ + 'columns' => [ 'input@' => false ], 'fieldset' => [ 'input@' => false ], - 'section' => [ + 'section' => [ 'input@' => false ], - 'tab' => [ + 'tab' => [ 'input@' => false ], - 'tabs' => [ + 'tabs' => [ 'input@' => false ], - 'key' => [ + 'key' => [ 'input@' => false ], - 'list' => [ + 'list' => [ 'array' => true ] ]; @@ -579,12 +594,12 @@ class AdminPlugin extends Plugin protected function initializeAdmin() { $this->enable([ - 'onTwigExtensions' => ['onTwigExtensions', 1000], - 'onPagesInitialized' => ['onPagesInitialized', 1000], - 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 1000], - 'onTwigSiteVariables' => ['onTwigSiteVariables', 1000], - 'onAssetsInitialized' => ['onAssetsInitialized', 1000], - 'onTask.GPM' => ['onTaskGPM', 0], + 'onTwigExtensions' => ['onTwigExtensions', 1000], + 'onPagesInitialized' => ['onPagesInitialized', 1000], + 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 1000], + 'onTwigSiteVariables' => ['onTwigSiteVariables', 1000], + 'onAssetsInitialized' => ['onAssetsInitialized', 1000], + 'onTask.GPM' => ['onTaskGPM', 0], 'onAdminRegisterPermissions' => ['onAdminRegisterPermissions', 0], ]); @@ -592,9 +607,7 @@ class AdminPlugin extends Plugin require_once __DIR__ . '/classes/admin.php'; // Check for required plugins - if (!$this->grav['config']->get('plugins.login.enabled') || - !$this->grav['config']->get('plugins.form.enabled') || - !$this->grav['config']->get('plugins.email.enabled')) { + if (!$this->grav['config']->get('plugins.login.enabled') || !$this->grav['config']->get('plugins.form.enabled') || !$this->grav['config']->get('plugins.email.enabled')) { throw new \RuntimeException('One of the required plugins is missing or not enabled'); } @@ -638,13 +651,14 @@ class AdminPlugin extends Plugin $this->theme = $this->config->get('plugins.admin.theme', 'grav'); $assets = $this->grav['assets']; - $translations = 'this.GravAdmin = this.GravAdmin || {}; if (!this.GravAdmin.translations) this.GravAdmin.translations = {}; ' . PHP_EOL . 'this.GravAdmin.translations.PLUGIN_ADMIN = {'; + $translations = 'this.GravAdmin = this.GravAdmin || {}; if (!this.GravAdmin.translations) this.GravAdmin.translations = {}; ' . PHP_EOL . 'this.GravAdmin.translations.PLUGIN_ADMIN = {'; // Enable language translations $translations_actual_state = $this->config->get('system.languages.translations'); $this->config->set('system.languages.translations', true); - $strings = ['EVERYTHING_UP_TO_DATE', + $strings = [ + 'EVERYTHING_UP_TO_DATE', 'UPDATES_ARE_AVAILABLE', 'IS_AVAILABLE_FOR_UPDATE', 'AND', @@ -703,9 +717,9 @@ class AdminPlugin extends Plugin 'TO' ]; - foreach($strings as $string) { + foreach ($strings as $string) { $separator = (end($strings) === $string) ? '' : ','; - $translations .= '"' . $string .'": "' . $this->admin->translate('PLUGIN_ADMIN.' . $string) . '"' . $separator; + $translations .= '"' . $string . '": "' . $this->admin->translate('PLUGIN_ADMIN.' . $string) . '"' . $separator; } $translations .= '};'; @@ -720,7 +734,7 @@ class AdminPlugin extends Plugin */ public function onTwigExtensions() { - require_once(__DIR__.'/twig/AdminTwigExtension.php'); + require_once(__DIR__ . '/twig/AdminTwigExtension.php'); $this->grav['twig']->twig->addExtension(new AdminTwigExtension()); } @@ -731,10 +745,12 @@ class AdminPlugin extends Plugin */ public function isAdminPath() { - if ($this->uri->route() == $this->base || - substr($this->uri->route(), 0, strlen($this->base) + 1) == $this->base . '/') { + if ($this->uri->route() == $this->base || substr($this->uri->route(), 0, + strlen($this->base) + 1) == $this->base . '/' + ) { return true; } + return false; } @@ -754,17 +770,17 @@ class AdminPlugin extends Plugin { $admin = $e['admin']; $permissions = [ - 'admin.super'=> 'boolean', - 'admin.login' => 'boolean', - 'admin.cache' => 'boolean', - 'admin.configuration' => 'boolean', - 'admin.settings' => 'boolean', - 'admin.pages' => 'boolean', - 'admin.maintenance' => 'boolean', - 'admin.statistics' => 'boolean', - 'admin.plugins' => 'boolean', - 'admin.themes' => 'boolean', - 'admin.users' => 'boolean', + 'admin.super' => 'boolean', + 'admin.login' => 'boolean', + 'admin.cache' => 'boolean', + 'admin.configuration' => 'boolean', + 'admin.settings' => 'boolean', + 'admin.pages' => 'boolean', + 'admin.maintenance' => 'boolean', + 'admin.statistics' => 'boolean', + 'admin.plugins' => 'boolean', + 'admin.themes' => 'boolean', + 'admin.users' => 'boolean', ]; $admin->addPermissions($permissions); } diff --git a/classes/admin.php b/classes/admin.php index 0a1e29e0..44e118c6 100644 --- a/classes/admin.php +++ b/classes/admin.php @@ -40,7 +40,7 @@ class Admin /** * @var array */ - protected $pages = array(); + protected $pages = []; /** * @var Session @@ -106,7 +106,7 @@ class Admin $this->user = $this->grav['user']; $this->permissions = []; $language = $this->grav['language']; - + // Load utility class require_once __DIR__ . '/utils.php'; @@ -306,7 +306,9 @@ class Admin $plugins = $this->grav['plugins']; $obj = $plugins->get(preg_replace('|plugins/|', '', $type)); - if (!$obj) { return []; } + if (!$obj) { + return []; + } $obj->merge($post); $obj->file($file); @@ -317,7 +319,9 @@ class Admin $themes = $this->grav['themes']; $obj = $themes->get(preg_replace('|themes/|', '', $type)); - if (!$obj) { return []; } + if (!$obj) { + return []; + } $obj->merge($post); $obj->file($file); @@ -363,7 +367,8 @@ class Admin if (!$this->gpm) { try { $this->gpm = new GPM(); - } catch (\Exception $e) {} + } catch (\Exception $e) { + } } return $this->gpm; @@ -400,6 +405,7 @@ class Admin } else { $routes = $pages->routes(); } + return $routes; } @@ -488,7 +494,7 @@ class Admin * Generate an array of dependencies for a package, used to generate a list of * packages that can be removed when removing a package. * - * @param string $slug The package slug + * @param string $slug The package slug * * @return array|bool */ @@ -525,7 +531,7 @@ class Admin /** * Get list of packages that depend on the passed package slug * - * @param string $slug The package slug + * @param string $slug The package slug * * @return array|bool */ @@ -615,9 +621,9 @@ class Admin /** @var Pages $pages */ $pages = $this->grav['pages']; - $latest = array(); + $latest = []; - if(is_null($pages->routes())){ + if (is_null($pages->routes())) { return null; } @@ -638,7 +644,7 @@ class Admin }); // build new array with just pages in it - $list = array(); + $list = []; foreach ($latest as $item) { $list[] = $item['page']; } @@ -715,7 +721,7 @@ class Admin return null; } - $ppath = str_replace('\\', '/' , dirname($path)); + $ppath = str_replace('\\', '/', dirname($path)); // Find or create parent(s). $parent = $this->getPage($ppath != '/' ? $ppath : ''); @@ -799,6 +805,7 @@ class Admin $languages[$lang] = LanguageCodes::getNativeName($lang); } + return $languages; } @@ -837,6 +844,7 @@ class Admin foreach ($lang_data as $index => $lang) { $languages[$lang] = LanguageCodes::getNativeName($lang); } + return $languages; } @@ -869,6 +877,7 @@ class Admin public static function getNonce() { $action = 'admin-form'; + return Utils::getNonce($action); } @@ -922,6 +931,7 @@ class Admin ob_end_clean(); $pinfo = preg_replace('%^.*(.*).*$%ms', '$1', $pinfo); + return $pinfo; } else { return 'phpinfo() method is not available on this server.'; @@ -933,7 +943,8 @@ class Admin * * @param array|mixed $args * - * @param mixed $languages + * @param mixed $languages + * * @return string */ public function translate($args, $languages = null) @@ -948,7 +959,7 @@ class Admin if (!$languages) { $languages = [$this->grav['user']->authenticated ? $this->grav['user']->language : 'en']; } else { - $languages = (array) $languages; + $languages = (array)$languages; } @@ -991,6 +1002,7 @@ class Admin * Guest date format based on euro/US * * @param $date + * * @return string */ public function guessDateFormat($date) @@ -1045,16 +1057,18 @@ class Admin public function validateDate($date, $format) { $d = DateTime::createFromFormat($format, $date); + return $d && $d->format($format) == $date; } /** * @param string $php_format + * * @return string */ public function dateformatToMomentJS($php_format) { - $SYMBOLS_MATCHING = array( + $SYMBOLS_MATCHING = [ // Day 'd' => 'DD', 'D' => 'ddd', @@ -1099,28 +1113,33 @@ class Admin 'c' => '', 'r' => 'llll ZZ', 'U' => 'X' - ); + ]; $js_format = ""; $escaping = false; - for($i = 0; $i < strlen($php_format); $i++) - { + for ($i = 0; $i < strlen($php_format); $i++) { $char = $php_format[$i]; - if($char === '\\') // PHP date format escaping character + if ($char === '\\') // PHP date format escaping character { $i++; - if($escaping) $js_format .= $php_format[$i]; - else $js_format .= '\'' . $php_format[$i]; + if ($escaping) { + $js_format .= $php_format[$i]; + } else { + $js_format .= '\'' . $php_format[$i]; + } $escaping = true; - } - else - { - if($escaping) { $js_format .= "'"; $escaping = false; } - if(isset($SYMBOLS_MATCHING[$char])) + } else { + if ($escaping) { + $js_format .= "'"; + $escaping = false; + } + if (isset($SYMBOLS_MATCHING[$char])) { $js_format .= $SYMBOLS_MATCHING[$char]; - else + } else { $js_format .= $char; + } } } + return $js_format; } @@ -1167,6 +1186,7 @@ class Admin } } } + return $found_fields; } @@ -1176,7 +1196,7 @@ class Admin $basename = ''; if (isset($path_parts['extension'])) { - $basename = '/'.$path_parts['basename']; + $basename = '/' . $path_parts['basename']; $path = $path_parts['dirname']; } @@ -1196,7 +1216,8 @@ class Admin // theme@ $parts = explode(':', $path); $route = $parts[1]; - $theme = str_replace(ROOT_DIR, '', $this->grav['locator']->findResource("theme://")); + $theme = str_replace(ROOT_DIR, '', $this->grav['locator']->findResource("theme://")); + return $theme . $route . $basename; } } else { diff --git a/classes/controller.php b/classes/controller.php index d2363a85..6d8e6462 100644 --- a/classes/controller.php +++ b/classes/controller.php @@ -85,11 +85,11 @@ class AdminController ]; /** - * @param Grav $grav + * @param Grav $grav * @param string $view * @param string $task * @param string $route - * @param array $post + * @param array $post */ public function __construct(Grav $grav, $view, $task, $route, $post) { @@ -126,11 +126,12 @@ class AdminController if (!$nonce || !Utils::verifyNonce($nonce, 'admin-form')) { if ($this->task == 'addmedia') { - $message = sprintf($this->admin->translate('PLUGIN_ADMIN.FILE_TOO_LARGE', null, true), ini_get('post_max_size')); + $message = sprintf($this->admin->translate('PLUGIN_ADMIN.FILE_TOO_LARGE', null, true), + ini_get('post_max_size')); //In this case it's more likely that the image is too big than POST can handle. Show message $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $message ]; @@ -139,7 +140,7 @@ class AdminController $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'), 'error'); $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN') ]; @@ -153,7 +154,7 @@ class AdminController $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'), 'error'); $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN') ]; @@ -165,7 +166,7 @@ class AdminController $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'), 'error'); $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN') ]; @@ -324,6 +325,7 @@ class AdminController } $this->admin->json_response = ['status' => 'success', 'reload' => $reload]; + return true; } @@ -350,10 +352,12 @@ class AdminController $dependencies = $this->admin->getDependenciesNeededToInstall($packages); } catch (\Exception $e) { $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + return; } $this->admin->json_response = ['status' => 'success', 'dependencies' => $dependencies]; + return true; } @@ -366,7 +370,11 @@ class AdminController $type = isset($data['type']) ? $data['type'] : ''; if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) { - $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')]; + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') + ]; + return false; } @@ -376,6 +384,7 @@ class AdminController $dependencies = $this->admin->getDependenciesNeededToInstall($packages); } catch (\Exception $e) { $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + return; } @@ -384,7 +393,10 @@ class AdminController if ($result) { $this->admin->json_response = ['status' => 'success', 'message' => 'Dependencies installed successfully']; } else { - $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED')]; + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED') + ]; } return true; @@ -397,7 +409,11 @@ class AdminController $type = isset($data['type']) ? $data['type'] : ''; if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) { - $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')]; + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') + ]; + return false; } @@ -409,13 +425,21 @@ class AdminController $result = \Grav\Plugin\Admin\Gpm::install($package, ['theme' => ($type == 'theme')]); } catch (\Exception $e) { $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + return; } if ($result) { - $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate(is_string($result) ? $result : sprintf($this->admin->translate('PLUGIN_ADMIN.PACKAGE_X_INSTALLED_SUCCESSFULLY', null, true), $package))]; + $this->admin->json_response = [ + 'status' => 'success', + 'message' => $this->admin->translate(is_string($result) ? $result : sprintf($this->admin->translate('PLUGIN_ADMIN.PACKAGE_X_INSTALLED_SUCCESSFULLY', + null, true), $package)) + ]; } else { - $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED')]; + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED') + ]; } return true; @@ -433,7 +457,11 @@ class AdminController $type = isset($data['type']) ? $data['type'] : ''; if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) { - $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')]; + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') + ]; + return false; } @@ -443,12 +471,15 @@ class AdminController $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."; } $this->admin->json_response = ['status' => 'error', 'message' => $message]; + return; } @@ -459,13 +490,21 @@ class AdminController $result = \Grav\Plugin\Admin\Gpm::uninstall($package, []); } catch (\Exception $e) { $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()]; + return; } if ($result) { - $this->admin->json_response = ['status' => 'success', 'dependencies' => $dependencies, 'message' => $this->admin->translate(is_string($result) ? $result : 'PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL')]; + $this->admin->json_response = [ + 'status' => 'success', + 'dependencies' => $dependencies, + 'message' => $this->admin->translate(is_string($result) ? $result : 'PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL') + ]; } else { - $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED')]; + $this->admin->json_response = [ + 'status' => 'error', + 'message' => $this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED') + ]; } return true; @@ -553,7 +592,8 @@ class AdminController 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->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'), + 'info'); } $this->setRedirect('/'); @@ -649,12 +689,12 @@ class AdminController $results = Cache::clearCache($clear); if (count($results) > 0) { $this->admin->json_response = [ - 'status' => 'success', + 'status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.CACHE_CLEARED') . '
' . $this->admin->translate('PLUGIN_ADMIN.METHOD') . ': ' . $clear . '' ]; } else { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.ERROR_CLEARING_CACHE') ]; } @@ -694,7 +734,7 @@ class AdminController $backup = ZipBackup::backup(); } catch (\Exception $e) { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.AN_ERROR_OCCURRED') . '. ' . $e->getMessage() ]; @@ -706,18 +746,18 @@ class AdminController '/') . '/task' . $param_sep . 'backup/download' . $param_sep . $download . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form'); $log->content([ - 'time' => time(), + 'time' => time(), 'location' => $backup ]); $log->save(); $this->admin->json_response = [ - 'status' => 'success', + 'status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.YOUR_BACKUP_IS_READY_FOR_DOWNLOAD') . '. ' . $this->admin->translate('PLUGIN_ADMIN.DOWNLOAD_BACKUP') . '', - 'toastr' => [ - 'timeOut' => 0, + 'toastr' => [ + 'timeOut' => 0, 'extendedTimeOut' => 0, - 'closeButton' => true + 'closeButton' => true ] ]; @@ -836,7 +876,7 @@ class AdminController } $this->admin->json_response = [ - 'status' => 'success', + 'status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.PAGES_FILTERED'), 'results' => $results ]; @@ -858,7 +898,7 @@ class AdminController if (!$page) { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND') ]; @@ -892,7 +932,7 @@ class AdminController if (!isset($_FILES['file']['error']) || is_array($_FILES['file']['error'])) { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_PARAMETERS') ]; @@ -905,7 +945,7 @@ class AdminController break; case UPLOAD_ERR_NO_FILE: $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_FILES_SENT') ]; @@ -913,14 +953,14 @@ class AdminController case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT') ]; return false; default: $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.UNKNOWN_ERRORS') ]; @@ -931,7 +971,7 @@ class AdminController // You should also check filesize here. if ($grav_limit > 0 && $_FILES['file']['size'] > $grav_limit) { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT') ]; @@ -950,7 +990,7 @@ class AdminController // If not a supported type, return if (!$fileExt || !$config->get("media.types.{$fileExt}")) { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $fileExt ]; @@ -962,7 +1002,7 @@ class AdminController sprintf('%s/%s', $page->path(), $_FILES['file']['name'])) ) { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.FAILED_TO_MOVE_UPLOADED_FILE') ]; @@ -971,7 +1011,7 @@ class AdminController Cache::clearCache(); $this->admin->json_response = [ - 'status' => 'success', + 'status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_UPLOADED_SUCCESSFULLY') ]; @@ -993,7 +1033,7 @@ class AdminController if (!$page) { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND') ]; @@ -1008,12 +1048,12 @@ class AdminController if (unlink($targetPath)) { Cache::clearCache(); $this->admin->json_response = [ - 'status' => 'success', + 'status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_DELETED') . ': ' . $filename ]; } else { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename ]; } @@ -1041,12 +1081,12 @@ class AdminController if ($deletedResponsiveImage) { Cache::clearCache(); $this->admin->json_response = [ - 'status' => 'success', + 'status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_DELETED') . ': ' . $filename ]; } else { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_NOT_FOUND') . ': ' . $filename ]; } @@ -1054,7 +1094,7 @@ class AdminController } } else { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_FILE_FOUND') ]; } @@ -1078,7 +1118,7 @@ class AdminController if (!$page) { $this->admin->json_response = [ - 'status' => 'error', + 'status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND') ]; @@ -1214,15 +1254,15 @@ class AdminController if ($result) { $this->admin->json_response = [ - 'status' => 'success', - 'type' => 'updategrav', + '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', + 'status' => 'error', + 'type' => 'updategrav', 'version' => GRAV_VERSION, 'message' => $this->admin->translate('PLUGIN_ADMIN.GRAV_UPDATE_FAILED') . '
' . Installer::lastErrorMsg() ]; @@ -1264,6 +1304,7 @@ class AdminController /** * @param $field + * * @return array */ private function cleanFilesData($field) @@ -1274,7 +1315,7 @@ class AdminController $file = $_FILES['data']; - $errors = (array) Utils::getDotNotation($file['error'], $field['name']); + $errors = (array)Utils::getDotNotation($file['error'], $field['name']); foreach ($errors as $index => $error) { if ($error == UPLOAD_ERR_OK) { @@ -1291,7 +1332,7 @@ class AdminController $type = Utils::getDotNotation($file['type'], $fieldname); $size = Utils::getDotNotation($file['size'], $fieldname); - $original_destination = null ; + $original_destination = null; $destination = Folder::getRelativePath(rtrim($field['destination'], '/')); if (!$this->match_in_array($type, $field['accept'])) { @@ -1314,11 +1355,11 @@ class AdminController if (move_uploaded_file($tmp_name, $upload_path)) { $path = $destination . '/' . $name; $fileData = [ - 'name' => $name, - 'path' => $path, - 'type' => $type, - 'size' => $size, - 'file' => $destination . '/' . $name, + 'name' => $name, + 'path' => $path, + 'type' => $type, + 'size' => $size, + 'file' => $destination . '/' . $name, 'route' => $page ? $path : null ]; @@ -1339,7 +1380,7 @@ class AdminController } /** - * @param string $needle + * @param string $needle * @param array|string $haystack * * @return bool @@ -1382,7 +1423,7 @@ class AdminController $keys = explode('.', preg_replace('/^header./', '', $key)); $init_key = array_shift($keys); if (count($keys) > 0) { - $new_data = isset($obj->header()->$init_key) ? $obj->header()->$init_key: []; + $new_data = isset($obj->header()->$init_key) ? $obj->header()->$init_key : []; Utils::setDotNotation($new_data, implode('.', $keys), $data); } else { $new_data = $data; @@ -1463,7 +1504,7 @@ class AdminController return false; } - $data = (array) $this->data; + $data = (array)$this->data; if ($data['route'] == '/') { $path = $this->grav['locator']->findResource('page://'); @@ -1522,7 +1563,7 @@ class AdminController } $reorder = true; - $data = (array) $this->data; + $data = (array)$this->data; $config = $this->grav['config']; @@ -1581,6 +1622,7 @@ class AdminController $obj->validate(); } catch (\Exception $e) { $this->admin->setMessage($e->getMessage(), 'error'); + return false; } $obj->filter(); @@ -1610,6 +1652,7 @@ class AdminController $obj->validate(); } catch (\Exception $e) { $this->admin->setMessage($e->getMessage(), 'error'); + return false; } @@ -1677,7 +1720,7 @@ class AdminController */ public function taskContinue() { - $data = (array) $this->data; + $data = (array)$this->data; if ($this->view == 'users') { $username = strip_tags(strtolower($data['username'])); @@ -1719,7 +1762,7 @@ class AdminController * Used when copying a page, to determine the first available slot * * @param string $item - * @param Page $page + * @param Page $page * * @return string The first available slot */ @@ -1731,28 +1774,37 @@ class AdminController $withoutPrefix = function ($string) { $match = preg_split('/^[0-9]+\./u', $string, 2, PREG_SPLIT_DELIM_CAPTURE); + return isset($match[1]) ? $match[1] : $match[0]; }; $withoutPostfix = function ($string) { $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE); + return $match[0]; }; $appendedNumber = function ($string) { $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE); $append = (isset($match[1]) ? (int)$match[1] + 1 : 2); + return $append; }; $highest = 1; $siblings = $page->parent()->children(); - $findCorrectAppendedNumber = function ($item, $page_item, $highest) use ($siblings, &$findCorrectAppendedNumber, &$withoutPrefix) { + $findCorrectAppendedNumber = function ($item, $page_item, $highest) use ( + $siblings, + &$findCorrectAppendedNumber, + &$withoutPrefix + ) { foreach ($siblings as $sibling) { if ($withoutPrefix($sibling->$item()) == ($highest === 1 ? $page_item : $page_item . '-' . $highest)) { $highest = $findCorrectAppendedNumber($item, $page_item, $highest + 1); + return $highest; } } + return $highest; }; @@ -1920,7 +1972,7 @@ class AdminController */ protected function taskSwitchlanguage() { - $data = (array) $this->data; + $data = (array)$this->data; if (isset($data['lang'])) { $language = $data['lang']; @@ -1957,7 +2009,7 @@ class AdminController return false; } - $data = (array) $this->data; + $data = (array)$this->data; $language = $data['lang']; if ($language) { @@ -2007,6 +2059,7 @@ class AdminController * Determine if the user can edit media * * @param string $type + * * @return bool True if the media action is allowed */ protected function canEditMedia($type = 'media') @@ -2078,7 +2131,7 @@ class AdminController if ($type == 'pages') { $page = $this->admin->page(true, $proute); $keys = explode('.', preg_replace('/^header./', '', $field)); - $header = (array) $page->header(); + $header = (array)$page->header(); $data_path = implode('.', $keys); $data = Utils::getDotNotation($header, $data_path); @@ -2090,9 +2143,9 @@ class AdminController $page->save(); } else { - $blueprint_prefix = $type == 'config' ? '': $type . '.'; + $blueprint_prefix = $type == 'config' ? '' : $type . '.'; $blueprint_name = str_replace('/blueprints', '', str_replace('config/', '', $blueprint)); - $blueprint_field = $blueprint_prefix . $blueprint_name . '.' . $field; + $blueprint_field = $blueprint_prefix . $blueprint_name . '.' . $field; $files = $this->grav['config']->get($blueprint_field); foreach ($files as $key => $value) { @@ -2241,7 +2294,7 @@ class AdminController */ protected function preparePage(Page $page, $clean_header = false, $language = '') { - $input = (array) $this->data; + $input = (array)$this->data; if (isset($input['order'])) { $order = max(0, ((int)isset($input['order']) && $input['order']) ? $input['order'] : $page->value('order')); diff --git a/classes/gpm.php b/classes/gpm.php index bb1d2668..db7621c4 100644 --- a/classes/gpm.php +++ b/classes/gpm.php @@ -24,6 +24,7 @@ class Gpm if (!static::$GPM) { static::$GPM = new GravGPM(); } + return static::$GPM; } @@ -42,7 +43,8 @@ class Gpm /** * @param Package[]|string[]|string $packages - * @param array $options + * @param array $options + * * @return bool */ public static function install($packages, array $options) @@ -56,7 +58,7 @@ class Gpm return false; } - $packages = is_array($packages) ? $packages : [ $packages ]; + $packages = is_array($packages) ? $packages : [$packages]; $count = count($packages); $packages = array_filter(array_map(function ($p) { @@ -91,7 +93,8 @@ class Gpm $local = static::download($package); - Installer::install($local, $options['destination'], ['install_path' => $package->install_path, 'theme' => $options['theme']]); + Installer::install($local, $options['destination'], + ['install_path' => $package->install_path, 'theme' => $options['theme']]); Folder::delete(dirname($local)); $errorCode = Installer::lastErrorCode(); @@ -115,7 +118,8 @@ class Gpm /** * @param Package[]|string[]|string $packages - * @param array $options + * @param array $options + * * @return bool */ public static function update($packages, array $options) @@ -127,14 +131,15 @@ class Gpm /** * @param Package[]|string[]|string $packages - * @param array $options + * @param array $options + * * @return bool */ public static function uninstall($packages, array $options) { $options = array_merge(self::$options, $options); - $packages = is_array($packages) ? $packages : [ $packages ]; + $packages = is_array($packages) ? $packages : [$packages]; $count = count($packages); $packages = array_filter(array_map(function ($p) { @@ -185,6 +190,7 @@ class Gpm /** * @param Package $package + * * @return string */ private static function download(Package $package) @@ -203,8 +209,9 @@ class Gpm } /** - * @param array $package + * @param array $package * @param string $tmp + * * @return string */ private static function _downloadSelfupgrade(array $package, $tmp) @@ -212,6 +219,7 @@ class Gpm $output = Response::get($package['download'], []); Folder::mkdir($tmp); file_put_contents($tmp . DS . $package['name'], $output); + return $tmp . DS . $package['name']; } @@ -228,17 +236,19 @@ class Gpm if (is_link(GRAV_ROOT . DS . 'index.php')) { Installer::setError(Installer::IS_LINK); + return false; } if (method_exists($upgrader, 'meetsRequirements') && !$upgrader->meetsRequirements()) { $error = []; $error[] = '

Grav has increased the minimum PHP requirement.
'; - $error[] = 'You are currently running PHP ' . PHP_VERSION .''; - $error[] = ', but PHP ' . GRAV_PHP_MIN .' is required.

'; + $error[] = 'You are currently running PHP ' . PHP_VERSION . ''; + $error[] = ', but PHP ' . GRAV_PHP_MIN . ' is required.

'; $error[] = '

Additional information

'; Installer::setError(implode("\n", $error)); + return false; } diff --git a/classes/popularity.php b/classes/popularity.php index b82b0b06..e0eb5181 100644 --- a/classes/popularity.php +++ b/classes/popularity.php @@ -38,10 +38,10 @@ class Popularity $this->config = Grav::instance()['config']; $this->data_path = Grav::instance()['locator']->findResource('log://popularity', true, true); - $this->daily_file = $this->data_path.'/'.self::DAILY_FILE; - $this->monthly_file = $this->data_path.'/'.self::MONTHLY_FILE; - $this->totals_file = $this->data_path.'/'.self::TOTALS_FILE; - $this->visitors_file = $this->data_path.'/'.self::VISITORS_FILE; + $this->daily_file = $this->data_path . '/' . self::DAILY_FILE; + $this->monthly_file = $this->data_path . '/' . self::MONTHLY_FILE; + $this->totals_file = $this->data_path . '/' . self::TOTALS_FILE; + $this->visitors_file = $this->data_path . '/' . self::VISITORS_FILE; } @@ -62,7 +62,7 @@ class Popularity } // Make sure no 'widcard-style' ignore matches this url - foreach ((array) $this->config->get('plugins.admin.popularity.ignore') as $ignore) { + foreach ((array)$this->config->get('plugins.admin.popularity.ignore') as $ignore) { if (fnmatch($ignore, $relative_url)) { return; } @@ -121,15 +121,17 @@ class Popularity $limit = intval($this->config->get('plugins.admin.popularity.dashboard.days_of_stats', 7)); $chart_data = array_slice($this->daily_data, -$limit, $limit); - $labels = array(); - $data = array(); + $labels = []; + $data = []; foreach ($chart_data as $date => $count) { - $labels[] = Grav::instance()['grav']['admin']->translate(['PLUGIN_ADMIN.' . strtoupper(date('D', strtotime($date)))]); + $labels[] = Grav::instance()['grav']['admin']->translate([ + 'PLUGIN_ADMIN.' . strtoupper(date('D', strtotime($date))) + ]); $data[] = $count; } - return array('labels' => $labels, 'data' => $data); + return ['labels' => $labels, 'data' => $data]; } /** @@ -162,7 +164,9 @@ class Popularity foreach (array_reverse($this->daily_data) as $daily) { $total += $daily; $day++; - if ($day == 7) break; + if ($day == 7) { + break; + } } return $total; @@ -217,14 +221,15 @@ class Popularity $this->monthly_data = $this->getData($this->monthly_file); } - $labels = array(); - $data = array(); + $labels = []; + $data = []; foreach ($this->monthly_data as $date => $count) { $labels[] = date('M', strtotime($date)); $data[] = $count; } - return array('labels' => $labels, 'data' => $data); + + return ['labels' => $labels, 'data' => $data]; } /** @@ -268,12 +273,13 @@ class Popularity /** * @param string $path + * * @return array */ protected function getData($path) { if (file_exists($path)) { - return (array) json_decode(file_get_contents($path), true); + return (array)json_decode(file_get_contents($path), true); } else { return []; } @@ -282,9 +288,9 @@ class Popularity public function flushPopularity() { - file_put_contents($this->daily_file, array()); - file_put_contents($this->monthly_file, array()); - file_put_contents($this->totals_file, array()); - file_put_contents($this->visitors_file, array()); + file_put_contents($this->daily_file, []); + file_put_contents($this->monthly_file, []); + file_put_contents($this->totals_file, []); + file_put_contents($this->visitors_file, []); } } diff --git a/classes/themes.php b/classes/themes.php index 582736e0..249c9d0e 100644 --- a/classes/themes.php +++ b/classes/themes.php @@ -4,7 +4,7 @@ namespace Grav\Plugin; /** * Admin theme object * - * @author RocketTheme + * @author RocketTheme * @license MIT */ class Themes extends \Grav\Common\Themes