From b87566d0b3aa458689ef5f8268dc1162078bc5b0 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 23 Sep 2022 11:19:51 -0400 Subject: [PATCH] Minor code improvements and housekeeping for various core classes and modules --- wire/core/AdminTheme.php | 34 +-- wire/core/AdminThemeFramework.php | 92 ++++---- wire/core/CacheFile.php | 29 ++- wire/core/DatabaseQuery.php | 6 +- wire/core/DatabaseQuerySelect.php | 6 +- wire/core/DatabaseQuerySelectFulltext.php | 25 ++- wire/core/Debug.php | 4 +- wire/core/Fields.php | 21 +- wire/core/ModuleJS.php | 13 +- wire/core/Notices.php | 30 ++- wire/core/PageAction.php | 14 ++ wire/core/Password.php | 10 +- wire/core/Paths.php | 4 +- wire/core/Process.php | 13 +- wire/core/ProcessController.php | 49 +++-- wire/core/Role.php | 48 +++-- wire/core/Roles.php | 26 ++- wire/core/Sanitizer.php | 48 +++-- wire/core/Session.php | 109 +++++----- wire/core/SessionCSRF.php | 50 +++-- wire/core/Template.php | 11 +- wire/core/TemplateFile.php | 38 ++-- wire/core/Templates.php | 33 +-- wire/core/Tfa.php | 83 ++++---- wire/core/User.php | 75 ++++--- wire/core/Users.php | 3 +- wire/core/WireAction.php | 5 + wire/core/WireClassLoader.php | 9 +- wire/core/WireSaveableItems.php | 20 +- wire/core/WireSaveableItemsLookup.php | 2 +- .../LanguageSupport/LanguageSupport.module | 164 +++++++++------ .../LanguageSupportFields.module | 7 +- .../LanguageSupport/LanguageTranslator.php | 5 +- .../LanguageSupport/ProcessLanguage.module | 62 +++--- .../ProcessLanguageTranslator.module | 135 +++++++----- .../ProcessForgotPassword.module | 199 +++++++++--------- wire/modules/Process/ProcessList.module | 22 +- .../Process/ProcessLogin/ProcessLogin.module | 128 ++++++----- .../System/SystemUpdater/SystemUpdater.module | 69 +++--- 39 files changed, 960 insertions(+), 741 deletions(-) diff --git a/wire/core/AdminTheme.php b/wire/core/AdminTheme.php index 80665e27..dc24f468 100644 --- a/wire/core/AdminTheme.php +++ b/wire/core/AdminTheme.php @@ -10,7 +10,7 @@ * This file is licensed under the MIT license. * https://processwire.com/about/license/mit/ * - * ProcessWire 3.x, Copyright 2021 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @property int|string $version Current admin theme version @@ -102,6 +102,7 @@ abstract class AdminTheme extends WireData implements Module { */ public function __construct() { // placeholder + parent::__construct(); } /** @@ -292,7 +293,7 @@ abstract class AdminTheme extends WireData implements Module { * */ protected function setCurrent() { - $config = $this->wire('config'); + $config = $this->wire()->config; $name = $this->className(); $config->paths->set('adminTemplates', $config->paths->get($name)); $config->urls->set('adminTemplates', $config->urls->get($name)); @@ -315,13 +316,14 @@ abstract class AdminTheme extends WireData implements Module { */ public function ___getExtraMarkup() { $parts = $this->extraMarkup; - $isLoggedin = $this->wire('user')->isLoggedin(); - if($isLoggedin && $this->wire('modules')->isInstalled('InputfieldCKEditor') - && $this->wire('process') instanceof WirePageEditor) { + $isLoggedin = $this->wire()->user->isLoggedin(); + if($isLoggedin && $this->wire()->modules->isInstalled('InputfieldCKEditor') + && $this->wire()->process instanceof WirePageEditor) { // necessary for when CKEditor is loaded via ajax - $parts['head'] .= ""; + $script = 'script'; + $parts['head'] .= "<$script>" . + "window.CKEDITOR_BASEPATH='" . $this->wire()->config->urls('InputfieldCKEditor') . + 'ckeditor-' . InputfieldCKEditor::CKEDITOR_VERSION . "/';"; } /* if($isLoggedin && $this->wire('config')->advanced) { @@ -447,9 +449,12 @@ abstract class AdminTheme extends WireData implements Module { // if we are the only admin theme installed, no need to add an admin_theme field if(self::$numAdminThemes == 0) return; + + $modules = $this->wire()->modules; // install a field for selecting the admin theme from the user's profile - $field = $this->wire('fields')->get('admin_theme'); + /** @var Field $field */ + $field = $this->wire()->fields->get('admin_theme'); $toUseNote = $this->_('To use this theme, select it from your user profile.'); @@ -458,9 +463,10 @@ abstract class AdminTheme extends WireData implements Module { $this->message($toUseNote); } else { // this will be the 2nd admin theme installed, so add a field that lets them select admin theme + /** @var Field $field */ $field = $this->wire(new Field()); $field->name = 'admin_theme'; - $field->type = $this->wire('modules')->get('FieldtypeModule'); + $field->type = $modules->get('FieldtypeModule'); $field->set('moduleTypes', array('AdminTheme')); $field->set('labelField', 'title'); $field->set('inputfieldClass', 'InputfieldRadios'); @@ -475,7 +481,7 @@ abstract class AdminTheme extends WireData implements Module { if($field && $field->id) { /** @var Fieldgroup $fieldgroup */ - $fieldgroup = $this->wire('fieldgroups')->get('user'); + $fieldgroup = $this->wire()->fieldgroups->get('user'); if(!$fieldgroup->hasField($field)) { $fieldgroup->add($field); $fieldgroup->save(); @@ -483,9 +489,9 @@ abstract class AdminTheme extends WireData implements Module { $this->message($toUseNote); } // make this field one that the user is allowed to configure in their profile - $data = $this->wire('modules')->getModuleConfigData('ProcessProfile'); + $data = $modules->getModuleConfigData('ProcessProfile'); $data['profileFields'][] = 'admin_theme'; - $this->wire('modules')->saveModuleConfigData('ProcessProfile', $data); + $modules->saveModuleConfigData('ProcessProfile', $data); } } @@ -505,7 +511,7 @@ abstract class AdminTheme extends WireData implements Module { public function ___uninstall() { - $defaultAdminTheme = $this->wire('config')->defaultAdminTheme; + $defaultAdminTheme = $this->wire()->config->defaultAdminTheme; if($defaultAdminTheme == $this->className()) { throw new WireException( "Cannot uninstall this admin theme because \$config->defaultAdminTheme = '$defaultAdminTheme'; " . diff --git a/wire/core/AdminThemeFramework.php b/wire/core/AdminThemeFramework.php index 901c8417..0e061100 100644 --- a/wire/core/AdminThemeFramework.php +++ b/wire/core/AdminThemeFramework.php @@ -96,7 +96,7 @@ abstract class AdminThemeFramework extends AdminTheme { } public function wired() { - $this->sanitizer = $this->wire('sanitizer'); + $this->sanitizer = $this->wire()->sanitizer; $user = $this->wire()->user; $this->isLoggedIn = $user && $user->isLoggedin(); parent::wired(); @@ -128,7 +128,9 @@ abstract class AdminThemeFramework extends AdminTheme { */ public function init() { - $user = $this->wire('user'); + $user = $this->wire()->user; + $input = $this->wire()->input; + if(!$this->isLoggedIn && $this->useAsLogin) $this->setCurrent(); parent::init(); @@ -139,11 +141,11 @@ abstract class AdminThemeFramework extends AdminTheme { $this->isEditor = $this->isLoggedIn && ($this->isSuperuser || $user->hasPermission('page-edit')); $this->includeInitFile(); - $modal = $this->wire('input')->get('modal'); + $modal = $input->get('modal'); if($modal) $this->isModal = $modal == 'inline' ? 'inline' : true; // test notices when requested - if($this->wire('input')->get('test_notices') && $this->isLoggedIn) $this->testNotices(); + if($input->get('test_notices') && $this->isLoggedIn) $this->testNotices(); } /** @@ -151,12 +153,12 @@ abstract class AdminThemeFramework extends AdminTheme { * */ public function includeInitFile() { - $config = $this->wire('config'); + $config = $this->wire()->config; $initFile = $this->path() . 'init.php'; if(file_exists($initFile)) { if(strpos($initFile, $config->paths->site) === 0) { // admin themes in /site/modules/ may be compiled - $initFile = $this->wire('files')->compile($initFile); + $initFile = $this->wire()->files->compile($initFile); } /** @noinspection PhpIncludeInspection */ include_once($initFile); @@ -173,9 +175,11 @@ abstract class AdminThemeFramework extends AdminTheme { */ public function _($text) { static $translate = null; - if(is_null($translate)) $translate = $this->wire('languages') !== null; + static $context = null; + if($translate === null) $translate = $this->wire()->languages !== null; if($translate === false) return $text; - $value = __($text, $this->wire('config')->paths->root . 'wire/templates-admin/default.php'); + if($context === null) $context = $this->wire()->config->paths->root . 'wire/templates-admin/default.php'; + $value = __($text, $context); if($value === $text) $value = parent::_($text); return $value; } @@ -188,8 +192,8 @@ abstract class AdminThemeFramework extends AdminTheme { */ public function getHeadline() { $headline = $this->wire('processHeadline'); - if(!$headline) $headline = $this->wire('page')->get('title|name'); - if($headline !== 'en' && $this->wire('languages')) $headline = $this->_($headline); + if(!$headline) $headline = $this->wire()->page->get('title|name'); + if($headline !== 'en' && $this->wire()->languages) $headline = $this->_($headline); return $this->sanitizer->entities1($headline); } @@ -225,7 +229,7 @@ abstract class AdminThemeFramework extends AdminTheme { public function getPageIcon(Page $p) { $icon = ''; if($p->template == 'admin') { - $info = $this->wire('modules')->getModuleInfo($p->process); + $info = $this->wire()->modules->getModuleInfo($p->process); if(!empty($info['icon'])) $icon = $info['icon']; } // allow for option of an admin field overriding the module icon @@ -236,7 +240,7 @@ abstract class AdminThemeFramework extends AdminTheme { case 21: $icon = 'plug'; break; // Modules case 28: $icon = 'key'; break; // Access } - if(!$icon && $p->parent->id != $this->wire('config')->adminRootPageID) { + if(!$icon && $p->parent->id != $this->wire()->config->adminRootPageID) { $icon = 'file-o ui-priority-secondary'; } return $icon; @@ -253,17 +257,16 @@ abstract class AdminThemeFramework extends AdminTheme { */ public function getAddNewActions() { - $page = $this->wire('page'); - $process = $this->wire('process'); - $input = $this->wire('input'); + $page = $this->wire()->page; + $process = $this->wire()->process; + $input = $this->wire()->input; if(!$this->isEditor) return array(); - if($page->name != 'page' || $this->wire('input')->urlSegment1) return array(); - if($input->urlSegment1 || $input->get('modal')) return array(); + if($page->name != 'page' || $input->urlSegment1 || $input->get('modal')) return array(); if(strpos($process, 'ProcessPageList') !== 0) return array(); /** @var ProcessPageAdd $module */ - $module = $this->wire('modules')->getModule('ProcessPageAdd', array('noInit' => true)); + $module = $this->wire()->modules->getModule('ProcessPageAdd', array('noInit' => true)); $data = $module->executeNavJSON(array('getArray' => true)); $actions = array(); @@ -293,8 +296,8 @@ abstract class AdminThemeFramework extends AdminTheme { */ public function getBodyClass() { - $page = $this->wire('page'); - $process = $this->wire('process'); + $page = $this->wire()->page; + $process = $this->wire()->process; $classes = array( "id-{$page->id}", @@ -305,7 +308,7 @@ abstract class AdminThemeFramework extends AdminTheme { if($this->isModal) $classes[] = 'modal'; if($this->isModal === 'inline') $classes[] = 'modal-inline'; - if($this->wire('input')->urlSegment1) $classes[] = 'hasUrlSegments'; + if($this->wire()->input->urlSegment1) $classes[] = 'hasUrlSegments'; if($process) $classes[] = $process->className(); if(!$this->isLoggedIn) $classes[] = 'pw-guest'; @@ -347,14 +350,15 @@ abstract class AdminThemeFramework extends AdminTheme { if($p->process == 'ProcessPageAdd') { // ProcessPageAdd: avoid showing this menu item if there are no predefined family settings to use - $numAddable = $this->wire('session')->getFor('ProcessPageAdd', 'numAddable'); + $session = $this->wire()->session; + $numAddable = $session->getFor('ProcessPageAdd', 'numAddable'); if($numAddable === null) { /** @var ProcessPageAdd $processPageAdd */ - $processPageAdd = $this->wire('modules')->getModule('ProcessPageAdd', array('noInit' => true)); + $processPageAdd = $this->wire()->modules->getModule('ProcessPageAdd', array('noInit' => true)); if($processPageAdd) { $addData = $processPageAdd->executeNavJSON(array('getArray' => true)); $numAddable = $addData['list']; - $this->wire('session')->setFor('ProcessPageAdd', 'numAddable', $numAddable); + $session->setFor('ProcessPageAdd', 'numAddable', $numAddable); } } // no addable options, so do not show the "Add New" item @@ -365,23 +369,23 @@ abstract class AdminThemeFramework extends AdminTheme { if(!$p->process) { // no process module present, so we delegate to just the page viewable state if no children to check - if($pageViewable && !$numChildren) return true; + if(!$numChildren) return true; } else if($p->process == 'ProcessList') { // page just serves as a list for children } else { // determine permission from Process module, if present - $moduleInfo = $this->wire('modules')->getModuleInfo($p->process); + $moduleInfo = $this->wire()->modules->getModuleInfo($p->process); if(!empty($moduleInfo['permission'])) $permission = $moduleInfo['permission']; } } if($permission) { // specific permission required to determine view access - $allow = $this->wire('user')->hasPermission($permission); + $allow = $this->wire()->user->hasPermission($permission); - } else if($pageViewable && $p->parent_id == $this->wire('config')->adminRootPageID) { + } else if($p->parent_id == $this->wire()->config->adminRootPageID) { // primary nav page requires that at least one child is viewable foreach($children as $child) { if($this->allowPageInNav($child)) { @@ -403,8 +407,8 @@ abstract class AdminThemeFramework extends AdminTheme { public function ___getPrimaryNavArray() { $items = array(); - $config = $this->wire('config'); - $admin = $this->wire('pages')->get($config->adminRootPageID); + $config = $this->wire()->config; + $admin = $this->wire()->pages->get($config->adminRootPageID); foreach($admin->children("check_access=0") as $p) { $item = $this->pageToNavArray($p); @@ -424,10 +428,11 @@ abstract class AdminThemeFramework extends AdminTheme { */ public function moduleToNavArray($module, Page $p) { - $config = $this->wire('config'); - $modules = $this->wire('modules'); + $config = $this->wire()->config; + $modules = $this->wire()->modules; + $user = $this->wire()->user; + $textdomain = str_replace($config->paths->root, '/', $modules->getModuleFile($p->process)); - $user = $this->wire('user'); $navArray = array(); if(is_array($module)) { @@ -484,7 +489,7 @@ abstract class AdminThemeFramework extends AdminTheme { // no children available if($p->template == 'admin' && $p->process) { // see if process module defines its own navigation - $moduleInfo = $this->wire('modules')->getModuleInfo($p->process); + $moduleInfo = $this->wire()->modules->getModuleInfo($p->process); if(!empty($moduleInfo['nav'])) { $navArray['children'] = $this->moduleToNavArray($moduleInfo, $p); } @@ -499,7 +504,7 @@ abstract class AdminThemeFramework extends AdminTheme { // if we reach this point, then we have a PageArray of children - $modules = $this->wire('modules'); + $modules = $this->wire()->modules; foreach($children as $c) { @@ -540,7 +545,7 @@ abstract class AdminThemeFramework extends AdminTheme { * */ public function ___getUserNavArray() { - $urls = $this->wire('urls'); + $urls = $this->wire()->urls; $navArray = array(); $navArray[] = array( @@ -550,7 +555,7 @@ abstract class AdminThemeFramework extends AdminTheme { 'icon' => 'eye', ); - if($this->wire('user')->hasPermission('profile-edit')) $navArray[] = array( + if($this->wire()->user->hasPermission('profile-edit')) $navArray[] = array( 'url' => $urls->admin . 'profile/', 'title' => $this->_('Profile'), 'icon' => 'user', @@ -576,15 +581,15 @@ abstract class AdminThemeFramework extends AdminTheme { public function getBrowserTitle() { $browserTitle = $this->wire('processBrowserTitle'); - $modal = $this->wire('input')->get('modal'); + $modal = $this->wire()->input->get('modal'); if(!$browserTitle) { if($modal) return $this->wire('processHeadline'); - $browserTitle = $this->_(strip_tags($this->wire('page')->get('title|name'))) . ' • ProcessWire'; + $browserTitle = $this->_(strip_tags($this->wire()->page->get('title|name'))) . ' • ProcessWire'; } if(!$modal) { - $httpHost = $this->wire('config')->httpHost; + $httpHost = $this->wire()->config->httpHost; if(strpos($httpHost, 'www.') === 0) $httpHost = substr($httpHost, 4); // remove www if(strpos($httpHost, ':')) $httpHost = preg_replace('/:\d+/', '', $httpHost); // remove port $browserTitle .= " • $httpHost"; @@ -600,7 +605,7 @@ abstract class AdminThemeFramework extends AdminTheme { * */ public function testNotices() { - if(!$this->wire('user')->isLoggedin()) return false; + if(!$this->wire()->user->isLoggedin()) return false; $this->message('Message test'); $this->message('Message test debug', Notice::debug); $this->message('Message test markup example', Notice::allowMarkup); @@ -648,7 +653,7 @@ abstract class AdminThemeFramework extends AdminTheme { $options = array_merge($defaults, $options); if($notices === true) return $options; - $config = $this->wire('config'); + $config = $this->wire()->config; $noticesArray = array(); $out = ''; @@ -656,13 +661,14 @@ abstract class AdminThemeFramework extends AdminTheme { $removeLabel = $this->_('Close all'); $removeLink = "$removeIcon"; - if($this->isLoggedIn && $this->wire('modules')->isInstalled('SystemNotifications')) { + if($this->isLoggedIn && $this->wire()->modules->isInstalled('SystemNotifications')) { $defaults['groupByType'] = false; //$systemNotifications = $this->wire('modules')->get('SystemNotifications'); //if(!$systemNotifications->placement) return ''; } foreach($notices as $n => $notice) { + /** @var Notice $notice */ $text = $notice->text; $allowMarkup = $notice->flags & Notice::allowMarkup; diff --git a/wire/core/CacheFile.php b/wire/core/CacheFile.php index aefac4f3..33b54129 100644 --- a/wire/core/CacheFile.php +++ b/wire/core/CacheFile.php @@ -12,7 +12,7 @@ * This file is licensed under the MIT license * https://processwire.com/about/license/mit/ * - * ProcessWire 3.x, Copyright 2016 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * */ @@ -48,6 +48,8 @@ class CacheFile extends Wire { * */ public function __construct($path, $id, $cacheTimeSeconds) { + + parent::__construct(); $this->useFuel(false); $path = rtrim($path, '/') . '/'; @@ -55,11 +57,11 @@ class CacheFile extends Wire { $this->path = $id ? $path . $id . '/' : $path; if(!is_dir($path)) { - if(!$this->wire('files')->mkdir($path, true)) throw new WireException("Unable to create path: $path"); + if(!wire()->files->mkdir($path, true)) throw new WireException("Unable to create path: $path"); } if(!is_dir($this->path)) { - if(!$this->wire('files')->mkdir($this->path)) throw new WireException("Unable to create path: {$this->path}"); + if(!wire()->files->mkdir($this->path)) throw new WireException("Unable to create path: $this->path"); } if(is_file($this->globalExpireFile)) { @@ -97,8 +99,11 @@ class CacheFile extends Wire { */ protected function buildFilename() { $filename = $this->path; - if($this->secondaryID) $filename .= $this->secondaryID; - else $filename .= $this->primaryID; + if($this->secondaryID) { + $filename .= $this->secondaryID; + } else { + $filename .= $this->primaryID; + } $filename .= self::cacheFileExtension; return $filename; } @@ -189,12 +194,12 @@ class CacheFile extends Wire { return false; } } else { - $this->wire('files')->mkdir("$dirname/", true); + $this->wire()->files->mkdir("$dirname/", true); } } $result = file_put_contents($filename, $data); - $this->wire('files')->chmod($filename); + $this->wire()->files->chmod($filename); return $result; } @@ -210,7 +215,7 @@ class CacheFile extends Wire { foreach($dir as $file) { if($file->isDir() || $file->isDot()) continue; //if(strpos($file->getFilename(), self::cacheFileExtension)) @unlink($file->getPathname()); - if(self::isCacheFile($file->getPathname())) $this->wire('files')->unlink($file->getPathname()); + if(self::isCacheFile($file->getPathname())) $this->wire()->files->unlink($file->getPathname()); } return @rmdir($this->path); @@ -223,7 +228,7 @@ class CacheFile extends Wire { * */ protected function removeFilename($filename) { - $this->wire('files')->unlink($filename); + $this->wire()->files->unlink($filename); } @@ -239,6 +244,7 @@ class CacheFile extends Wire { $dir = new \DirectoryIterator($path); $numRemoved = 0; + $files = wire()->files; foreach($dir as $file) { @@ -250,7 +256,7 @@ class CacheFile extends Wire { $numRemoved += self::removeAll($pathname, true); } else if($file->isFile() && (self::isCacheFile($pathname) || ($file->getFilename() == self::globalExpireFilename))) { - if(wire('files')->unlink($pathname)) $numRemoved++; + if($files->unlink($pathname)) $numRemoved++; } } @@ -266,7 +272,8 @@ class CacheFile extends Wire { * */ public function expireAll() { - $note = "The modification time of this file represents the time of the last usable cache file. " . + $note = + "The modification time of this file represents the time of the last usable cache file. " . "Cache files older than this file are considered expired. " . date('m/d/y H:i:s'); @file_put_contents($this->globalExpireFile, $note, LOCK_EX); } diff --git a/wire/core/DatabaseQuery.php b/wire/core/DatabaseQuery.php index 279c80c2..3820b351 100644 --- a/wire/core/DatabaseQuery.php +++ b/wire/core/DatabaseQuery.php @@ -10,7 +10,7 @@ * of what other methods/objects have done to it. It also means being able * to build a complex query without worrying about correct syntax placement. * - * ProcessWire 3.x, Copyright 2021 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * This file is licensed under the MIT license @@ -287,7 +287,7 @@ abstract class DatabaseQuery extends WireData { } else { // provided key, make sure it is valid and unique (this part is not typically used) $key = ltrim($options['key'], ':') . 'X'; - if(!ctype_alnum(str_replace('_', '', $key))) $key = $this->wire('database')->escapeCol($key); + if(!ctype_alnum(str_replace('_', '', $key))) $key = $this->wire()->database->escapeCol($key); if(empty($key) || ctype_digit($key[0]) || isset($this->bindKeys[":$key"])) { // if key is not valid, then auto-generate one instead unset($options['key']); @@ -597,7 +597,7 @@ abstract class DatabaseQuery extends WireData { public function getDebugQuery() { $sql = $this->getQuery(); $suffix = $this->bindOptions['suffix']; - $database = $this->wire('database'); + $database = $this->wire()->database; foreach($this->bindValues as $bindKey => $bindValue) { if(is_string($bindValue)) $bindValue = $database->quote($bindValue); if($bindKey[strlen($bindKey)-1] === $suffix) { diff --git a/wire/core/DatabaseQuerySelect.php b/wire/core/DatabaseQuerySelect.php index 6e5f22da..b73f8eec 100644 --- a/wire/core/DatabaseQuerySelect.php +++ b/wire/core/DatabaseQuerySelect.php @@ -12,7 +12,7 @@ * This file is licensed under the MIT license * https://processwire.com/about/license/mit/ * - * ProcessWire 3.x, Copyright 2016 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @property array $select @@ -87,7 +87,7 @@ class DatabaseQuerySelect extends DatabaseQuery { $this->getQueryMethod('limit') ) . ' '; - if($this->get('comment') && $this->wire('config')->debug) { + if($this->get('comment') && $this->wire()->config->debug) { // NOTE: PDO thinks ? and :str param identifiers in /* comments */ are real params // so we str_replace them out of the comment, and only support comments in debug mode $comment = str_replace(array('*/', '?', ':'), '', $this->comment); @@ -142,7 +142,7 @@ class DatabaseQuerySelect extends DatabaseQuery { protected function getQuerySelect() { if(self::$dbCache === null) { - self::$dbCache = $this->wire('config')->dbCache === false ? false : true; + self::$dbCache = $this->wire()->config->dbCache === false ? false : true; } $select = $this->select; diff --git a/wire/core/DatabaseQuerySelectFulltext.php b/wire/core/DatabaseQuerySelectFulltext.php index af92b966..afea9edf 100644 --- a/wire/core/DatabaseQuerySelectFulltext.php +++ b/wire/core/DatabaseQuerySelectFulltext.php @@ -20,7 +20,7 @@ * This file is licensed under the MIT license * https://processwire.com/about/license/mit/ * - * ProcessWire 3.x, Copyright 2021 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @property-read $tableField @@ -164,19 +164,19 @@ class DatabaseQuerySelectFulltext extends Wire { * */ public function __construct(DatabaseQuerySelect $query) { + parent::__construct(); $query->wire($this); $this->query = $query; } /** - * @param string $key - * + * @param string $name * @return mixed|string * */ - public function __get($key) { - if($key === 'tableField') return $this->tableField(); - return parent::__get($key); + public function __get($name) { + if($name === 'tableField') return $this->tableField(); + return parent::__get($name); } /** @@ -296,7 +296,7 @@ class DatabaseQuerySelectFulltext extends Wire { } else { // disable orderby statements when calling object will be negating whatever we do $selector = $this->query->selector; - if($selector && $selector instanceof Selector && $selector->not) $allowOrder = false; + if($selector instanceof Selector && $selector->not) $allowOrder = false; } // if allowOrder has not been specifically set, then set value now @@ -361,7 +361,9 @@ class DatabaseQuerySelectFulltext extends Wire { protected function matchArrayFieldName(array $fieldNames, $value) { $query = $this->query; $query->bindOption('global', true); - $this->query = $this->wire(new DatabaseQuerySelect()); + + $this->query = new DatabaseQuerySelect(); + $this->wire($this->query); $this->query->bindOption(true, $query->bindOption(true)); foreach($fieldNames as $fieldName) { @@ -397,7 +399,8 @@ class DatabaseQuerySelectFulltext extends Wire { $query = $this->query; $query->bindOption('global', true); - $this->query = $this->wire(new DatabaseQuerySelect()); + $this->query = new DatabaseQuerySelect(); + $this->wire($this->query); $this->query->bindOption(true, $query->bindOption(true)); $method = $this->method; @@ -949,7 +952,7 @@ class DatabaseQuerySelectFulltext extends Wire { * - `phrase` (bool): Is entire $value a full phrase to match? (default=auto-detect) * - `useStopwords` (bool): Allow inclusion of stopwords? (default=null, auto-detect) * - `alternates` (bool): Get word alternates? (default=null, auto-detect) - * @return string|array Value provided to the function with boolean operators added, or verbose array. + * @return array Value provided to the function with boolean operators added, or verbose array. * */ protected function getBooleanModeWords($value, array $options = array()) { @@ -1005,7 +1008,7 @@ class DatabaseQuerySelectFulltext extends Wire { } // iterate through all words to build boolean query values - foreach($allWords as $key => $word) { + foreach($allWords as $word) { $length = strlen($word); if(!$length || isset($booleanValues[$word])) continue; diff --git a/wire/core/Debug.php b/wire/core/Debug.php index 0f43455e..7035eafa 100644 --- a/wire/core/Debug.php +++ b/wire/core/Debug.php @@ -352,7 +352,7 @@ class Debug { $options = array_merge($defaults, $options); if($options['limit']) $options['limit']++; $traces = @debug_backtrace($options['flags'], $options['limit']); - $config = wire('config'); + $config = wire()->config; $rootPath = ProcessWire::getRootPath(true); $rootPath2 = $config && $config->paths ? $config->paths->root : $rootPath; array_shift($traces); // shift of the simpleBacktrace call, which is not needed @@ -365,7 +365,7 @@ class Debug { $apiVars[wireClassName($value)] = '$' . $name; } - foreach($traces as $n => $trace) { + foreach($traces as $trace) { if(!is_array($trace) || !isset($trace['function']) || !isset($trace['file'])) { continue; diff --git a/wire/core/Fields.php b/wire/core/Fields.php index fc7493d5..89e2e9cb 100644 --- a/wire/core/Fields.php +++ b/wire/core/Fields.php @@ -156,6 +156,10 @@ class Fields extends WireSaveableItems { self::$nativeNamesSystem = array_flip(self::$nativeNamesSystem); } } + + public function getCacheItemName() { + return array('roles', 'permissions', 'title', 'process'); + } /** * Construct and load the Fields @@ -457,7 +461,7 @@ class Fields extends WireSaveableItems { * * @param Field|Saveable $item Field to clone * @param string $name Optionally specify name for new cloned item - * @return bool|Saveable $item Returns the new clone on success, or false on failure + * @return Field $item Returns the new clone on success, or false on failure * */ public function ___clone(Saveable $item, $name = '') { @@ -637,7 +641,7 @@ class Fields extends WireSaveableItems { $flags = $field2->flags; if($flags & Field::flagSystem) { $field2->flags = $flags | Field::flagSystemOverride; - $field2->flags = 0; + $field2->flags = 0; // intentional overwrite after above line } $field2->name = $field2->name . "_PWTMP"; $field2->type->createField($field2); @@ -688,7 +692,7 @@ class Fields extends WireSaveableItems { $this->error("Field type change failed. Database reports: $error"); $database->exec("DROP TABLE `$table2`"); // QA $severe = $this->wire()->process != 'ProcessField'; - if($exception) $this->trackException($exception, $severe); + $this->trackException($exception, $severe); return false; } @@ -1112,6 +1116,7 @@ class Fields extends WireSaveableItems { } foreach($this->getWireArray() as $field) { + /** @var Field $field */ $fieldtype = $field->type; if(!$fieldtype) continue; @@ -1290,7 +1295,7 @@ class Fields extends WireSaveableItems { * #pw-internal * * @param Field $field - * @return array Array of Fieldtype objects indexed by class name + * @return Fieldtypes * @since 3.0.140 * */ @@ -1298,15 +1303,16 @@ class Fields extends WireSaveableItems { $fieldtype = $field->type; if($fieldtype) { // ask fieldtype what is compatible + /** @var Fieldtypes $fieldtypes */ $fieldtypes = $fieldtype->getCompatibleFieldtypes($field); - if(!$fieldtypes || !$fieldtypes instanceof WireArray) { + if(!$fieldtypes instanceof WireArray) { $fieldtypes = $this->wire(new Fieldtypes()); } // ensure original is present $fieldtypes->prepend($fieldtype); } else { // allow all - $fieldtypes = $this->wire('fieldtypes'); + $fieldtypes = $this->wire()->fieldtypes; } return $fieldtypes; } @@ -1339,7 +1345,8 @@ class Fields extends WireSaveableItems { $fieldId = $this->_fieldId($field); $fieldgroups = $this->wire()->fieldgroups; - $items = $getCount ? null : $this->wire(new FieldgroupsArray()); /** @var FieldgroupsArray $items */ + /** @var FieldgroupsArray $items */ + $items = $getCount ? null : $this->wire(new FieldgroupsArray()); $ids = array(); $count = 0; diff --git a/wire/core/ModuleJS.php b/wire/core/ModuleJS.php index 55753792..7647d979 100644 --- a/wire/core/ModuleJS.php +++ b/wire/core/ModuleJS.php @@ -10,7 +10,7 @@ * * See the Module interface (Module.php) for details about each method. * - * ProcessWire 3.x, Copyright 2016 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * This file is licensed under the MIT license @@ -33,7 +33,7 @@ abstract class ModuleJS extends WireData implements Module { 'summary' => '', // 1 sentence summary of module 'href' => '', // URL to more information (optional) 'permanent' => false, // true if module is permanent and thus not uninstallable - ); + ); } @@ -109,7 +109,7 @@ abstract class ModuleJS extends WireData implements Module { public function init() { $class = $this->className(); - $config = $this->wire('config'); + $config = $this->wire()->config; $file = $config->paths->$class . "$class.css"; if($this->loadStyles && is_file($file)) { @@ -138,7 +138,7 @@ abstract class ModuleJS extends WireData implements Module { $url = $config->urls->$class . $url; } $url .= "?v=$mtime"; - $this->wire('config')->scripts->add($url); + $config->scripts->add($url); } $this->requested = array(); } @@ -155,9 +155,10 @@ abstract class ModuleJS extends WireData implements Module { */ public function ___use($name) { - $name = $this->wire('sanitizer')->name($name); $class = $this->className(); - $config = $this->wire('config'); + $config = $this->wire()->config; + + if(!ctype_alnum($name)) $name = $this->wire()->sanitizer->name($name); if(!isset($this->components[$name])) { $this->error("Unrecognized $class component requested: $name"); diff --git a/wire/core/Notices.php b/wire/core/Notices.php index 3410556c..dd5e139c 100644 --- a/wire/core/Notices.php +++ b/wire/core/Notices.php @@ -10,7 +10,7 @@ * Base class that holds a message, source class, and timestamp. * Contains notices/messages used by the application to the user. * - * ProcessWire 3.x, Copyright 2020 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @property string $text Text of notice @@ -186,7 +186,7 @@ abstract class Notice extends WireData { if($key === 'text' && is_string($value) && strpos($value, 'icon-') === 0 && strpos($value, ' ')) { list($icon, $value) = explode(' ', $value, 2); list(,$icon) = explode('-', $icon, 2); - $icon = $this->wire('sanitizer')->name($icon); + $icon = $this->wire()->sanitizer->name($icon); if(strlen($icon)) $this->set('icon', $icon); } else if($key === 'flags') { $this->flags($value); @@ -475,10 +475,10 @@ class Notices extends WireArray { */ protected function allowNotice(Notice $item) { - $user = $this->wire('user'); /** @var User $user */ + $user = $this->wire()->user; if($item->flags & Notice::debug) { - if(!$this->wire('config')->debug) return false; + if(!$this->wire()->config->debug) return false; } if($item->flags & Notice::superuser) { @@ -490,7 +490,7 @@ class Notices extends WireArray { } if($item->flags & Notice::admin) { - $page = $this->wire('page'); /** @var Page|null $page */ + $page = $this->wire()->page; if(!$page || !$page->template || $page->template->name != 'admin') return false; } @@ -519,7 +519,7 @@ class Notices extends WireArray { if(is_array($text)) { $item->text = "
" . trim(print_r($this->sanitizeArray($text), true)) . "
"; $item->flags = $item->flags | Notice::allowMarkup; - } else if(is_object($text) && $text instanceof Wire) { + } else if($text instanceof Wire) { $item->text = "
" . $this->wire()->sanitizer->entities(print_r($text, true)) . "
"; $item->flags = $item->flags | Notice::allowMarkup; } else if(is_object($text)) { @@ -577,8 +577,7 @@ class Notices extends WireArray { * */ protected function storeNotice(Notice $item) { - /** @var Session $session */ - $session = $this->wire('session'); + $session = $this->wire()->session; if(!$session) return false; $items = $session->getFor($this, 'items'); if(!is_array($items)) $items = array(); @@ -598,7 +597,7 @@ class Notices extends WireArray { */ protected function loadStoredNotices() { - $session = $this->wire('session'); + $session = $this->wire()->session; $items = $session->getFor($this, 'items'); $qty = 0; @@ -640,7 +639,7 @@ class Notices extends WireArray { return $this; } if($item) parent::remove($item); - $session = $this->wire('session'); + $session = $this->wire()->session; $items = $session->getFor($this, 'items'); if(is_array($items) && isset($items[$idStr])) { unset($items[$idStr]); @@ -680,13 +679,12 @@ class Notices extends WireArray { * */ protected function addLog(Notice $item) { - /** @var Notice $item */ $text = $item->text; if(strpos($text, '&') !== false) { - $text = $this->wire('sanitizer')->unentities($text); + $text = $this->wire()->sanitizer->unentities($text); } - if($this->wire('config')->debug && $item->class) $text .= " ($item->class)"; - $this->wire('log')->save($item->getName(), $text); + if($this->wire()->config->debug && $item->class) $text .= " ($item->class)"; + $this->wire()->log->save($item->getName(), $text); } /** @@ -729,7 +727,7 @@ class Notices extends WireArray { * */ public function sanitizeArray(array $a) { - $sanitizer = $this->wire('sanitizer'); + $sanitizer = $this->wire()->sanitizer; $b = array(); foreach($a as $key => $value) { if(is_array($value)) { @@ -738,7 +736,7 @@ class Notices extends WireArray { if(is_object($value)) $value = (string) $value; $value = $sanitizer->entities($value); } - $key = $this->wire('sanitizer')->entities($key); + $key = $sanitizer->entities($key); $b[$key] = $value; } return $b; diff --git a/wire/core/PageAction.php b/wire/core/PageAction.php index 5b9e1311..90a8a849 100644 --- a/wire/core/PageAction.php +++ b/wire/core/PageAction.php @@ -7,6 +7,9 @@ * * This file is licensed under the MIT license * https://processwire.com/about/license/mit/ + * + * @method bool action(Page $item) + * @method executeMultiple(PageArray $items) * */ @@ -36,6 +39,17 @@ abstract class PageAction extends WireAction implements Module { return strlen(__NAMESPACE__) ? __NAMESPACE__ . '\\Page' : 'Page'; } + /** + * Execute the action for the given page + * + * @param Page $item Item to operate upon + * @return bool True if the item was successfully operated upon, false if not. + * + */ + public function execute($item) { + return parent::execute($item); + } + /** * Perform the action on the given item * diff --git a/wire/core/Password.php b/wire/core/Password.php index abf24823..83114665 100644 --- a/wire/core/Password.php +++ b/wire/core/Password.php @@ -5,7 +5,7 @@ * Class to hold combined password/salt info. Uses Blowfish when possible. * Specially used by FieldtypePassword. * - * ProcessWire 3.x, Copyright 2019 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @method setPass($value) Protected internal use method @@ -24,7 +24,7 @@ class Password extends Wire { protected $data = array( 'salt' => '', 'hash' => '', - ); + ); /** * @var WireRandom|null @@ -216,6 +216,8 @@ class Password extends Wire { * */ protected function hash($pass) { + + $config = $this->wire()->config; // if there is no salt yet, make one (for new pass or reset pass) if(strlen($this->data['salt']) < 28) $this->data['salt'] = $this->salt(); @@ -227,10 +229,10 @@ class Password extends Wire { $salt1 = $this->data['salt']; // static salt stored in config.php - $salt2 = (string) $this->wire('config')->userAuthSalt; + $salt2 = (string) $config->userAuthSalt; // auto-detect the hash type based on the format of the salt - $hashType = $this->isBlowfish($salt1) ? 'blowfish' : $this->wire('config')->userAuthHashType; + $hashType = $this->isBlowfish($salt1) ? 'blowfish' : $config->userAuthHashType; if(!$hashType) { // If there is no defined hash type, and the system doesn't support blowfish, then just use md5 (ancient backwards compatibility) diff --git a/wire/core/Paths.php b/wire/core/Paths.php index 5e505015..4fdc8aa4 100644 --- a/wire/core/Paths.php +++ b/wire/core/Paths.php @@ -173,9 +173,9 @@ class Paths extends WireData { $key = "$key"; } else if(strpos($key, 'http') === 0) { if(is_null($_http)) { - $scheme = $this->wire('input')->scheme; + $scheme = $this->wire()->input->scheme; if(!$scheme) $scheme = 'http'; - $httpHost = $this->wire('config')->httpHost; + $httpHost = $this->wire()->config->httpHost; if($httpHost) $_http = "$scheme://$httpHost"; } $http = $_http; diff --git a/wire/core/Process.php b/wire/core/Process.php index ee8feed3..c5204832 100644 --- a/wire/core/Process.php +++ b/wire/core/Process.php @@ -367,7 +367,9 @@ abstract class Process extends WireData implements Module { $info = $modules->getModuleInfoVerbose($this); $name = $sanitizer->pageName($name); - if(!strlen($name)) $name = strtolower(preg_replace('/([A-Z])/', '-$1', str_replace('Process', '', $this->className()))); + if(!strlen($name)) { + $name = strtolower(preg_replace('/([A-Z])/', '-$1', str_replace('Process', '', $this->className()))); + } $adminPage = $pages->get($config->adminRootPageID); if($parent instanceof Page) { // already have what we need @@ -407,14 +409,15 @@ abstract class Process extends WireData implements Module { * */ protected function ___uninstallPage() { - $moduleID = $this->wire('modules')->getModuleID($this); + $pages = $this->wire()->pages; + $moduleID = $this->wire()->modules->getModuleID($this); if(!$moduleID) return 0; $n = 0; - foreach($this->wire('pages')->find("process=$moduleID, include=all") as $page) { + foreach($pages->find("process=$moduleID, include=all") as $page) { if("$page->process" != "$this") continue; $page->process = null; $this->message(sprintf($this->_('Trashed Page: %s'), $page->path)); - $this->wire('pages')->trash($page); + $pages->trash($page); $n++; } return $n; @@ -534,6 +537,7 @@ abstract class Process extends WireData implements Module { if(!empty($options['getArray'])) return $data; if($config->ajax) header("Content-Type: application/json"); + return json_encode($data); } @@ -645,7 +649,6 @@ abstract class Process extends WireData implements Module { * */ public static function getAfterLoginUrl(Page $page) { - if($page) {} return false; } } diff --git a/wire/core/ProcessController.php b/wire/core/ProcessController.php index 94cfebff..8b64eacc 100644 --- a/wire/core/ProcessController.php +++ b/wire/core/ProcessController.php @@ -5,7 +5,7 @@ * * Loads and executes Process Module instance and determines access. * - * ProcessWire 3.x, Copyright 2018 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * */ @@ -107,7 +107,11 @@ class ProcessController extends Wire { * */ public function setProcessName($processName) { - $this->processName = $this->sanitizer->name($processName); + $processName = (string) $processName; + if(!ctype_alnum($processName)) { + $processName = $this->wire()->sanitizer->className($processName); + } + $this->processName = $processName; } /** @@ -121,7 +125,11 @@ class ProcessController extends Wire { * */ public function setProcessMethodName($processMethod) { - $this->processMethodName = $this->sanitizer->name($processMethod); + $processMethod = (string) $processMethod; + if(!ctype_alnum($processMethod)) { + $processMethod = $this->wire()->sanitizer->name($processMethod); + } + $this->processMethodName = $processMethod; } /** @@ -135,7 +143,9 @@ class ProcessController extends Wire { * */ public function setPrefix($prefix) { - $this->prefix = $this->sanitizer->name($prefix); + $prefix = (string) $prefix; + if(!ctype_alpha($prefix)) $prefix = $this->wire()->sanitizer->name($prefix); + $this->prefix = $prefix; } /** @@ -145,6 +155,8 @@ class ProcessController extends Wire { * */ public function getProcess() { + + $modules = $this->wire()->modules; if($this->process) { $processName = $this->process->className(); @@ -156,14 +168,14 @@ class ProcessController extends Wire { // verify that there is adequate permission to execute the Process $permissionName = ''; - $info = $this->wire('modules')->getModuleInfoVerbose($processName); + $info = $modules->getModuleInfoVerbose($processName); $this->processInfo = $info; if(!empty($info['permission'])) $permissionName = $info['permission']; $this->hasPermission($permissionName, true); // throws exception if no permission if(!$this->process) { - $module = $this->modules->getModule($processName, array('returnError' => true)); + $module = $modules->getModule($processName, array('returnError' => true)); if(is_string($module)) { $this->processError = $module; $this->process = null; @@ -191,7 +203,7 @@ class ProcessController extends Wire { * */ protected function hasPermission($permissionName, $throw = true) { - $user = $this->wire('user'); + $user = $this->wire()->user; if($user->isSuperuser()) return true; if($permissionName && $user->hasPermission($permissionName)) return true; if($throw) { @@ -215,7 +227,7 @@ class ProcessController extends Wire { // i.e. executeHelloWorld => helloWorld $urlSegment = $method; if(strpos($method, 'execute') === 0) list(,$urlSegment) = explode('execute', $method, 2); - $urlSegment = $this->wire('sanitizer')->hyphenCase($urlSegment); + $urlSegment = $this->wire()->sanitizer->hyphenCase($urlSegment); if(!$this->hasUrlSegmentPermission($urlSegment, $throw)) return false; return true; } @@ -231,7 +243,7 @@ class ProcessController extends Wire { */ protected function hasUrlSegmentPermission($urlSegment, $throw = true) { - if(empty($this->processInfo['nav']) || $this->wire('user')->isSuperuser()) return true; + if(empty($this->processInfo['nav']) || $this->wire()->user->isSuperuser()) return true; $hasPermission = true; $urlSegment = trim(strtolower($urlSegment), '.-_'); @@ -259,11 +271,11 @@ class ProcessController extends Wire { * */ public function getProcessMethodName(Process $process) { - + + $sanitizer = $this->wire()->sanitizer; $forceFail = false; - $urlSegment1 = $this->wire('input')->urlSegment1; + $urlSegment1 = $this->wire()->input->urlSegment1; $method = self::defaultProcessMethodName; - $sanitizer = $this->wire('sanitizer'); if($this->processMethodName) { // the method to use has been preset with the setProcessMethodName() function @@ -272,7 +284,7 @@ class ProcessController extends Wire { $this->hasMethodPermission($method); } - } else if(strlen($urlSegment1) && !$this->wire('user')->isGuest()) { + } else if(strlen($urlSegment1) && !$this->wire()->user->isGuest()) { // determine requested method from urlSegment1 // $urlSegment1 = trim($this->wire('sanitizer')->hyphenCase($urlSegment1, array('allow' => 'a-z0-9_')), '_'); if(ctype_alpha($urlSegment1)) { @@ -315,8 +327,8 @@ class ProcessController extends Wire { */ public function ___execute() { - $debug = $this->wire('config')->debug; - $breadcrumbs = $this->wire('breadcrumbs'); + $debug = $this->wire()->config->debug; + $breadcrumbs = $this->wire()->breadcrumbs; $headline = $this->wire('processHeadline'); $numBreadcrumbs = $breadcrumbs ? count($breadcrumbs) : null; $process = $this->getProcess(); @@ -341,12 +353,12 @@ class ProcessController extends Wire { // setup breadcrumbs if in some method other than the main execute() method if($method !== 'execute') { // some method other than the main one - if(!is_null($numBreadcrumbs) && $numBreadcrumbs === count($breadcrumbs)) { + if($numBreadcrumbs === count($breadcrumbs)) { // process added no breadcrumbs, but there should be more if($headline === $this->wire('processHeadline')) { $process->headline(str_replace('execute', '', $method)); } - $href = substr($this->wire('input')->url(), -1) == '/' ? '../' : './'; + $href = substr($this->wire()->input->url(), -1) == '/' ? '../' : './'; $process->breadcrumb($href, $this->processInfo['title']); } } @@ -364,6 +376,7 @@ class ProcessController extends Wire { $viewFile = $this->getViewFile($process, $method); if($viewFile) { // get output from a separate view file + /** @var TemplateFile $template */ $template = $this->wire(new TemplateFile($viewFile)); foreach($content as $key => $value) { $template->set($key, $value); @@ -393,7 +406,7 @@ class ProcessController extends Wire { if(empty($method)) $method = 'execute'; $className = $process->className(); - $viewPath = $this->wire('config')->paths->$className; + $viewPath = $this->wire()->config->paths->$className; $method2 = ''; // lowercase hyphenated version $method3 = ''; // lowercase hyphenated, without leading execute if(strtolower($method) != $method) { diff --git a/wire/core/Role.php b/wire/core/Role.php index 4b659088..892081a3 100644 --- a/wire/core/Role.php +++ b/wire/core/Role.php @@ -11,7 +11,7 @@ * access related methods on `Page`. * #pw-body * - * ProcessWire 3.x, Copyright 2016 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @property PageArray $permissions PageArray of permissions assigned to Role. @@ -49,7 +49,7 @@ class Role extends Page { * */ protected function getPredefinedTemplate() { - return $this->wire('templates')->get('role'); + return $this->wire()->templates->get('role'); } /** @@ -59,7 +59,7 @@ class Role extends Page { * */ protected function getPredefinedParent() { - return $this->wire('pages')->get($this->wire('config')->rolesPageID); + return $this->wire()->pages->get($this->wire()->config->rolesPageID); } /** @@ -79,7 +79,7 @@ class Role extends Page { if(empty($name)) { // do nothing - return $has; + return false; } else if($name instanceof Page) { $permission = $name; @@ -95,16 +95,20 @@ class Role extends Page { } } - } else if($name == "page-add" || $name == "page-create") { + } else if($name === 'page-add' || $name === 'page-create') { // runtime permissions that don't have associated permission pages if(empty($context)) return false; + /** @var Permission $permission */ $permission = $this->wire(new Permission()); $permission->name = $name; } else if(is_string($name)) { - if(!$this->wire('permissions')->has($name)) { - if(!ctype_alnum(str_replace('-', '', $name))) $name = $this->wire('sanitizer')->pageName($name); - $delegated = $this->wire('permissions')->getDelegatedPermissions(); + $permissions = $this->wire()->permissions; // all permissions + if(!$permissions->has($name)) { + if(!ctype_alnum(str_replace('-', '', $name))) { + $name = $this->wire()->sanitizer->pageName($name); + } + $delegated = $permissions->getDelegatedPermissions(); if(isset($delegated[$name])) $name = $delegated[$name]; } foreach($this->permissions as $p) { @@ -116,8 +120,8 @@ class Role extends Page { } } - if($context !== null && ($context instanceof Page || $context instanceof Template)) { - if(!$permission) $permission = $this->wire('permissions')->get($name); + if($context instanceof Page || $context instanceof Template) { + if(!$permission) $permission = $this->wire()->permissions->get($name); if($permission) { $has = $this->hasPermissionContext($has, $permission, $context); } @@ -137,21 +141,23 @@ class Role extends Page { */ protected function hasPermissionContext($has, Permission $permission, Wire $context) { - if(strpos($permission->name, "page-") !== 0) return $has; + if(strpos($permission->name, 'page-') !== 0) return $has; + $type = str_replace('page-', '', $permission->name); + if(!in_array($type, array('view', 'edit', 'add', 'create'))) $type = 'edit'; $accessTemplate = $context instanceof Page ? $context->getAccessTemplate($type) : $context; if(!$accessTemplate) return false; if(!$accessTemplate->useRoles) return $has; - if($permission->name == 'page-view') { + if($permission->name === 'page-view') { if(!$has) return false; $has = $accessTemplate->hasRole($this); return $has; } - if($permission->name == 'page-edit' && !$has) return false; + if($permission->name === 'page-edit' && !$has) return false; switch($permission->name) { case 'page-edit': @@ -194,8 +200,10 @@ class Role extends Page { * */ public function addPermission($permission) { - if(is_string($permission) || is_int($permission)) $permission = $this->wire('permissions')->get($permission); - if(is_object($permission) && $permission instanceof Permission) { + if(is_string($permission) || is_int($permission)) { + $permission = $this->wire()->permissions->get($permission); + } + if($permission instanceof Permission) { $this->permissions->add($permission); return true; } @@ -212,8 +220,10 @@ class Role extends Page { * */ public function removePermission($permission) { - if(is_string($permission) || is_int($permission)) $permission = $this->wire('permissions')->get($permission); - if(is_object($permission) && $permission instanceof Permission) { + if(is_string($permission) || is_int($permission)) { + $permission = $this->wire()->permissions->get($permission); + } + if($permission instanceof Permission) { $this->permissions->remove($permission); return true; } @@ -225,11 +235,11 @@ class Role extends Page { * * #pw-internal * - * @return Pages|PagesType + * @return Roles * */ public function getPagesManager() { - return $this->wire('roles'); + return $this->wire()->roles; } } diff --git a/wire/core/Roles.php b/wire/core/Roles.php index dfa51b3e..e2e185b1 100644 --- a/wire/core/Roles.php +++ b/wire/core/Roles.php @@ -19,6 +19,10 @@ class Roles extends PagesType { + /** + * @var Role|null + * + */ protected $guestRole = null; /** @@ -28,13 +32,13 @@ class Roles extends PagesType { * * #pw-internal * - * @return Role|NullPage|Page + * @return Role * @throws WireException * */ public function getGuestRole() { if($this->guestRole) return $this->guestRole; - $this->guestRole = parent::get((int) $this->wire('config')->guestUserRolePageID); + $this->guestRole = parent::get((int) $this->wire()->config->guestUserRolePageID); return $this->guestRole; } @@ -85,11 +89,13 @@ class Roles extends PagesType { * #pw-group-manipulation * * @param string $name Name of role you want to add, i.e. "hello-world" - * @return Role|Page|NullPage Returns a Role page on success, or a NullPage on error + * @return Role|NullPage Returns a Role page on success, or a NullPage on error * */ public function ___add($name) { - return parent::___add($name); + /** @var Role|NullPage $role */ + $role = parent::___add($name); + return $role; } /** @@ -101,8 +107,14 @@ class Roles extends PagesType { * */ protected function loaded(Page $page) { - if(!$page->permissions->has("name=page-view")) { - $page->permissions->add($this->wire('permissions')->get("name=page-view")); + $hasPageView = false; + foreach($page->permissions as $permission) { + if($permission->name === 'page-view') $hasPageView = true; + if($hasPageView) break; + } + if(!$hasPageView) { + $pageView = $this->wire()->permissions->get('page-view'); + $page->permissions->add($pageView); } } @@ -115,7 +127,7 @@ class Roles extends PagesType { * */ public function ___deleted(Page $page) { - foreach($this->wire('templates') as $template) { + foreach($this->wire()->templates as $template) { /** @var Template $template */ if(!$template->useRoles) continue; $template->removeRole($page, 'all'); diff --git a/wire/core/Sanitizer.php b/wire/core/Sanitizer.php index 25686710..d54cd3fa 100644 --- a/wire/core/Sanitizer.php +++ b/wire/core/Sanitizer.php @@ -324,6 +324,7 @@ class Sanitizer extends Wire { * */ public function __construct() { + parent::__construct(); $this->multibyteSupport = function_exists("mb_internal_encoding"); if($this->multibyteSupport) mb_internal_encoding("UTF-8"); $this->allowedASCII = str_split($this->alphaASCII . $this->digitASCII); @@ -361,7 +362,7 @@ class Sanitizer extends Wire { $value = mb_strtolower($value); if(empty($replacements)) { - $configData = $this->wire('modules')->getModuleConfigData('InputfieldPageName'); + $configData = $this->wire()->modules->getModuleConfigData('InputfieldPageName'); $replacements = empty($configData['replacements']) ? InputfieldPageName::$defaultReplacements : $configData['replacements']; } @@ -719,7 +720,7 @@ class Sanitizer extends Wire { if(!strlen($value)) return ''; $defaults = array( - 'charset' => $this->wire('config')->pageNameCharset + 'charset' => $this->wire()->config->pageNameCharset ); if(is_array($beautify)) { @@ -824,8 +825,10 @@ class Sanitizer extends Wire { $value = $this->string($value); if(!strlen($value)) return ''; + $config = $this->wire()->config; + // if UTF8 module is not enabled then delegate this call to regular pageName sanitizer - if($this->wire('config')->pageNameCharset != 'UTF8') return $this->pageName($value, false, $maxLength); + if($config->pageNameCharset != 'UTF8') return $this->pageName($value, false, $maxLength); $tt = $this->getTextTools(); @@ -836,7 +839,7 @@ class Sanitizer extends Wire { $separators = array('.', '-', '_'); // whitelist of allowed characters and blacklist of disallowed characters - $whitelist = $this->wire('config')->pageNameWhitelist; + $whitelist = $config->pageNameWhitelist; if(!strlen($whitelist)) $whitelist = false; $blacklist = '/\\%"\'<>?#@:;,+=*^$()[]{}|&'; @@ -1105,7 +1108,7 @@ class Sanitizer extends Wire { * #pw-group-pages * * @param string $value Value to sanitize - * @param bool $beautify Beautify the value? (default=false). Maybe any of the following: + * @param bool|int $beautify Beautify the value? (default=false). Maybe any of the following: * - `true` (bool): Beautify the individual page names in the path to remove redundant and trailing punctuation and more. * - `false` (bool): Do not perform any conversion or attempt to make it more pretty, just sanitize (default). * - `Sanitizer::translate` (constant): Translate UTF-8 characters to visually similar ASCII (using InputfieldPageName module settings). @@ -1202,7 +1205,7 @@ class Sanitizer extends Wire { * */ public function pagePathNameUTF8($value) { - if($this->wire('config')->pageNameCharset !== 'UTF8') return $this->pagePathName($value); + if($this->wire()->config->pageNameCharset !== 'UTF8') return $this->pagePathName($value); $value = $this->string($value); if(!strlen($value)) return ''; $parts = explode('/', $value); @@ -1363,7 +1366,7 @@ class Sanitizer extends Wire { if($separator !== null && $count > 1) { $value = implode($separator, $a); - } else if($count) { + } else { $value = reset($a); } @@ -1849,7 +1852,7 @@ class Sanitizer extends Wire { * */ public function markupToLine($value, array $options = array()) { - if(!isset($options['newline'])) $options['newline'] = $options['newline'] = " "; + if(!isset($options['newline'])) $options['newline'] = " "; if(!isset($options['separator'])) $options['separator'] = ", "; return $this->markupToText($value, $options); } @@ -2549,7 +2552,7 @@ class Sanitizer extends Wire { * * @param $value * @param array $options - * @return bool|mixed|string + * @return string * */ protected function selectorValueV1($value, $options = array()) { @@ -2829,8 +2832,8 @@ class Sanitizer extends Wire { if($options['fullMarkdown']) { // full markdown - - $markdown = $this->wire('modules')->get('TextformatterMarkdownExtra'); + /** @var TextformatterMarkdownExtra $markdown */ + $markdown = $this->wire()->modules->get('TextformatterMarkdownExtra'); if(is_int($options['fullMarkdown'])) { $markdown->flavor = $options['fullMarkdown']; } else { @@ -3037,7 +3040,8 @@ class Sanitizer extends Wire { * */ public function purifier(array $options = array()) { - $purifier = $this->wire('modules')->get('MarkupHTMLPurifier'); + /** @var MarkupHTMLPurifier $purifier */ + $purifier = $this->wire()->modules->get('MarkupHTMLPurifier'); foreach($options as $key => $value) $purifier->set($key, $value); return $purifier; } @@ -3335,7 +3339,7 @@ class Sanitizer extends Wire { if($html) { if(empty($whitespaceHTML)) { $whitespaceHTML = $this->whitespaceHTML; - foreach($this->whitespaceUTF8 as $key => $value) { + foreach($this->whitespaceUTF8 as $value) { $whitespaceHTML[] = "&#x$value;"; // hex entity $whitespaceHTML[] = "&#" . hexdec($value) . ';'; // decimal entity } @@ -3449,7 +3453,7 @@ class Sanitizer extends Wire { * @param array $options Options to modify behavior, 3.0.169+ only: * - `replaceWith` (string): Replace MB4+ characters with this character, may not be blank (default='�') * - `version` (int): Replacement method version (default=2) - * @return string|array|mixed + * @return string|array * */ public function removeMB4($value, array $options = array()) { @@ -3801,7 +3805,7 @@ class Sanitizer extends Wire { 'strict' => false, ); $options = array_merge($defaults, $options); - $datetime = $this->wire('datetime'); + $datetime = $this->wire()->datetime; $iso8601 = 'Y-m-d H:i:s'; $_value = trim($this->string($value)); // original value string if(empty($value)) return $options['default']; @@ -4008,8 +4012,12 @@ class Sanitizer extends Wire { if(is_string($min)) $min = ctype_digit($min) ? (float) $min : (int) $min; if(is_string($max)) $max = ctype_digit($max) ? (float) $max : (int) $max; $value = is_float($min) || is_float($max) ? (float) $value : (int) $value; - if($min === null) $min = is_float($value) ? PHP_FLOAT_MIN : PHP_INT_MIN; - if($max === null) $max = is_float($value) ? PHP_FLOAT_MAX : PHP_INT_MAX; + if($min === null) { + $min = is_float($value) && defined('PHP_FLOAT_MIN') ? constant('PHP_FLOAT_MIN') : PHP_INT_MIN; + } + if($max === null) { + $max = is_float($value) && defined('PHP_FLOAT_MAX') ? constant('PHP_FLOAT_MAX') : PHP_INT_MAX; + } if($min > $max) list($min, $max) = array($max, $min); // swap args if necessary if($value < $min) { $value = $min; @@ -4418,7 +4426,7 @@ class Sanitizer extends Wire { } $clean = array(); $strict = isset($options['strict']) ? $options['strict'] : false; - foreach($value as $k => $v) { + foreach($value as $v) { if($strict) { $isInt = is_int($v); $isStr = !$isInt && is_string($v); @@ -4575,7 +4583,7 @@ class Sanitizer extends Wire { $options = is_array($options) ? array_merge($defaults, $options) : $defaults; $preserveKeys = $options['preserveKeys']; - foreach($value as $key => $val) { + foreach($value as $val) { if(is_array($val)) $isFlat = false; if(!$isFlat) break; } @@ -4923,7 +4931,7 @@ class Sanitizer extends Wire { if($value === "1") return true; if($value === "false") return false; if($value === "true") return true; - if($length) return true; + return true; } else if(is_object($value)) { $value = $this->string($value); } else if(is_array($value)) { diff --git a/wire/core/Session.php b/wire/core/Session.php index de10091d..8e9a9b8e 100644 --- a/wire/core/Session.php +++ b/wire/core/Session.php @@ -170,8 +170,11 @@ class Session extends Wire implements \IteratorAggregate { * */ public function __construct(ProcessWire $wire) { - + + parent::__construct(); $wire->wire($this); + + $users = $wire->wire()->users; $this->config = $wire->wire()->config; $this->sessionKey = $this->className(); @@ -204,15 +207,15 @@ class Session extends Wire implements \IteratorAggregate { $userID = $this->get('_user', 'id'); if($userID) { if($this->isValidSession($userID)) { - $user = $this->wire('users')->get($userID); + $user = $users->get($userID); } else { $this->logout(); } } } - if(!$user || !$user->id) $user = $this->wire('users')->getGuestUser(); - $this->wire('users')->setCurrentUser($user); + if(!$user || !$user->id) $user = $users->getGuestUser(); + $users->setCurrentUser($user); if($sessionAllow) $this->wakeupNotices(); $this->setTrackChanges(true); @@ -377,7 +380,7 @@ class Session extends Wire implements \IteratorAggregate { } else if($reason && $userID && $userID != $this->wire('config')->guestUserPageID) { // otherwise log the invalid session - $user = $this->wire('users')->get((int) $userID); + $user = $this->wire()->users->get((int) $userID); if($user && $user->id) $reason = "User '$user->name' - $reason"; $reason .= " (IP: " . $this->getIP() . ")"; $this->log($reason); @@ -444,7 +447,7 @@ class Session extends Wire implements \IteratorAggregate { if(!$useFingerprint) return false; - if($useFingerprint === true || $useFingerprint === 1 || $useFingerprint === "1") { + if($useFingerprint === true || $useFingerprint === 1 || "$useFingerprint" === "1") { // default (boolean true or int 1) $useFingerprint = self::fingerprintRemoteAddr | self::fingerprintUseragent; if($debug) $debugInfo[] = 'default'; @@ -515,22 +518,24 @@ class Session extends Wire implements \IteratorAggregate { public function get($key, $_key = null) { if($key === 'CSRF') { return $this->CSRF(); - } else if(!is_null($_key)) { + } else if($_key !== null) { // namespace return $this->getFor($key, $_key); } if($this->sessionInit) { $value = isset($_SESSION[$this->sessionKey][$key]) ? $_SESSION[$this->sessionKey][$key] : null; } else { - if($key == 'config') return $this->config; + if($key === 'config') return $this->config; $value = isset($this->data[$key]) ? $this->data[$key] : null; } - + + /* if(is_null($value) && is_null($_key) && strpos($key, '_user_') === 0) { // for backwards compatiblity with non-core modules or templates that may be checking _user_[property] // not currently aware of any instances, but this is just a precaution return $this->get('_user', str_replace('_user_', '', $key)); } + */ return $value; } @@ -696,8 +701,11 @@ class Session extends Wire implements \IteratorAggregate { $ns = $this->getNamespace($ns); $data = $this->get($ns); if(!is_array($data)) $data = array(); - if(is_null($value)) unset($data[$key]); - else $data[$key] = $value; + if(is_null($value)) { + unset($data[$key]); + } else { + $data[$key] = $value; + } return $this->set($ns, $data); } @@ -798,12 +806,12 @@ class Session extends Wire implements \IteratorAggregate { /** * Provide non-namespaced $session->variable get access * - * @param string $key + * @param string $name * @return SessionCSRF|mixed|null * */ - public function __get($key) { - return $this->get($key); + public function __get($name) { + return $this->get($name); } /** @@ -870,10 +878,13 @@ class Session extends Wire implements \IteratorAggregate { $ip = '127.0.0.1'; } else if($useClient) { - if(!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP']; - else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; - else if(!empty($_SERVER['REMOTE_ADDR'])) $ip = $_SERVER['REMOTE_ADDR']; - else $ip = '0.0.0.0'; + if(!empty($_SERVER['HTTP_CLIENT_IP'])) { + $ip = $_SERVER['HTTP_CLIENT_IP']; + } else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } else { + $ip = $_SERVER['REMOTE_ADDR']; + } // It's possible for X_FORWARDED_FOR to have more than one CSV separated IP address, per @tuomassalo if(strpos($ip, ',') !== false && $useClient !== 2) { list($ip) = explode(',', $ip); @@ -966,17 +977,14 @@ class Session extends Wire implements \IteratorAggregate { /** @var User|null $user */ $user = null; - /** @var Sanitizer $sanitizer */ - $sanitizer = $this->wire('sanitizer'); - /** @var Users $users */ - $users = $this->wire('users'); - /** @var int $guestUserID */ - $guestUserID = $this->wire('config')->guestUserPageID; + $sanitizer = $this->wire()->sanitizer; + $users = $this->wire()->users; + $guestUserID = $this->wire()->config->guestUserPageID; $fail = true; $failReason = ''; - if(is_object($name) && $name instanceof User) { + if($name instanceof User) { $user = $name; $name = $user->name; } else { @@ -1005,7 +1013,7 @@ class Session extends Wire implements \IteratorAggregate { } else if($force === true || $this->authenticate($user, $pass)) { - $this->trackChange('login', $this->wire('user'), $user); + $this->trackChange('login', $this->wire()->user, $user); session_regenerate_id(true); $this->set('_user', 'id', $user->id); $this->set('_user', 'ts', time()); @@ -1108,24 +1116,22 @@ class Session extends Wire implements \IteratorAggregate { public function ___allowLogin($name, $user = null) { $allow = true; if(!strlen($name)) return false; - if(!$user || !$user instanceof User) { - $name = $this->wire('sanitizer')->pageNameUTF8($name); - $user = $this->wire('users')->get("name=" . $this->wire('sanitizer')->selectorValue($name)); + if(!$user instanceof User) { + $sanitizer = $this->wire()->sanitizer; + $name = $sanitizer->pageNameUTF8($name); + $user = $this->wire()->users->get('name=' . $sanitizer->selectorValue($name)); } - if(!$user || !$user->id || !$user instanceof User) return false; - if($user->isGuest()) return false; - $xroles = $this->wire('config')->loginDisabledRoles; - if(!is_array($xroles) && !empty($xroles)) $xroles = array($xroles); - if($name) {} - if($user) { - if($user->isUnpublished()) { - $allow = false; - } else if(is_array($xroles)) { - foreach($xroles as $xrole) { - if($user->hasRole($xrole)) { - $allow = false; - break; - } + if(!$user instanceof User || !$user->id) return false; + if($user->isGuest() || $user->isUnpublished()) return false; + $xroles = $this->config->loginDisabledRoles; + if(!is_array($xroles) && !empty($xroles)) { + $xroles = array($xroles); + } + if(is_array($xroles)) { + foreach($xroles as $xrole) { + if($user->hasRole($xrole)) { + $allow = false; + break; } } } @@ -1198,11 +1204,14 @@ class Session extends Wire implements \IteratorAggregate { session_regenerate_id(true); $_SESSION[$this->sessionKey] = array(); } - $user = $this->wire('user'); + $user = $this->wire()->user; + $users = $this->wire()->users; if($user) $this->logoutSuccess($user); - $guest = $this->wire('users')->getGuestUser(); - if($this->wire('languages') && "$user->language" != "$guest->language") $guest->language = $user->language; - $this->wire('users')->setCurrentUser($guest); + $guest = $users->getGuestUser(); + if($this->wire()->languages && "$user->language" != "$guest->language") { + $guest->language = $user->language; + } + $users->setCurrentUser($guest); $this->trackChange('logout', $user, $guest); return $this; } @@ -1470,8 +1479,7 @@ class Session extends Wire implements \IteratorAggregate { */ protected function wakeupNotices() { - /** @var Notices $notices */ - $notices = $this->wire('notices'); + $notices = $this->wire()->notices; if(!$notices) return; $types = array( @@ -1561,8 +1569,7 @@ class Session extends Wire implements \IteratorAggregate { // prevent multiple calls, just in case $this->skipMaintenance = true; - $config = $this->wire()->config; - $historyCnt = (int) ($config ? $config->sessionHistory : 0); + $historyCnt = (int) ($this->config ? $this->config->sessionHistory : 0); if($historyCnt) { diff --git a/wire/core/SessionCSRF.php b/wire/core/SessionCSRF.php index 36909d44..17c2419e 100644 --- a/wire/core/SessionCSRF.php +++ b/wire/core/SessionCSRF.php @@ -1,13 +1,5 @@ session->get($this, "name$id"); + $session = $this->wire()->session; + $tokenName = $session->get($this, "name$id"); if(!$tokenName) { $tokenName = 'TOKEN' . mt_rand() . "X" . time(); // token name always ends with timestamp - $this->session->set($this, "name$id", $tokenName); + $session->set($this, "name$id", $tokenName); } return $tokenName; } @@ -66,13 +61,14 @@ class SessionCSRF extends Wire { * */ public function getTokenValue($id = '') { + $session = $this->wire()->session; $tokenName = $this->getTokenName($id); - $tokenValue = $this->session->get($this, $tokenName); + $tokenValue = $session->get($this, $tokenName); if(empty($tokenValue)) { // $tokenValue = md5($this->page->path() . mt_rand() . microtime()) . md5($this->page->name . $this->config->userAuthSalt . mt_rand()); $rand = new WireRandom(); $tokenValue = $rand->base64(32, array('fast' => true)); - $this->session->set($this, $tokenName, $tokenValue); + $session->set($this, $tokenName, $tokenValue); } return $tokenValue; } @@ -83,7 +79,7 @@ class SessionCSRF extends Wire { * #pw-group-initiating * * @param int|string|null $id Optional unique ID for this token - * @return string + * @return int * */ public function getTokenTime($id = '') { @@ -122,13 +118,14 @@ class SessionCSRF extends Wire { * */ public function getSingleUseToken($id = '') { + $session = $this->wire()->session; if(!strlen($id)) $id = (string) mt_rand(); $name = $this->getTokenName($id); $time = $this->getTokenTime($id); $value = $this->getTokenValue($id); - $singles = $this->session->get($this, 'singles'); + $singles = $session->get($this, 'singles'); $singles[$name] = $value; - $this->session->set($this, 'singles', $singles); + $session->set($this, 'singles', $singles); return array( 'id' => $id, 'name' => $name, @@ -148,24 +145,30 @@ class SessionCSRF extends Wire { * */ public function hasValidToken($id = '', $reset = null) { + + $session = $this->wire()->session; + $config = $this->wire()->config; + $input = $this->wire()->input; $tokenName = $this->getTokenName($id); $tokenValue = $this->getTokenValue($id); + $headerName = "HTTP_X_$tokenName"; $valid = false; if(strlen($id)) { - $singles = $this->session->get($this, 'singles'); + $singles = $session->get($this, 'singles'); if(is_array($singles) && isset($singles[$tokenName])) { // remove single use token unset($singles[$tokenName]); - $this->session->set($this, 'singles', $singles); + $session->set($this, 'singles', $singles); if($reset !== false) $reset = true; } } + - if($this->config->ajax && isset($_SERVER["HTTP_X_$tokenName"]) && $_SERVER["HTTP_X_$tokenName"] === $tokenValue) { + if($config->ajax && isset($_SERVER[$headerName]) && $_SERVER[$headerName] === $tokenValue) { $valid = true; - } else if($this->input->post($tokenName) === $tokenValue) { + } else if($input->post($tokenName) === $tokenValue) { $valid = true; } @@ -185,7 +188,7 @@ class SessionCSRF extends Wire { * */ public function validate($id = '') { - if(!$this->config->protectCSRF) return true; + if(!$this->wire()->config->protectCSRF) return true; if($this->hasValidToken($id)) return true; $this->resetToken(); throw new WireCSRFException($this->_('This request was aborted because it appears to be forged.')); @@ -201,8 +204,9 @@ class SessionCSRF extends Wire { */ public function resetToken($id = '') { $tokenName = $this->getTokenName($id); - $this->session->remove($this, "name$id"); - $this->session->remove($this, $tokenName); + $session = $this->wire()->session; + $session->remove($this, "name$id"); + $session->remove($this, $tokenName); } /** @@ -212,7 +216,7 @@ class SessionCSRF extends Wire { * */ public function resetAll() { - $this->session->remove($this, true); + $this->wire()->session->remove($this, true); } /** diff --git a/wire/core/Template.php b/wire/core/Template.php index c8ec60d8..29c2354f 100644 --- a/wire/core/Template.php +++ b/wire/core/Template.php @@ -333,7 +333,7 @@ class Template extends WireData implements Saveable, Exportable { * */ protected function roleTypeNames($type) { - if(is_object($type) && $type instanceof Page) $type = $type->name; + if($type instanceof Page) $type = $type->name; if($type === 'view' || $type === 'roles' || $type === 'viewRoles' || $type === 'page-view') { return array('view', 'roles', 'page-view'); } else if($type === 'edit' || $type === 'page-edit' || $type === 'editRoles') { @@ -433,7 +433,7 @@ class Template extends WireData implements Saveable, Exportable { $has = $roles->has("name=$role"); } else if(is_int($role)) { $has = $roles->has("id=$role"); - $rolePage = $this->wire('roles')->get($role); + $rolePage = $this->wire()->roles->get($role); } else if($role instanceof Page) { $has = $roles->has($role); $rolePage = $role; @@ -519,11 +519,14 @@ class Template extends WireData implements Saveable, Exportable { if(!is_array($value)) $value = array(); $a = array(); + $roles = $this->wire()->roles; + $permissions = $this->wire()->permissions; + foreach($value as $roleID => $permissionIDs) { if(!ctype_digit("$roleID")) { // convert role name to ID - $roleID = $this->wire()->roles->get("name=$roleID")->id; + $roleID = $roles->get("name=$roleID")->id; } if(!$roleID) continue; @@ -534,7 +537,7 @@ class Template extends WireData implements Saveable, Exportable { if(!ctype_digit($test)) { // convert permission name to ID $revoke = strpos($permissionID, '-') === 0; - $permissionID = $this->wire()->permissions->get("name=$test")->id; + $permissionID = $permissions->get("name=$test")->id; if(!$permissionID) continue; if($revoke) $permissionID = "-$permissionID"; } diff --git a/wire/core/TemplateFile.php b/wire/core/TemplateFile.php index 574ac1ea..a16552c3 100644 --- a/wire/core/TemplateFile.php +++ b/wire/core/TemplateFile.php @@ -5,7 +5,7 @@ * * A template file that will be loaded and executed as PHP and its output returned. * - * ProcessWire 3.x, Copyright 2020 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @property bool $halt Set to true to halt during render, or use method $this->halt(); @@ -155,6 +155,7 @@ class TemplateFile extends WireData { * */ public function __construct($filename = '') { + parent::__construct(); if(self::$obStartLevel === null) self::$obStartLevel = ob_get_level(); if($filename) $this->setFilename($filename); } @@ -367,7 +368,7 @@ class TemplateFile extends WireData { protected function fileReady($filename) { $this->currentFilename = $filename; if($this->profiler) { - $f = str_replace($this->wire('config')->paths->root, '/', $filename); + $f = str_replace($this->wire()->config->paths->root, '/', $filename); $this->profilerEvent = $this->profiler->start($f, $this); } self::pushRenderStack($filename); @@ -400,7 +401,6 @@ class TemplateFile extends WireData { */ protected function ___fileFailed($filename, \Exception $e) { $this->fileFinished(); - if($e || $filename) {} // ignore return true; } @@ -419,7 +419,7 @@ class TemplateFile extends WireData { $this->savedInstance = ProcessWire::getCurrentInstance(); ProcessWire::setCurrentInstance($this->wire()); - $this->profiler = $this->wire('profiler'); + $this->profiler = $this->wire()->profiler; if($this->chdir !== false) { $cwd = getcwd(); @@ -495,42 +495,42 @@ class TemplateFile extends WireData { * */ public function getArray() { - return array_merge($this->wire('fuel')->getArray(), parent::getArray()); + return array_merge($this->wire()->fuel->getArray(), parent::getArray()); } /** * Get a set property from the template file, typically to check if a template has access to a given variable * - * @param string $property + * @param string $key * @return mixed Returns the value of the requested property, or NULL if it doesn't exist * */ - public function get($property) { - if($property === 'filename') return $this->filename; - if($property === 'appendFilename' || $property === 'appendFilenames') return $this->appendFilename; - if($property === 'prependFilename' || $property === 'prependFilenames') return $this->prependFilename; - if($property === 'currentFilename') return $this->currentFilename; - if($property === 'halt') return $this->halt; - if($property === 'trim') return $this->trim; - if($value = parent::get($property)) return $value; - if(isset(self::$globals[$property])) return self::$globals[$property]; + public function get($key) { + if($key === 'filename') return $this->filename; + if($key === 'appendFilename' || $key === 'appendFilenames') return $this->appendFilename; + if($key === 'prependFilename' || $key === 'prependFilenames') return $this->prependFilename; + if($key === 'currentFilename') return $this->currentFilename; + if($key === 'halt') return $this->halt; + if($key === 'trim') return $this->trim; + if($value = parent::get($key)) return $value; + if(isset(self::$globals[$key])) return self::$globals[$key]; return null; } /** * Set a property * - * @param string $property + * @param string $key * @param mixed $value * @return $this|WireData * */ - public function set($property, $value) { - if($property === 'halt') { + public function set($key, $value) { + if($key === 'halt') { $this->halt($value); return $this; } - return parent::set($property, $value); + return parent::set($key, $value); } /** diff --git a/wire/core/Templates.php b/wire/core/Templates.php index 45febf27..0511a255 100644 --- a/wire/core/Templates.php +++ b/wire/core/Templates.php @@ -249,9 +249,7 @@ class Templates extends WireSaveableItems { */ public function get($key) { if($key === 'path') return $this->wire()->config->paths->templates; - $value = $this->getWireArray()->get($key); - if(is_null($value)) $value = parent::get($key); - return $value; + return parent::get($key); } /** @@ -276,17 +274,17 @@ class Templates extends WireSaveableItems { throw new WireException("Template '$item' cannot be saved because it has no fieldgroup assigned"); } if(!$item->fieldgroup->id) { - throw new WireException("You must save Fieldgroup '{$item->fieldgroup->name}' before adding to Template '{$item}'"); + throw new WireException("You must save Fieldgroup '{$item->fieldgroup->name}' before adding to Template '$item'"); } $rolesChanged = $item->isChanged('useRoles'); if($this->wire()->pages->get('/')->template->id == $item->id) { if(!$item->useRoles) { - throw new WireException("Template '{$item}' is used by the homepage and thus must manage access"); + throw new WireException("Template '$item' is used by the homepage and thus must manage access"); } if(!$item->hasRole('guest')) { - throw new WireException("Template '{$item}' is used by the homepage and thus must have the 'guest' role assigned."); + throw new WireException("Template '$item' is used by the homepage and thus must have the 'guest' role assigned."); } } @@ -297,6 +295,7 @@ class Templates extends WireSaveableItems { if($result && !$isNew && $item->fieldgroupPrevious && $item->fieldgroupPrevious->id != $item->fieldgroup->id) { // the fieldgroup has been changed // remove data from all fields that are not part of the new fieldgroup + /** @var FieldsArray $removeFields */ $removeFields = $this->wire(new FieldsArray()); foreach($item->fieldgroupPrevious as $field) { if(!$item->fieldgroup->has($field)) { @@ -305,6 +304,7 @@ class Templates extends WireSaveableItems { } if(count($removeFields)) { foreach($removeFields as $field) { + /** @var Field $field */ $field->type->deleteTemplateField($item, $field); } /* @@ -320,6 +320,7 @@ class Templates extends WireSaveableItems { } if($rolesChanged) { + /** @var PagesAccess $access */ $access = $this->wire(new PagesAccess()); $access->updateTemplate($item); } @@ -366,7 +367,7 @@ class Templates extends WireSaveableItems { * * @param Template|Saveable $item Template to clone * @param string $name Name of new template that will be created, or omit to auto-assign. - * @return bool|Saveable|Template $item Returns the new Template on success, or false on failure + * @return bool|Template $item Returns the new Template on success, or false on failure * */ public function ___clone(Saveable $item, $name = '') { @@ -392,6 +393,7 @@ class Templates extends WireSaveableItems { $item->fieldgroup = $fieldgroup; } + /** @var Template|bool $item */ $item = parent::___clone($item, $name); if($item && $item->id && !$item->altFilename) { @@ -434,7 +436,7 @@ class Templates extends WireSaveableItems { $fieldgroup = $template->fieldgroup; $t = $this->get($name); - if($t && $t instanceof Template && $t->id != $template->id) { + if($t instanceof Template && $t->id != $template->id) { throw new WireException("Template '$name' already exists"); } @@ -516,7 +518,7 @@ class Templates extends WireSaveableItems { $values = array(); foreach($data[$key] as $id) { if(ctype_digit("$id")) $id = (int) $id; - $t = $this->wire('templates')->get($id); + $t = $this->get($id); if($t) $values[] = $t->name; } $data[$key] = $values; @@ -524,11 +526,12 @@ class Templates extends WireSaveableItems { // convert roles to guids if($template->useRoles) { + $roles = $this->wire()->roles; foreach(array('roles', 'editRoles', 'addRoles', 'createRoles') as $key) { if(!isset($data[$key])) continue; $values = array(); foreach($data[$key] as $id) { - $role = $id instanceof Role ? $id : $this->wire()->roles->get((int) $id); + $role = $id instanceof Role ? $id : $roles->get((int) $id); $values[] = $role->name; } $data[$key] = $values; @@ -598,6 +601,7 @@ class Templates extends WireSaveableItems { if($key == 'fieldgroups_id' && !ctype_digit("$value")) { $fieldgroup = $fieldgroups->get($value); if(!$fieldgroup) { + /** @var Fieldgroup $fieldgroup */ $fieldgroup = $this->wire(new Fieldgroup()); $fieldgroup->name = $value; } @@ -636,7 +640,7 @@ class Templates extends WireSaveableItems { try { $template->set($key, $value); if($key == 'roles') $template->getRoles(); // forces reload of roles (and resulting error messages) - $error = $template->errors("clear"); + $error = $template->errors('clear'); } catch(\Exception $e) { $this->trackException($e, false); $error = array($e->getMessage()); @@ -723,7 +727,7 @@ class Templates extends WireSaveableItems { if($getAll) { // build list of all parents (will check access outside loop) - if($numParentPages) $foundParents->add($parentPages); + $foundParents->add($parentPages); continue; } else if($numParentPages > 1) { // multiple possible parents, we can early-exit @@ -917,7 +921,7 @@ class Templates extends WireSaveableItems { $defaultPermissions = array('page-view', 'page-edit', 'page-create', 'page-add'); $updated = false; - if(is_string($role) || is_int($role)) $role = $this->wire('roles')->get($role); + if(is_string($role) || is_int($role)) $role = $this->wire()->roles->get($role); if(!$role instanceof Role) throw new WireException("Unknown role for Template::setPermissionByRole"); if(is_string($permission) && in_array($permission, $defaultPermissions)) { @@ -1005,8 +1009,7 @@ class Templates extends WireSaveableItems { * */ public function _hookFinished(HookEvent $e) { - if($e) {} - foreach($this->fileModTemplates as $id => $template) { + foreach($this->fileModTemplates as /* $id => */ $template) { if($template->isChanged('modified') || $template->isChanged('ns')) { $template->save(); } diff --git a/wire/core/Tfa.php b/wire/core/Tfa.php index 7a98cfd4..f9276f9d 100644 --- a/wire/core/Tfa.php +++ b/wire/core/Tfa.php @@ -5,7 +5,7 @@ * * This class is for “Tfa” modules to extend. See the TfaEmail and TfaTotp modules as examples. * - * ProcessWire 3.x, Copyright 2020 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @@ -272,6 +272,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ public function remember(User $user, array $settings) { + /** @var RememberTfa $remember */ $remember = $this->wire(new RememberTfa($this, $user, $settings)); $remember->setDays($this->rememberDays); $remember->setFingerprints($this->rememberFingerprints); @@ -421,8 +422,10 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ public function isValidUserCode(User $user, $code, array $settings) { - if($user && $code && $settings) throw new WireException('Modules should not call this method'); - return false; + if($code && $settings) throw new WireException('Modules should not call this method'); + $value = false; + /** @var bool|int $value */ + return $value; } /** @@ -455,7 +458,6 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ public function enabledForUser(User $user, array $settings) { - if($user) {} // ignore $enabled = empty($settings['enabled']) ? false : true; return $enabled; } @@ -475,7 +477,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { $module = $this->getModule(); if(!$module) return false; $result = $module->process(); // redirects may occur - if($result && $result instanceof User && $result->id) return true; + if($result instanceof User && $result->id) return true; return false; } @@ -579,8 +581,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { if($this->authCodeForm) return $this->authCodeForm; - /** @var Modules $modules */ - $modules = $this->wire('modules'); + $modules = $this->wire()->modules; /** @var InputfieldForm $form */ $form = $modules->get('InputfieldForm'); @@ -602,6 +603,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { $form->add($f); if($this->rememberDays) { + /** @var InputfieldCheckbox $f */ $f = $modules->get('InputfieldCheckbox'); $f->attr('id+name', 'tfa_remember'); $f->attr('value', $this->rememberDays); @@ -621,7 +623,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { if($this->showCancel) { $cancelUrl = $this->url(); - $cancelLabel = $this->sanitizer->entities1($this->cancelLabel); + $cancelLabel = $this->wire()->sanitizer->entities1($this->cancelLabel); $form->appendMarkup .= str_replace( array('{url}', '{label}'), array($cancelUrl, $cancelLabel), @@ -664,17 +666,14 @@ class Tfa extends WireData implements Module, ConfigurableModule { */ public function ___process() { - /** @var WireInput $input */ - $input = $this->wire('input'); - - /** @var Session $session */ - $session = $this->wire('session'); + $input = $this->wire()->input; + $session = $this->wire()->session; /** @var string|null $key */ $key = $input->get($this->keyName); // invalid key, abort - if(empty($key) || $key !== $this->getSessionKey() || $this->wire('user')->isLoggedin()) { + if(empty($key) || $key !== $this->getSessionKey() || $this->wire()->user->isLoggedin()) { return $this->sessionReset('./'); } @@ -683,7 +682,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { $userID = (int) $this->sessionGet('id'); $userName = $this->sessionGet('name'); $userPash = $this->sessionGet('pash'); - $user = $userID ? $this->wire('users')->get($userID) : null; + $user = $userID ? $this->wire()->users->get($userID) : null; $initTime = (int) $this->sessionGet('time'); $numTries = (int) $this->sessionGet('tries'); $maxTries = 3; @@ -778,7 +777,6 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ public function ___getUserSettingsInputfields(User $user, InputfieldWrapper $fieldset, $settings) { - if($user || $fieldset || $settings) {} // ignore $script = 'script'; // jump to and highlight fieldset they need to complete (where supported) $fieldset->appendMarkup .= @@ -798,7 +796,6 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ public function ___getUserEnabledInputfields(User $user, InputfieldWrapper $fieldset, $settings) { - if($user) {} // ignore $fieldset->label .= ' - ' . $this->enabledLabel; $fieldset->icon = 'user-secret'; @@ -826,7 +823,6 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ public function ___processUserSettingsInputfields(User $user, InputfieldWrapper $fieldset, $settings, $settingsPrev) { - if($user || $fieldset || $settings || $settingsPrev) {} // ignore return $settings; } @@ -841,7 +837,6 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ public function ___processUserEnabledInputfields(User $user, InputfieldWrapper $fieldset, $settings, $settingsPrev) { - if($user || $fieldset || $settings || $settingsPrev) {} // ignore if($this->wire()->input->post('_tfa_clear_remember')) { unset($settings['remember']); $this->remember($user, $settings)->disableAll(); @@ -857,7 +852,6 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ public function getModuleConfigInputfields(InputfieldWrapper $inputfields) { - if($inputfields) {} // ignore } /*** SESSION *******************************************************************************************/ @@ -871,7 +865,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ protected function sessionGet($key, $blankValue = null) { - $value = $this->wire('session')->getFor($this->keyName, $key); + $value = $this->wire()->session->getFor($this->keyName, $key); if($value === null) $value = $blankValue; return $value; } @@ -886,8 +880,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ protected function sessionSet($key, $value = null) { - /** @var Session $session */ - $session = $this->wire('session'); + $session = $this->wire()->session; $values = is_array($key) ? $key : array($key => $value); foreach($values as $k => $v) { $session->setFor($this->keyName, $k, $v); @@ -898,7 +891,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { * Remove all session variables set for this module * * @param string $redirectURL Optionally redirect to URL after reset - * @return bool|string|int + * @return false * */ protected function sessionReset($redirectURL = '') { @@ -997,7 +990,6 @@ class Tfa extends WireData implements Module, ConfigurableModule { * */ protected function getDefaultUserSettings(User $user) { - if($user) {} return array( 'enabled' => false, // whether user has this auth method enabled ); @@ -1023,7 +1015,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { $defaults = $this->getDefaultUserSettings($user); - $field = $this->wire('fields')->get($this->userFieldName); + $field = $this->wire()->fields->get($this->userFieldName); if(!$field) return $defaults; $value = $user->get($field->name); @@ -1031,7 +1023,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { $table = $field->getTable(); $sql = "SELECT `settings` FROM `$table` WHERE pages_id=:user_id"; - $query = $this->wire('database')->prepare($sql); + $query = $this->wire()->database->prepare($sql); $query->bindValue(':user_id', $user->id, \PDO::PARAM_INT); $query->execute(); $data = $query->fetchColumn(); @@ -1072,7 +1064,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { if(!empty($settings[$className])) $settings = $settings[$className]; // just in case it is $tfaSettings $tfaSettings = array($className => $settings); $user->setQuietly('_tfa_settings', $tfaSettings); - $field = $this->wire('fields')->get($this->userFieldName); + $field = $this->wire()->fields->get($this->userFieldName); if(!$field) return false; if(!$user->get($field->name)) return false; // no module selected $table = $field->getTable(); @@ -1096,7 +1088,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { if($this->wire()->user->isLoggedin()) { // if user is logged in, user can be current user or one being edited - $process = $this->wire('process'); + $process = $this->wire()->process; // if process API variable not adequate, attempt to get from current page if(!$process || $process == 'ProcessPageView') { @@ -1105,7 +1097,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { } // check if we have a process - if($process && $process instanceof Process) { + if($process instanceof Process) { // user being edited like in ProcessUser, ProcessProfile or ProcessPageEdit if($process instanceof WirePageEditor) { $user = $process->getPage(); @@ -1123,7 +1115,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { } // if not a user being edited, user can only be current user - if(!$user || !$user instanceof User || !$user->id) { + if(!$user instanceof User || !$user->id) { $user = $this->wire()->user; } @@ -1188,7 +1180,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { )); } - if(!$module || !$module instanceof Tfa) return false; + if(!$module instanceof Tfa) return false; $settings = $module->getUserSettings($user); if(!$module->enabledForUser($user, $settings)) return false; @@ -1285,6 +1277,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { } foreach($fieldset->getAll() as $f) { + /** @var Inputfield $f */ $name = $f->attr('name'); if(strpos($name, '_tfa_') === 0) list(,$name) = explode('_tfa_', $name); $f->attr('name', "_tfa_$name"); @@ -1328,6 +1321,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { $changes = array(); foreach($fieldset->getAll() as $f) { + /** @var Inputfield $f */ $name = $f->attr('name'); if(strpos($name, '_tfa_') === 0) list(,$name) = explode('_tfa_', $name); $settings[$name] = $f->val(); @@ -1340,7 +1334,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { } foreach($settings as $name => $value) { - if(!isset($settingsPrev[$name]) || $settingsPrev[$name] !== $settings[$name]) { + if(!isset($settingsPrev[$name]) || $settingsPrev[$name] !== $value) { $changes[$name] = $name; } } @@ -1392,7 +1386,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { 'noInit' => true, 'noCache' => true, )); - if(!$module || !$module instanceof Tfa) continue; + if(!$module instanceof Tfa) continue; if($inputfield instanceof InputfieldRadios) { $label = $module->getTfaTypeName() . ' - ' . $module->getTfaTypeSummary(); } else { @@ -1430,7 +1424,6 @@ class Tfa extends WireData implements Module, ConfigurableModule { $this->getUserEnabledInputfields($user, $fieldset, $settings); $session->removeFor('_user', 'requireTfa'); // set by ProcessLogin } else { - /** @var InputfieldFieldset $fieldset */ $this->getUserSettingsInputfields($user, $fieldset, $settings); if(!$input->requestMethod('POST')) { $this->warning( @@ -1445,6 +1438,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { $inputfield->getParent()->insertAfter($fieldset, $inputfield); foreach($fieldset->getAll() as $f) { + /** @var Inputfield $f */ $name = $f->attr('name'); if(isset($settings[$name])) $f->val($settings[$name]); if(strpos($name, '_tfa_') !== 0) $f->attr('name', "_tfa_$name"); @@ -1469,7 +1463,7 @@ class Tfa extends WireData implements Module, ConfigurableModule { $this->wire($field); $field->name = $fieldName; $field->label = $this->defaults['fieldTfaTypeLabel']; - $field->type = $this->wire('fieldtypes')->get('FieldtypeModule'); + $field->type = $this->wire()->fieldtypes->get('FieldtypeModule'); $field->flags = Field::flagSystem; $field->description = $this->defaults['fieldTfaTypeDescLabel']; $field->icon = 'user-secret'; @@ -1479,11 +1473,11 @@ class Tfa extends WireData implements Module, ConfigurableModule { $field->set('labelField', 'title-summary'); $field->set('inputfieldClass', 'InputfieldRadios'); $field->set('blankType', 'zero'); - $this->wire('fields')->save($field); + $this->wire()->fields->save($field); $this->message("Added field: $field->name", Notice::debug); // add a custom “settings” column to the field $table = $field->getTable(); - $this->wire('database')->exec("ALTER TABLE `$table` ADD `settings` MEDIUMTEXT"); + $this->wire()->database->exec("ALTER TABLE `$table` ADD `settings` MEDIUMTEXT"); } // add user_tfa field to all user template fieldgroups @@ -1791,7 +1785,7 @@ class RememberTfa extends Wire { * Disable one or more cookie/remembered client by name(s) * * @param array|string $names - * @return bool + * @return int * */ public function disable($names) { @@ -1851,7 +1845,7 @@ class RememberTfa extends Wire { 'httponly' => true, 'domain' => '', ); - if($this->config->https) $options['secure'] = true; + if($this->config->https) $cookieOptions['secure'] = true; $cookieName = $this->cookieName($cookieName); $this->debugNote("Setting cookie: $cookieName=$cookieValue"); return $this->wire()->input->cookie->set($cookieName, $cookieValue, $cookieOptions); @@ -1928,9 +1922,10 @@ class RememberTfa extends Wire { */ public function ___getFingerprintArray() { + $config = $this->wire()->config; $agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'noagent'; - $fwip = ''; + if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $fwip .= $_SERVER['HTTP_X_FORWARDED_FOR']; if(isset($_SERVER['HTTP_CLIENT_IP'])) $fwip .= ' ' . $_SERVER['HTTP_CLIENT_IP']; if(empty($fwip)) $fwip = 'nofwip'; @@ -1939,8 +1934,8 @@ class RememberTfa extends Wire { 'agent' => $agent, 'agentVL' => preg_replace('![^a-zA-Z]!', '', $agent), // versionless agent 'accept' => (isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : 'noaccept'), - 'scheme' => ($this->config->https ? 'HTTPS' : 'http'), - 'host' => $this->config->httpHost, + 'scheme' => ($config->https ? 'HTTPS' : 'http'), + 'host' => $config->httpHost, 'ip' => (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'noip'), 'fwip' => $fwip, ); @@ -2007,4 +2002,4 @@ class RememberTfa extends Wire { if(self::debug) $this->warning($note); } -} \ No newline at end of file +} diff --git a/wire/core/User.php b/wire/core/User.php index f35b64e0..55121eec 100644 --- a/wire/core/User.php +++ b/wire/core/User.php @@ -58,8 +58,12 @@ class User extends Page { */ public function wired() { parent::wired(); + // intentionally duplicated from __construct() in case a multi-instance environment + // and we got the wrong instance in __construct() $template = $this->wire()->templates->get('user'); - if($template !== $this->template && (!$this->template || $this->template->name === 'user')) $this->template = $template; + if($template !== $this->template && (!$this->template || $this->template->name === 'user')) { + $this->template = $template; + } $this->_parent_id = $this->wire()->config->usersPageID; } @@ -87,7 +91,7 @@ class User extends Page { if(empty($roles)) { // do nothing - } else if(is_object($role) && $role instanceof Page) { + } else if($role instanceof Page) { $has = $roles->has($role); } else if(ctype_digit("$role")) { @@ -129,8 +133,10 @@ class User extends Page { * */ public function addRole($role) { - if(is_string($role) || is_int($role)) $role = $this->wire()->roles->get($role); - if(is_object($role) && $role instanceof Role) { + if(is_string($role) || is_int($role)) { + $role = $this->wire()->roles->get($role); + } + if($role instanceof Role) { $this->get('roles')->add($role); return true; } @@ -155,8 +161,10 @@ class User extends Page { * */ public function removeRole($role) { - if(is_string($role) || is_int($role)) $role = $this->wire()->roles->get($role); - if(is_object($role) && $role instanceof Role) { + if(is_string($role) || is_int($role)) { + $role = $this->wire()->roles->get($role); + } + if($role instanceof Role) { $this->get('roles')->remove($role); return true; } @@ -242,7 +250,7 @@ class User extends Page { $permission = $permissions->get((int) $name); } else if($name == 'page-rename') { // optional permission that, if not installed, page-edit is substituted for - if($this->wire('permissions')->has('page-rename')) { + if($permissions->has('page-rename')) { $permission = $permissions->get('page-rename'); } else { $permission = $permissions->get('page-edit'); @@ -263,19 +271,20 @@ class User extends Page { if(!$permission || !$permission->id) return false; - /** @var PageArray $roles */ - $roles = $this->getUnformatted('roles'); - if(empty($roles) || !$roles instanceof PageArray) return false; + /** @var PageArray $userRoles */ + $userRoles = $this->getUnformatted('roles'); + if(empty($userRoles) || !$userRoles instanceof PageArray) return false; $has = false; $accessTemplate = is_null($page) ? false : $page->getAccessTemplate($permission->name); if(is_null($accessTemplate)) return false; - foreach($roles as $key => $role) { + foreach($userRoles as $role) { + /** @var Role $role */ if(!$role || !$role->id) continue; $context = null; - if(!is_null($page)) { + if($page !== null) { // @todo some of this logic has been duplicated in Role::hasPermission, so code within this if() may be partially redundant if(!$page->id) continue; @@ -321,14 +330,14 @@ class User extends Page { */ protected function ___hasTemplatePermission($name, $template) { - if(is_object($name)) $name = $name->name; + if($this->isSuperuser()) return true; - if($this->isSuperuser()) return true; + if(is_object($name)) $name = $name->name; if($template instanceof Template) { // fantastic then } else if(is_string($template) || is_int($template)) { - $template = $this->templates->get($this->wire()->sanitizer->name($template)); + $template = $this->wire()->templates->get($this->wire()->sanitizer->name($template)); if(!$template) return false; } else { return false; @@ -338,12 +347,12 @@ class User extends Page { // because we don't have any page context to inherit from at this point // if(!$template->useRoles) return false; - /** @var PageArray $roles */ - $roles = $this->get('roles'); - if(empty($roles)) return false; + /** @var PageArray $userRoles */ + $userRoles = $this->get('roles'); + if(empty($userRoles)) return false; $has = false; - foreach($roles as $role) { + foreach($userRoles as $role) { /** @var Role $role */ // @todo much of this logic has been duplicated in Role::hasPermission, so code within this foreach() may be partially redundant @@ -398,11 +407,11 @@ class User extends Page { public function getPermissions(Page $page = null) { // Does not currently include page-add or page-create permissions (runtime). if($this->isSuperuser()) return $this->wire()->permissions->getIterator(); // all permissions - $permissions = $this->wire()->pages->newPageArray(); - /** @var PageArray $roles */ - $roles = $this->get('roles'); - if(empty($roles)) return $permissions; - foreach($roles as $key => $role) { + $userPermissions = $this->wire()->pages->newPageArray(); + /** @var PageArray $userRoles */ + $userRoles = $this->get('roles'); + if(empty($userRoles)) return $userPermissions; + foreach($userRoles as $role) { if($page && !$page->hasAccessRole($role)) continue; foreach($role->permissions as $permission) { if($page && $permission->name == 'page-edit') { @@ -410,10 +419,10 @@ class User extends Page { if(!$accessTemplate) continue; if(!in_array($role->id, $accessTemplate->editRoles)) continue; } - $permissions->add($permission); + $userPermissions->add($permission); } } - return $permissions; + return $userPermissions; } /** @@ -435,11 +444,11 @@ class User extends Page { $is = false; } else { $superuserRoleID = (int) $config->superUserRolePageID; - /** @var PageArray $roles */ - $roles = $this->getUnformatted('roles'); - if(empty($roles)) return false; // no cache intentional + /** @var PageArray $userRoles */ + $userRoles = $this->getUnformatted('roles'); + if(empty($userRoles)) return false; // no cache intentional $is = false; - foreach($roles as $role) { + foreach($userRoles as $role) { /** @var Role $role */ if(((int) $role->id) === $superuserRoleID) { $is = true; @@ -523,7 +532,7 @@ class User extends Page { */ protected function getFieldValue($key, $selector = '') { $value = parent::getFieldValue($key, $selector); - if(!$value && $key == 'language') { + if(!$value && $key === 'language') { $languages = $this->wire()->languages; if($languages) $value = $languages->getDefault(); } @@ -567,7 +576,7 @@ class User extends Page { * * #pw-internal * - * @return Pages|PagesType|Users + * @return Users * */ public function getPagesManager() { @@ -611,7 +620,7 @@ class User extends Page { * */ public function ___changed($what, $old = null, $new = null) { - if($what == 'roles' && is_bool($this->isSuperuser)) $this->isSuperuser = null; + if($what === 'roles' && is_bool($this->isSuperuser)) $this->isSuperuser = null; parent::___changed($what, $old, $new); } diff --git a/wire/core/Users.php b/wire/core/Users.php index 18930676..4fefadf6 100644 --- a/wire/core/Users.php +++ b/wire/core/Users.php @@ -69,10 +69,11 @@ class Users extends PagesType { * Get the user by name, ID or selector string * * @param string $selectorString - * @return Page|NullPage|null + * @return User|NullPage|null * */ public function get($selectorString) { + /** @var User|NullPage|null $user */ $user = parent::get($selectorString); return $user; } diff --git a/wire/core/WireAction.php b/wire/core/WireAction.php index eb1978b1..fd73675d 100644 --- a/wire/core/WireAction.php +++ b/wire/core/WireAction.php @@ -7,6 +7,10 @@ * * This file is licensed under the MIT license * https://processwire.com/about/license/mit/ + * + * @method bool action($item) + * @method int executeMultiple($items) + * @method InputfieldWrapper getConfigInputfields() * */ abstract class WireAction extends WireData implements Module { @@ -42,6 +46,7 @@ abstract class WireAction extends WireData implements Module { * */ public function __construct() { + parent::__construct(); // $this->set('key', 'value'); } diff --git a/wire/core/WireClassLoader.php b/wire/core/WireClassLoader.php index d977e4c1..a93896ce 100644 --- a/wire/core/WireClassLoader.php +++ b/wire/core/WireClassLoader.php @@ -13,7 +13,7 @@ * This file is licensed under the MIT license * https://processwire.com/about/license/mit/ * - * ProcessWire 3.x, Copyright 2020 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * */ @@ -243,11 +243,11 @@ class WireClassLoader { $level++; if($this->modules === null && $this->wire) { - $this->modules = $this->wire->wire('modules'); + $this->modules = $this->wire->wire()->modules; } if($this->debug === null && $this->wire) { - $this->debug = $this->wire->wire('config')->debug; + $this->debug = $this->wire->wire()->config->debug; } if($this->debug) { @@ -267,7 +267,6 @@ class WireClassLoader { $name = array_pop($parts); $namespace = implode("\\", $parts); } else { - $_parts = array(); if(strpos($className, "\\") !== false) { $parts = explode("\\", $className); $name = array_pop($parts); @@ -322,7 +321,7 @@ class WireClassLoader { /** @noinspection PhpIncludeInspection */ include_once($found); if($this->debug) { - $file = $this->wire ? str_replace($this->wire->wire('config')->paths->root, '/', $found) : $found; + $file = $this->wire ? str_replace($this->wire->wire()->config->paths->root, '/', $found) : $found; $this->debugLog[$_className] = $file . $levelHistoryStr; } if($this->findFile === true && $level === 1) { diff --git a/wire/core/WireSaveableItems.php b/wire/core/WireSaveableItems.php index d1653462..f046d495 100644 --- a/wire/core/WireSaveableItems.php +++ b/wire/core/WireSaveableItems.php @@ -110,11 +110,12 @@ abstract class WireSaveableItems extends Wire implements \IteratorAggregate { $database = $this->wire()->database; - if(is_object($selectors) && $selectors instanceof Selectors) { + if($selectors instanceof Selectors) { // iterable selectors } else if($selectors && is_string($selectors)) { // selector string, convert to iterable selectors $selectorString = $selectors; + /** @var Selectors $selectors */ $selectors = $this->wire(new Selectors()); $selectors->init($selectorString); @@ -189,6 +190,7 @@ abstract class WireSaveableItems extends Wire implements \IteratorAggregate { $fields[$k] = "$table.$v"; } + /** @var DatabaseQuerySelect $query */ $query = $this->wire(new DatabaseQuerySelect()); $query->select($fields)->from($table); if($sort = $this->getSort()) $query->orderby($sort); @@ -371,12 +373,15 @@ abstract class WireSaveableItems extends Wire implements \IteratorAggregate { */ public function ___delete(Saveable $item) { $blank = $this->makeBlankItem(); - if(!$item instanceof $blank) throw new WireException("WireSaveableItems::delete(item) requires item to be of type '" . $blank->className() . "'"); + if(!$item instanceof $blank) { + $typeName = $blank->className(); + throw new WireException("WireSaveableItems::delete(item) requires item to be of type '$typeName'"); + } $id = (int) $item->id; if(!$id) return false; - $database = $this->wire('database'); + $database = $this->wire()->database; $this->deleteReady($item); $this->getWireArray()->remove($item); @@ -465,9 +470,9 @@ abstract class WireSaveableItems extends Wire implements \IteratorAggregate { return $value; } - public function __get($key) { - $value = $this->get($key); - if($value === null) $value = parent::__get($key); + public function __get($name) { + $value = $this->get($name); + if($value === null) $value = parent::__get($name); return $value; } @@ -548,6 +553,7 @@ abstract class WireSaveableItems extends Wire implements \IteratorAggregate { } foreach($items as $field) { + /** @var WireData $field */ $index = null; if($matchValue !== null) { if($matchArray) { @@ -748,7 +754,7 @@ abstract class WireSaveableItems extends Wire implements \IteratorAggregate { * */ public function log($str, Saveable $item = null) { - $logs = $this->wire('config')->logs; + $logs = $this->wire()->config->logs; $name = $this->className(array('lowercase' => true)); if($logs && in_array($name, $logs)) { if($item && strpos($str, "'$item->name'") === false) $str .= " '$item->name'"; diff --git a/wire/core/WireSaveableItemsLookup.php b/wire/core/WireSaveableItemsLookup.php index fb91cf50..d89781f7 100644 --- a/wire/core/WireSaveableItemsLookup.php +++ b/wire/core/WireSaveableItemsLookup.php @@ -198,7 +198,7 @@ abstract class WireSaveableItemsLookup extends WireSaveableItems { if($item_id) { $sql = "INSERT INTO $lookupTable SET {$table}_id=:item_id, $lookupField=:value_id, sort=:sort"; $query = $database->prepare($sql); - foreach($item->getLookupItems() as $key => $value) { + foreach($item->getLookupItems() as $value) { $value_id = (int) $value->id; $query->bindValue(":item_id", $item_id, \PDO::PARAM_INT); $query->bindValue(":value_id", $value_id, \PDO::PARAM_INT); diff --git a/wire/modules/LanguageSupport/LanguageSupport.module b/wire/modules/LanguageSupport/LanguageSupport.module index 18b42e9d..49e8d059 100644 --- a/wire/modules/LanguageSupport/LanguageSupport.module +++ b/wire/modules/LanguageSupport/LanguageSupport.module @@ -34,7 +34,7 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { 'ProcessLanguageTranslator', ), 'addFlag' => Modules::flagsNoUserConfig - ); + ); } /** @@ -92,6 +92,8 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { * */ public function __construct() { + + parent::__construct(); $this->set('initialized', false); @@ -129,7 +131,9 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { // document which pages were already cached at this point, as their values may need // to be reloaded to account for language fields. - foreach($pages->getCache() as $id => $value) $this->earlyCachedPages[$id] = $value; + foreach($pages->getCache() as $id => $value) { + $this->earlyCachedPages[$id] = $value; + } // prevent possible double init if($this->initialized) return; @@ -203,8 +207,8 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { $this->addHookAfter('Inputfield::processInput', $this, 'hookInputfieldAfterProcessInput'); $this->addHookBefore('Inputfield::processInput', $this, 'hookInputfieldBeforeProcessInput'); $this->addHookAfter('Field::getInputfield', $this, 'hookFieldGetInputfield'); - $this->pages->addHook('added', $this, 'hookPageAdded'); - $this->pages->addHook('deleteReady', $this, 'hookPageDeleteReady'); + $pages->addHook('added', $this, 'hookPageAdded'); + $pages->addHook('deleteReady', $this, 'hookPageDeleteReady'); $this->addHook('Page::setLanguageValue', $this, 'hookPageSetLanguageValue'); $this->addHook('Page::getLanguageValue', $this, 'hookPageGetLanguageValue'); @@ -257,7 +261,7 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { // unset the values from all the early cached pages since they didn't recognize languages // this will force them to reload when accessed - foreach($this->earlyCachedPages as $id => $p) { + foreach($this->earlyCachedPages as /* $id => */ $p) { $t = $p->trackChanges(); if($t) $p->setTrackChanges(false); foreach($fieldNames as $name) unset($p->$name); @@ -281,6 +285,9 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { * */ protected function editableInputfield(Inputfield $inputfield) { + + $page = $this->wire()->page; + $alwaysAllowInputfields = array( 'InputfieldWrapper', 'InputfieldPageName', @@ -289,16 +296,18 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { 'InputfieldHidden', ); // ignore this call if in ProcessProfile - if($this->wire('page')->process == 'ProcessProfile') return true; - if($this->wire('page')->process == 'ProcessLanguage') return true; + if($page->process == 'ProcessProfile') return true; + if($page->process == 'ProcessLanguage') return true; + + $user = $this->wire()->user; + $languages = $this->wire()->languages; - $user = $this->wire('user'); if($user->isSuperuser()) return true; if($inputfield->getSetting('useLanguages')) return true; if(!$this->LanguageSupportFields) return true; - $permissions = $this->wire('languages')->getPageEditPermissions(); + $permissions = $languages->getPageEditPermissions(); if(!isset($permissions['none'])) return true; - if(!$this->wire('process') instanceof WirePageEditor) return true; + if(!$this->wire()->process instanceof WirePageEditor) return true; if($inputfield->name == 'delete_page') return true; $allow = false; foreach($alwaysAllowInputfields as $type) { @@ -310,7 +319,8 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { } if($allow) return true; if($inputfield->hasFieldtype && $this->LanguageSupportFields->isAlternateField($inputfield->name)) return true; - if($this->wire('languages')->editable('none')) return true; + if($languages->editable('none')) return true; + return false; } @@ -378,7 +388,8 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { if(!strlen($label)) $label = $language->name; $class = 'LanguageSupport'; $labelClass = 'LanguageSupportLabel detail'; - if(!$this->wire('languages')->editable($language)) { + + if(!$this->wire()->languages->editable($language)) { $labelClass .= ' LanguageNotEditable'; $class .= ' LanguageNotEditable'; $label = "$label"; @@ -393,6 +404,7 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { $out = "
" . "" . $out . "
"; + return $out; } @@ -407,6 +419,7 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { public function hookInputfieldAfterRender(HookEvent $event) { static $numLanguages = null; + if(!$event->return) return; // if already empty, nothing to do /** @var Inputfield $inputfield */ @@ -415,14 +428,18 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { $renderValueMode = $event->method == 'renderValue'; - /** @var Languages $languages */ - $languages = $this->wire('languages'); + $languages = $this->wire()->languages; + if(is_null($numLanguages)) $numLanguages = $languages->count(); // provide an automatic translation for some system/default fields if they've not been overridden in the fields editor - if($name == 'language' && $inputfield->label == 'Language') $inputfield->label = $this->_('Language'); // Label for 'language' field in user profile - else if($name == 'email' && $inputfield->label == 'E-Mail Address') $inputfield->label = $this->_('E-Mail Address'); // Label for 'email' field in user profile - else if($name == 'title' && $inputfield->label == 'Title') $inputfield->label = $this->_('Title'); // Label for 'title' field used throughout ProcessWire + if($name == 'language' && $inputfield->label == 'Language') { + $inputfield->label = $this->_('Language'); // Label for 'language' field in user profile + } else if($name == 'email' && $inputfield->label == 'E-Mail Address') { + $inputfield->label = $this->_('E-Mail Address'); // Label for 'email' field in user profile + } else if($name == 'title' && $inputfield->label == 'Title') { + $inputfield->label = $this->_('Title'); // Label for 'title' field used throughout ProcessWire + } // check if this is a language alternate field (i.e. title_es or title) if($this->LanguageSupportFields) { @@ -504,7 +521,7 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { if($inputfield->getSetting('useLanguages') || $inputfield->getSetting('hasLanguages')) { // multi-language field $this->hookInputfieldBeforeRender($event); // ensures default language values are populated - if(!$this->wire('languages')->editable($this->defaultLanguagePage)) $replace = true; + if(!$this->wire()->languages->editable($this->defaultLanguagePage)) $replace = true; } else { // not a native multi-language field, check if it's language alternate or not editable @@ -512,7 +529,7 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { $replace = true; } else if($inputfield->hasFieldtype && $this->LanguageSupportFields) { $language = $this->LanguageSupportFields->isAlternateField($inputfield->name); - if($language && !$this->wire('languages')->editable($language)) $replace = true; + if($language && !$this->wire()->languages->editable($language)) $replace = true; } } @@ -536,15 +553,15 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { /** @var Inputfield $inputfield */ $inputfield = $event->object; if(!$inputfield->getSetting('useLanguages')) return; + $post = $event->arguments[0]; - $languages = $this->wire('languages'); + $languages = $this->wire()->languages; // originals $name = $inputfield->attr('name'); $id = $inputfield->attr('id'); $value = $inputfield->attr('value'); $required = $inputfield->required; - // process and set value for each language foreach($languages as $language) { @@ -577,7 +594,6 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { $inputfield->setAttribute('value', $value); $inputfield->required = $required; $inputfield->setTrackChanges(true); - } /** @@ -588,24 +604,23 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { */ public function hookFieldGetInputfield(HookEvent $event) { - $language = $this->wire('user')->language; + $language = $this->wire()->user->language; if(!$language || !$language->id) return; - /** @var Field $field */ - $field = $event->object; - /** @var Page $page */ - $page = $event->arguments[0]; - /** @var Template $template */ - $template = $page ? $page->template : null; - $inputfield = $event->return; + $field = $event->object; /** @var Field $field */ + $page = $event->arguments[0]; /** @var Page $page */ + $template = $page ? $page->template : null; /** @var Template|null $template */ + $inputfield = $event->return; /** @var Inputfield $inputfield */ + if(!$inputfield) return; + $translatable = array('label', 'description', 'notes'); - if($inputfield->attr('placeholder') !== null && $this->wire('process') != 'ProcessField') { + if($inputfield->attr('placeholder') !== null && $this->wire()->process != 'ProcessField') { $translatable[] = 'placeholder'; } - $languages = $template ? $template->getLanguages() : $this->wire('languages'); + $languages = $template ? $template->getLanguages() : $this->wire()->languages; $useLanguages = $template && $template->noLang ? false : true; - if(!$languages) $languages = $this->wire('languages'); + if(!$languages) $languages = $this->wire()->languages; // populate language versions where available foreach($translatable as $key) { @@ -626,7 +641,7 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { // set values in this field specific to each language foreach($languages as $language) { $languageValue = ''; - if(is_object($value) && $value instanceof LanguagesPageFieldValue) { + if($value instanceof LanguagesPageFieldValue) { $languageValue = $value->getLanguageValue($language->id); } else { if($language->isDefault) $languageValue = $value; @@ -649,6 +664,7 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { */ public function hookPageAdded(HookEvent $event) { + /** @var Page $page */ $page = $event->arguments[0]; if($page->template->name != self::languageTemplateName) return; @@ -656,13 +672,14 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { $ids = $this->otherLanguagePageIDs; $ids[] = $page->id; $this->set('otherLanguagePageIDs', $ids); - wire('languages')->added($page); + $this->wire()->languages->added($page); // save this as a known language page with module settings // this is a shortcut used to identify language pages before the API is fully ready - $configData = $this->wire('modules')->getModuleConfigData('LanguageSupport'); + $modules = $this->wire()->modules; + $configData = $modules->getModuleConfigData('LanguageSupport'); $configData['otherLanguagePageIDs'][] = $page->id; - wire('modules')->saveModuleConfigData('LanguageSupport', $configData); + $modules->saveModuleConfigData('LanguageSupport', $configData); } @@ -674,20 +691,21 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { */ public function hookPageDeleteReady(HookEvent $event) { + /** @var Page $page */ $page = $event->arguments[0]; if($page->template->name != self::languageTemplateName) return; $language = $page; // remove any language-specific values from any fields - foreach($this->wire('fields') as $field) { - + foreach($this->wire()->fields as $field) { + /** @var Field $field */ $changed = false; foreach(array('label', 'description', 'notes') as $name) { $name = $name . $language->id; if(!isset($field->$name)) continue; $field->remove($name); - $this->message("Removed {$language->name} $name from field {$field->name}"); + $this->message("Removed $language->name $name from field $field->name"); $changed = true; } @@ -695,24 +713,26 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { } // remove template labels - foreach($this->wire('templates') as $template) { + foreach($this->wire()->templates as $template) { + /** @var Template $template */ $name = 'label' . $page->id; if(isset($template->$name)) { $template->remove($name); $template->save(); - $this->message("Removed {$language->name} label from template {$template->name}"); + $this->message("Removed $language->name label from template $template->name"); } } // trigger hook in $languages - wire('languages')->deleted($page); + $this->wire()->languages->deleted($page); // update the other language module IDs to remove the uninstalled language - $configData = $this->wire('modules')->getModuleConfigData('LanguageSupport'); + $modules = $this->wire()->modules; + $configData = $modules->getModuleConfigData('LanguageSupport'); $key = array_search($page->id, $configData['otherLanguagePageIDs']); if($key !== false) { unset($configData['otherLanguagePageIDs'][$key]); - $this->wire('modules')->saveModuleConfigData('LanguageSupport', $configData); + $modules->saveModuleConfigData('LanguageSupport', $configData); } } @@ -730,12 +750,13 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { * */ public function hookPageSetLanguageValue(HookEvent $event) { - - $page = $event->object; - $language = $event->arguments(0); - $field = $event->arguments(1); + + $page = $event->object; /** @var Page $page */ + $language = $event->arguments(0); /** @var Language $language */ + $field = $event->arguments(1); /** @var string|Field $field */ $value = $event->arguments(2); $languages = $this->wire()->languages; + $event->return = $page; if(!is_object($language)) { @@ -743,7 +764,9 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { $language = $languages ? $languages->get($language) : null; } - if(!$language instanceof Language) throw new WireException('Unknown language set to Page::setLanguageValue'); + if(!$language instanceof Language) { + throw new WireException('Unknown language set to Page::setLanguageValue'); + } if($field === 'name' || $field === 'status') { // set page name or status @@ -761,9 +784,9 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { if(is_object($field)) $field = $field->name; $previousValue = $page->get($field); - if(is_object($previousValue) && $previousValue instanceof LanguagesValueInterface) { + if($previousValue instanceof LanguagesValueInterface) { // utilize existing set methods available in LanguagesValueInterface (which might be slightly quicker than the else condition method - if(is_object($value) && $value instanceof LanguagesValueInterface) { + if($value instanceof LanguagesValueInterface) { // if given a LanguagesPageFieldValue, then just set it to the page $page->set($field, $value); } else { @@ -774,7 +797,7 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { } else { // temporarily set user's language to field language, set the field value, then set user's language back // we don't know what exactly $field might be, whether custom field or some other field, but we'll set it anyway - $user = $this->wire('user'); + $user = $this->wire()->user; $userLanguage = $user->language->id != $language->id ? $user->language : null; if($userLanguage) $user->language = $language; $page->set($field, $value); @@ -798,22 +821,20 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { */ public function hookPageGetLanguageValue(HookEvent $event) { - /** @var Page $page */ - $page = $event->object; - /** @var Language $language */ - $language = $event->arguments(0); - /** @var Field $field */ - $field = $event->arguments(1); - $value = null; + $page = $event->object; /** @var Page $page */ + $language = $event->arguments(0); /** @var Language $language */ + $field = $event->arguments(1); /** @var string|Field $field */ if(!is_object($language)) { if(ctype_digit("$language")) $language = (int) $language; - $language = $this->wire('languages')->get($language); + $language = $this->wire()->languages->get($language); } - if(!$language instanceof Language) throw new WireException('Unknown language sent to Page::getLanguageValue'); + if(!$language instanceof Language) { + throw new WireException('Unknown language sent to Page::getLanguageValue'); + } - if($field == 'name') { + if($field === 'name') { // get a page name if($language->isDefault()) { $value = $page->name; @@ -826,12 +847,12 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { if(is_object($field)) $field = $field->name; $value = $page->get($field); - if(is_object($value) && $value instanceof LanguagesValueInterface) { + if($value instanceof LanguagesValueInterface) { $value = $value->getLanguageValue($language->id); } else { // temporarily set user's language to field language, get the field value, then set user's language back - $user = $this->wire('user'); + $user = $this->wire()->user; $userLanguage = $user->language->id != $language->id ? $user->language : null; if($userLanguage) $user->language = $language; $value = $page->get($field); @@ -862,19 +883,24 @@ class LanguageSupport extends WireData implements Module, ConfigurableModule { * */ public function refreshLanguageIDs() { + $languages = $this->wire()->languages; + $modules = $this->wire()->modules; + $this->message('Refreshing other language page IDs', Notice::debug); - if(!$this->wire('languages')) return; + if(!$languages) return; + $ids = array(); - foreach($this->wire('languages') as $language) { + + foreach($languages as $language) { if($language->isDefault()) continue; $ids[] = $language->id; } if($this->otherLanguagePageIDs != $ids) { $this->set('otherLanguagePageIDs', $ids); - $configData = $this->wire('modules')->getModuleConfigData('LanguageSupport'); + $configData = $modules->getModuleConfigData('LanguageSupport'); if($configData['otherLanguagePageIDs'] != $ids) { $configData['otherLanguagePageIDs'] = $ids; - $this->wire('modules')->saveModuleConfigData('LanguageSupport', $configData); + $modules->saveModuleConfigData('LanguageSupport', $configData); } } } diff --git a/wire/modules/LanguageSupport/LanguageSupportFields.module b/wire/modules/LanguageSupport/LanguageSupportFields.module index 03b2643a..a178c770 100644 --- a/wire/modules/LanguageSupport/LanguageSupportFields.module +++ b/wire/modules/LanguageSupport/LanguageSupportFields.module @@ -57,6 +57,7 @@ class LanguageSupportFields extends WireData implements Module { * */ public function __construct() { + parent::__construct(); // load other required classes $dirname = dirname(__FILE__); require_once($dirname . '/LanguagesValueInterface.php'); @@ -138,7 +139,7 @@ class LanguageSupportFields extends WireData implements Module { $field = $event->arguments[1]; if($field->name === 'language') return; - $language = $this->wire()->user->get('language'); + $language = $this->wire()->user->language; if(!$language || !$language->id || $language->isDefault()) return; // exit quickly if we can determine now we don't need to continue @@ -327,7 +328,7 @@ class LanguageSupportFields extends WireData implements Module { $fields = $selector->field; $fields = is_array($fields) ? $fields : array($fields); - foreach($fields as $key => $field) { + foreach($fields as $field) { $subfield = ''; if(strpos($field, '.')) list($field, $subfield) = explode('.', $field); @@ -554,7 +555,7 @@ class LanguageSupportFields extends WireData implements Module { * */ public function ___install() { - $this->modules->get('FieldtypeTextLanguage'); + $this->wire()->modules->get('FieldtypeTextLanguage'); } /** diff --git a/wire/modules/LanguageSupport/LanguageTranslator.php b/wire/modules/LanguageSupport/LanguageTranslator.php index c63cf5cc..3ae57846 100644 --- a/wire/modules/LanguageSupport/LanguageTranslator.php +++ b/wire/modules/LanguageSupport/LanguageTranslator.php @@ -3,7 +3,7 @@ /** * ProcessWire Language Translator * - * ProcessWire 3.x, Copyright 2016 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @@ -96,9 +96,10 @@ class LanguageTranslator extends Wire { * */ public function __construct(Language $currentLanguage) { + parent::__construct(); $currentLanguage->wire($this); $this->setCurrentLanguage($currentLanguage); - $this->rootPath = $this->wire('config')->paths->root; + $this->rootPath = $this->wire()->config->paths->root; $file = __FILE__; $pos = strpos($file, '/wire/modules/LanguageSupport/'); $this->rootPath2 = $pos ? substr($file, 0, $pos+1) : ''; diff --git a/wire/modules/LanguageSupport/ProcessLanguage.module b/wire/modules/LanguageSupport/ProcessLanguage.module index aff9d1e6..91713ba0 100644 --- a/wire/modules/LanguageSupport/ProcessLanguage.module +++ b/wire/modules/LanguageSupport/ProcessLanguage.module @@ -29,8 +29,8 @@ class ProcessLanguage extends ProcessPageType { 'permission' => 'lang-edit', 'permissions' => array( 'lang-edit' => 'Administer languages and static translation files' - ) - ); + ) + ); } /** @@ -90,7 +90,7 @@ class ProcessLanguage extends ProcessPageType { $this->addHookAfter('InputfieldFile::renderUpload', $this, 'renderInputfieldFileUpload'); $this->addHookBefore('InputfieldFile::processInput', $this, 'processInputfieldFileInput'); - if(!$this->wire('config')->ajax) { + if(!$this->wire()->config->ajax) { $this->addHookBefore('InputfieldForm::render', $this, 'renderInputfieldForm'); } parent::init(); @@ -98,8 +98,9 @@ class ProcessLanguage extends ProcessPageType { protected function translationUrl() { if(!$this->translationUrl) { - $support = $this->wire('modules')->get('LanguageSupport'); - $this->translationUrl = $this->wire('pages')->get($support->languageTranslatorPageID)->url; + /** @var LanguageSupport $support */ + $support = $this->wire()->modules->get('LanguageSupport'); + $this->translationUrl = $this->wire()->pages->get($support->languageTranslatorPageID)->url; } return $this->translationUrl; } @@ -120,15 +121,14 @@ class ProcessLanguage extends ProcessPageType { */ public function renderInputfieldFile(HookEvent $event) { - /** @var InputfieldFile $inputfield */ - $inputfield = $event->object; - $language = $this->wire('process')->getPage(); + $inputfield = $event->object; /** @var InputfieldFile $inputfield */ + $language = $this->wire()->process->getPage(); /** @var Language $language */ /** @var Pagefiles $pagefiles */ $pagefiles = $inputfield->attr('value'); foreach($pagefiles as $pagefile) { - /** Pagefile $pagefile */ + /** @var Pagefile $pagefile */ if($pagefile->ext() != 'csv') continue; $pagefiles->remove($pagefile); $this->processCSV($pagefile->filename(), $language); @@ -146,9 +146,13 @@ class ProcessLanguage extends ProcessPageType { /** @var InputfieldForm $form */ $form = $event->object; $language = $this->getPage(); + if(!$language->id) return; + $file = $language->filesManager()->path . '.phrase-index.txt'; - $inputfield = $this->wire('modules')->get('InputfieldMarkup'); + + /** @var InputfieldMarkup $inputfield */ + $inputfield = $this->wire()->modules->get('InputfieldMarkup'); $inputfield->label = $this->_('Live Search'); $inputfield->icon = 'search'; $placeholder = $this->_('Text to search for'); @@ -163,12 +167,13 @@ class ProcessLanguage extends ProcessPageType { $phrases = file_get_contents($file); $phrases = str_replace(array('"', "\n", "<", ">"), ' ', $phrases); + $script = 'script'; $inputfield->value = - "" . + "" . "

" . $this->_('Search all translatable files for specific text/phrase.') . ' ' . $this->_('Click found matches to edit translation or add file (if not already present).') . @@ -195,10 +200,8 @@ class ProcessLanguage extends ProcessPageType { public function renderInputfieldFileItem(HookEvent $event) { $translationUrl = $this->translationUrl(); - /** @var Pagefile $pagefile */ - $pagefile = $event->arguments[0]; - /** @var Language $page */ - $page = $pagefile->get('page'); + $pagefile = $event->arguments[0]; /** @var Pagefile $pagefile */ + $page = $pagefile->get('page'); /** @var Language $page */ if($pagefile->ext() == 'csv') { $event->return .= @@ -214,9 +217,11 @@ class ProcessLanguage extends ProcessPageType { $data = $page->translator->getTextdomain($textdomain); $file = $data['file']; - $pathname = $this->wire('config')->paths->root . $file; + $pathname = $this->wire()->config->paths->root . $file; $translations =& $data['translations']; $total = count($translations); + + /** @var LanguageParser $parser */ $parser = $this->wire(new LanguageParser($page->translator, $pathname)); $untranslated = $parser->getUntranslated(); $alternates = $parser->getAlternates(); @@ -276,18 +281,16 @@ class ProcessLanguage extends ProcessPageType { * */ public function renderInputfieldFileUpload(HookEvent $event) { - + + $modules = $this->wire()->modules; $translationUrl = $this->translationUrl(); - /** @var Pagefiles $pagefiles */ - $pagefiles = $event->arguments(0); - /** @var Page $page */ - $page = $pagefiles->get('page'); - /** @var InputfieldFile $inputfield */ - $inputfield = $event->object; + $pagefiles = $event->arguments(0); /** @var Pagefiles $pagefiles */ + $page = $pagefiles->get('page'); /** @var Page $page */ + $inputfield = $event->object; /** @var InputfieldFile $inputfield */ $out = ''; /** @var InputfieldButton $btn1 */ - $btn1 = $this->wire('modules')->get('InputfieldButton'); + $btn1 = $modules->get('InputfieldButton'); $btn1->href = "{$translationUrl}add/?language_id={$page->id}"; $btn1->value = $this->_('Find Files to Translate'); $btn1->icon = 'plane'; @@ -296,7 +299,7 @@ class ProcessLanguage extends ProcessPageType { if(count($inputfield->attr('value'))) { /** @var InputfieldButton $btn2 */ - $btn2 = $this->wire('modules')->get('InputfieldButton'); + $btn2 = $modules->get('InputfieldButton'); $btn2->href = "../download/?language_id={$page->id}&field=" . $inputfield->attr('name'); $btn2->value = $this->_('Download ZIP'); $btn2->icon = 'file-zip-o'; @@ -336,10 +339,11 @@ class ProcessLanguage extends ProcessPageType { public function ___execute() { // check if 2.5 update needed to add new language_files_site field - if(!$this->wire('fields')->get('language_files_site')) { + if(!$this->wire()->fields->get('language_files_site')) { require_once(dirname(__FILE__) . '/LanguageSupportInstall.php'); + /** @var LanguageSupportInstall $installer */ $installer = $this->wire(new LanguageSupportInstall()); - $installer->addFilesFields($this->wire('fieldgroups')->get(LanguageSupport::languageTemplateName)); + $installer->addFilesFields($this->wire()->fieldgroups->get(LanguageSupport::languageTemplateName)); } return parent::___execute(); } @@ -376,7 +380,7 @@ class ProcessLanguage extends ProcessPageType { } } - if(!count($files) && $fieldName) { + if(!count($files)) { foreach($language->$fieldName as $file) { $files[] = $file->filename; } diff --git a/wire/modules/LanguageSupport/ProcessLanguageTranslator.module b/wire/modules/LanguageSupport/ProcessLanguageTranslator.module index a898e624..82ddc4a6 100644 --- a/wire/modules/LanguageSupport/ProcessLanguageTranslator.module +++ b/wire/modules/LanguageSupport/ProcessLanguageTranslator.module @@ -88,11 +88,11 @@ class ProcessLanguageTranslator extends Process { public function init() { // if language specified as a GET var in the URL, then pick it up and use it (storing in session) - $id = $this->input->get('language_id'); + $id = $this->wire()->input->get('language_id'); if($id) { $this->setLanguage((int) $id); - } else if($this->session->get('translateLanguageID')) { - $this->setLanguage($this->session->get('translateLanguageID')); + } else if($this->wire()->session->get('translateLanguageID')) { + $this->setLanguage($this->wire()->session->get('translateLanguageID')); } // else throw new WireException("No language specified"); parent::init(); @@ -111,12 +111,19 @@ class ProcessLanguageTranslator extends Process { */ public function setLanguage($language) { - $languages = $this->wire('languages'); + $languages = $this->wire()->languages; if(!$languages) return; if(is_int($language)) $language = $languages->get($language); - if(!$language instanceof Language || !$language->id) throw new WireException($this->_("Unknown/invalid language")); - if(!$language->editable()) throw new WirePermissionException($this->_('You do not have permission to edit this language')); + + if(!$language instanceof Language || !$language->id) { + throw new WireException($this->_("Unknown/invalid language")); + } + + if(!$language->editable()) { + throw new WirePermissionException($this->_('You do not have permission to edit this language')); + } + $this->language = $language; $this->session->set('translateLanguageID', $language->id); $this->translator = new LanguageTranslator($this->language); @@ -135,10 +142,13 @@ class ProcessLanguageTranslator extends Process { * */ public function ___executeList() { + + $modules = $this->wire()->modules; + $config = $this->wire()->config; /** @var MarkupAdminDataTable $table */ - $table = $this->modules->get("MarkupAdminDataTable"); - $url = $this->pages->get("template=admin, name=language-translations")->url; + $table = $modules->get("MarkupAdminDataTable"); + $url = $this->wire()->pages->get("template=admin, name=language-translations")->url; $out = ''; foreach(array('language_files', 'language_files_site') as $fieldName) { @@ -155,7 +165,7 @@ class ProcessLanguageTranslator extends Process { $table->row(array( $data['file'] => $url . "edit/?textdomain=$textdomain", count($data['translations']), - date($this->config->dateFormat, filemtime($file->filename)) + date($config->dateFormat, filemtime($file->filename)) )); $this->translator->unloadTextdomain($textdomain); } @@ -167,7 +177,7 @@ class ProcessLanguageTranslator extends Process { } /** @var InputfieldButton $btn */ - $btn = $this->modules->get('InputfieldButton'); + $btn = $modules->get('InputfieldButton'); $btn->href = $url . 'add/'; $btn->icon = 'plane'; $btn->showInHeader(); @@ -183,26 +193,31 @@ class ProcessLanguageTranslator extends Process { * */ public function ___executeAdd() { + + $modules = $this->wire()->modules; + $input = $this->wire()->input; + $config = $this->wire()->config; + $session = $this->wire()->session; $this->addBreadcrumbs(); $this->headline($this->_('Select File(s)')); // Headline when adding new translation files /** @var InputfieldForm $form */ - $form = $this->modules->get("InputfieldForm"); + $form = $modules->get("InputfieldForm"); $form->attr('method', 'post'); $form->attr('action', "./?language_id={$this->language->id}"); //$form->description = sprintf("Select file(s) for translation to %s", $this->language->get('title|name')); $languageTitle = $this->language->get('title|name'); $form->description = sprintf($this->_('Select a file (or multiple files) and click Submit to create new %s translation files.'), $languageTitle); - $useCache = $this->input->post('submit_refresh') || $this->input->get('refresh') ? false : true; + $useCache = $input->post('submit_refresh') || $input->get('refresh') ? false : true; $files = array( - 'site' => $this->findTranslatableFiles($this->wire('config')->paths->site, $useCache), - 'wire' => $this->findTranslatableFiles($this->wire('config')->paths->wire, $useCache) + 'site' => $this->findTranslatableFiles($config->paths->site, $useCache), + 'wire' => $this->findTranslatableFiles($config->paths->wire, $useCache) ); - if($this->input->get('refresh')) { - $this->wire('session')->redirect("../../languages/edit/?id={$this->language->id}"); + if($input->get('refresh')) { + $session->redirect("../../languages/edit/?id={$this->language->id}"); return ''; } @@ -217,7 +232,7 @@ class ProcessLanguageTranslator extends Process { foreach(array_keys($files) as $key) { /** @var InputfieldSelectMultiple $field */ - $field = $this->modules->get('InputfieldSelectMultiple'); + $field = $modules->get('InputfieldSelectMultiple'); $field->attr('name', 'file_' . $key); $field->label = sprintf($this->_('Translatable files in %s'), "/$key/"); $field->addClass('TranslationFileSelect'); @@ -274,7 +289,7 @@ class ProcessLanguageTranslator extends Process { } /** @var InputfieldText $field */ - $field = $this->modules->get('InputfieldText'); + $field = $modules->get('InputfieldText'); $field->attr('name', 'filename'); $field->label = $this->_('Enter file to translate'); $field->icon = 'code'; @@ -284,14 +299,14 @@ class ProcessLanguageTranslator extends Process { $form->add($field); /** @var InputfieldSubmit $submit */ - $submit = $this->modules->get("InputfieldSubmit"); + $submit = $modules->get("InputfieldSubmit"); $submit->attr('id+name', 'submit_add'); $submit->icon = 'plane'; $submit->showInHeader(); $form->add($submit); /** @var InputfieldSubmit $submit */ - $submit = $this->modules->get("InputfieldSubmit"); + $submit = $modules->get("InputfieldSubmit"); $submit->attr('name', 'submit_refresh'); $submit->attr('value', $this->_('Refresh File List')); $submit->setSecondary(); @@ -299,13 +314,13 @@ class ProcessLanguageTranslator extends Process { $form->add($submit); if($form->isSubmitted('submit_add')) { - if($this->input->post('filename')) { + if($input->post('filename')) { $this->processAdd($field); } else { $newTextdomains = array(); foreach(array('site' => 'file_site', 'wire' => 'file_wire') as $key => $name) { - $postFiles = $this->input->post->$name; + $postFiles = $input->post->$name; if(!wireCount($postFiles)) continue; foreach($postFiles as $file) { if(!isset($files[$key][$file])) continue; @@ -318,11 +333,11 @@ class ProcessLanguageTranslator extends Process { } } if(count($newTextdomains) == 1) { - $this->session->redirect("../edit/?language_id={$this->language->id}&textdomain=" . reset($newTextdomains)); + $session->redirect("../edit/?language_id={$this->language->id}&textdomain=" . reset($newTextdomains)); return ''; } else if(count($newTextdomains) > 1) { // render form again - $this->session->redirect("../../languages/edit/?id={$this->language->id}"); + $session->redirect("../../languages/edit/?id={$this->language->id}"); return ''; } } @@ -340,27 +355,29 @@ class ProcessLanguageTranslator extends Process { * */ protected function ___processAdd($field = null, $sourceFilename = '') { + + $session = $this->wire()->session; if($sourceFilename) { $filename = $sourceFilename; } else { - $filename = $this->input->post('filename'); + $filename = $this->wire()->input->post('filename'); } $filename = str_replace(array('\\', '..'), array('/', ''), $filename); if($field) $field->attr('value', $filename); - $pathname = $this->config->paths->root . ltrim($filename, '/'); + $pathname = $this->wire()->config->paths->root . ltrim($filename, '/'); if(is_file($pathname)) { - if(!$sourceFilename) $this->session->get('CSRF')->validate(); + if(!$sourceFilename) $session->get('CSRF')->validate(); $this->message(sprintf($this->_('Found %s'), $filename)); // Found [filename] if($this->parseTranslatableFile($pathname)) { $textdomain = $this->translator->addFileToTranslate($filename); if($textdomain) { - $this->session->redirect("../edit/?language_id={$this->language->id}&textdomain=$textdomain"); + $session->redirect("../edit/?language_id={$this->language->id}&textdomain=$textdomain"); } $this->error($this->_('That file is already in the system')); @@ -384,15 +401,16 @@ class ProcessLanguageTranslator extends Process { $qty = substr_count($untranslated, "\n")+1; $qty2 = substr_count($translated, "\n")+1; if($qty2 > $qty) $qty = $qty2; - $field = $this->modules->get("InputfieldTextarea"); + $field = $this->wire()->modules->get("InputfieldTextarea"); $field->attr('rows', $qty > 2 ? $qty : 2); } else if(strlen($untranslated) < 128) { - $field = $this->modules->get("InputfieldText"); + $field = $this->wire()->modules->get("InputfieldText"); } else { - $field = $this->modules->get("InputfieldTextarea"); + $field = $this->wire()->modules->get("InputfieldTextarea"); $field->attr('rows', 3); } - + + /** @var InputfieldText $field */ $field->attr('id+name', $hash); $field->set('textFormat', Inputfield::textFormatNone); $field->attr('value', $translated); @@ -430,9 +448,9 @@ class ProcessLanguageTranslator extends Process { } if((!strlen($translated) || $translated === '+') && !$field instanceof InputfieldTextarea) { - $languages = $this->wire('languages'); + $languages = $this->wire()->languages; $languages->setLanguage($this->language); - $this->wire('user')->language = $this->language; + $this->wire()->user->language = $this->language; $test = $this->translator->commonTranslation($untranslated); $field->textFormat = Inputfield::textFormatBasic; if(strlen($test) && $test !== $untranslated) { @@ -458,9 +476,11 @@ class ProcessLanguageTranslator extends Process { * */ protected function executeEditAbandoned(&$translations, $form) { + + $modules = $this->wire()->modules; /** @var InputfieldFieldset $fieldset */ - $fieldset = $this->modules->get("InputfieldFieldset"); + $fieldset = $modules->get("InputfieldFieldset"); $fieldset->attr('id+name', 'abandoned_fieldset'); $fieldset->description = $this->_('The following unused translations were found. This means that the original untranslated text was either changed or deleted. It is recommended that you delete abandoned translations unless you need to keep them to copy/paste to a new translation.'); $fieldset->collapsed = Inputfield::collapsedYes; @@ -475,7 +495,7 @@ class ProcessLanguageTranslator extends Process { $n++; /** @var InputfieldCheckbox $field */ - $field = $this->modules->get("InputfieldCheckbox"); + $field = $modules->get("InputfieldCheckbox"); $field->attr('name', "abandoned$n"); $field->attr('value', $hash); $field->description = !strlen($translation['text']) ? $this->_('[empty]') : $translation['text']; @@ -520,7 +540,7 @@ class ProcessLanguageTranslator extends Process { if(!$fileUrl) { $filename = $input->get('filename'); $test = $filename ? $this->translator->filenameToTextdomain($filename) : ''; - if($textdomain && $test === $textdomain) { + if($test === $textdomain) { $this->processAdd(null, $filename); } else { throw new WireException($this->_('Unable to load textdomain')); @@ -616,11 +636,15 @@ class ProcessLanguageTranslator extends Process { * */ protected function ___processEdit($form, $textdomain, $translations) { - - $form->processInput($this->input->post); + + $input = $this->wire()->input; + $session = $this->wire()->session; + $numChanges = 0; $numRemoved = 0; + $form->processInput($input->post); + foreach($this->untranslated as $hash => $text) { $translation = isset($translations[$hash]) ? $translations[$hash] : array('text' => ''); $field = $form->getChildByName($hash); @@ -630,16 +654,16 @@ class ProcessLanguageTranslator extends Process { } } - foreach($this->input->post as $key => $hash) { + foreach($input->post as $key => $hash) { if(strpos($key, 'abandoned') !== 0) continue; - if(!$field = $form->getChildByName($key)) continue; + if(!$form->getChildByName($key)) continue; $this->translator->removeTranslation($textdomain, $hash); $numRemoved++; } // show only untranslated toggle, remember setting - $untranslated = (int) $this->input->post('untranslated'); - $this->session->setFor($this, 'untranslated', $untranslated); + $untranslated = (int) $input->post('untranslated'); + $session->setFor($this, 'untranslated', $untranslated); if($numChanges) $this->message(sprintf($this->_n('%d translation changed', '%d translations changed', $numChanges), $numChanges)); if($numRemoved) $this->message(sprintf($this->_n('%d abandoned translation removed', '%d abandoned translations removed', $numRemoved), $numRemoved)); @@ -648,10 +672,10 @@ class ProcessLanguageTranslator extends Process { $this->message(sprintf($this->_('Saved %s'), $textdomain)); // button actions - $action = $this->wire('input')->post('_action_value'); + $action = $input->post('_action_value'); if($action == 'exit') { // save and exit - $this->session->redirect("../../languages/edit/?id={$this->language->id}"); + $session->redirect("../../languages/edit/?id={$this->language->id}"); } else if($action == 'next') { // save and edit next file $nextTextdomain = false; @@ -670,10 +694,10 @@ class ProcessLanguageTranslator extends Process { $nextTextdomain = $textdomain; $this->warning($this->_('There is no next file to edit.')); } - $this->session->redirect("./?textdomain=$nextTextdomain&language_id={$this->language->id}"); + $session->redirect("./?textdomain=$nextTextdomain&language_id={$this->language->id}"); } else { // save and continue editing (default) - $this->session->redirect("./?textdomain=$textdomain&language_id={$this->language->id}"); + $session->redirect("./?textdomain=$textdomain&language_id={$this->language->id}"); } } @@ -700,11 +724,12 @@ class ProcessLanguageTranslator extends Process { */ protected function addBreadcrumbs() { /** @var LanguageSupport $languageSupport */ - $languageSupport = $this->modules->get('LanguageSupport'); + $languageSupport = $this->wire()->modules->get('LanguageSupport'); $languagesPage = $this->pages->get($languageSupport->languagesPageID); $url = $languagesPage->url; - $this->wire('breadcrumbs')->add(new Breadcrumb($url, $languagesPage->title)); - $this->wire('breadcrumbs')->add(new Breadcrumb($url . "edit/?id={$this->language->id}", $this->language->get('title|name'))); + $breadcrumbs = $this->wire()->breadcrumbs; + $breadcrumbs->add(new Breadcrumb($url, $languagesPage->title)); + $breadcrumbs->add(new Breadcrumb($url . "edit/?id={$this->language->id}", $this->language->get('title|name'))); } /** @@ -728,7 +753,7 @@ class ProcessLanguageTranslator extends Process { if(!$level) { $cacheKey = "files_" . md5($path); if($useCache) { - $files = $this->session->get($this, $cacheKey); + $files = $this->wire()->session->get($this, $cacheKey); if($files !== null) return $files; } } else { @@ -737,13 +762,13 @@ class ProcessLanguageTranslator extends Process { if(is_null($this->fp)) { $f = $this->language->filesManager()->path() . '.phrase-index.txt'; - if(is_file($f)) $this->wire('files')->unlink($f); + if(is_file($f)) $this->wire()->files->unlink($f); $this->fp = fopen($f, "a"); } $files = array(); $dirs = array(); - $root = $this->wire('config')->paths->root; + $root = $this->wire()->config->paths->root; $assetsDir = '/site/assets/'; if(DIRECTORY_SEPARATOR != '/') $assetsDir = str_replace('/', DIRECTORY_SEPARATOR, $assetsDir); @@ -801,7 +826,7 @@ class ProcessLanguageTranslator extends Process { $pathname = str_replace($root, '/', $pathname); $files[$pathname] = $pathname; if(preg_match_all('/\b(?:_[_nx]\(|->_[nx]?\()[\'"](.+?)[\'"]\)/', $text, $matches)) { - foreach($matches[1] as $key => $phrase) { + foreach($matches[1] as $phrase) { $phrase = str_replace(array('|', '^', "\n", "\r", "\t", "<", ">"), ' ', strip_tags($phrase)); fwrite($this->fp, "|$phrase"); } @@ -821,7 +846,7 @@ class ProcessLanguageTranslator extends Process { $level--; if($cacheKey) { - $this->session->set($this, $cacheKey, $files); + $this->wire()->session->set($this, $cacheKey, $files); } if($this->fp && !$level) { diff --git a/wire/modules/Process/ProcessForgotPassword/ProcessForgotPassword.module b/wire/modules/Process/ProcessForgotPassword/ProcessForgotPassword.module index b9578eea..2ea6a508 100644 --- a/wire/modules/Process/ProcessForgotPassword/ProcessForgotPassword.module +++ b/wire/modules/Process/ProcessForgotPassword/ProcessForgotPassword.module @@ -9,7 +9,7 @@ * For more details about how Process modules work, please see: * /wire/core/Process.php * - * ProcessWire 3.x, Copyright 2018 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @property bool|int $allowReset Allow passwords to be reset? @@ -46,7 +46,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { 'version' => 104, 'permanent' => false, 'permission' => 'page-view', - ); + ); } /** @@ -98,9 +98,16 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $this->set('allowRoles', array()); $this->set('blockRoles', array()); $this->set('wireMailer', ''); - - $emailField = $this->wire('fields')->get('email'); - if($emailField) $this->set('confirmFields', array("email:$emailField->id")); + } + + /** + * Wired to API + * + */ + public function wired() { + $emailField = $this->wire()->fields->get('email'); + if($emailField) $this->set('confirmFields', array("email:$emailField->id")); + parent::wired(); } /** @@ -109,8 +116,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ public function ___execute() { - /** @var WireInput $input */ - $input = $this->wire('input'); + $input = $this->wire()->input; $out = ''; $errors = array( @@ -121,7 +127,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $this->headline($this->_('Reset Password')); // Reset password page headline // password reset not applicable to logged-in users - if($this->user->isLoggedin()) return ''; + if($this->wire()->user->isLoggedin()) return ''; $this->setupResetTable(); @@ -162,7 +168,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { if(empty($out)) $out = $this->renderContinue(); $out = $errors . $out; } else if(empty($out)) { - $this->wire('session')->redirect('./'); + $this->wire()->session->location('./'); } if($out) $out = "

$out
"; @@ -177,19 +183,21 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * */ protected function step1_renderForm() { + + $modules = $this->wire()->modules; /** @var InputfieldForm $form */ - $form = $this->modules->get("InputfieldForm"); + $form = $modules->get("InputfieldForm"); $form->attr('action', './?forgot=1'); $form->attr('method', 'post'); /** @var InputfieldText $field */ if($this->askEmail) { - $field = $this->modules->get("InputfieldEmail"); + $field = $modules->get("InputfieldEmail"); $field->label = $this->_("Enter your email address"); $field->icon = 'envelope-o'; } else { - $field = $this->modules->get("InputfieldText"); + $field = $modules->get("InputfieldText"); $field->label = $this->_("Enter your user name"); $field->icon = 'user-circle-o'; } @@ -200,7 +208,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $form->add($field); /** @var InputfieldSubmit $submit */ - $submit = $this->modules->get("InputfieldSubmit"); + $submit = $modules->get("InputfieldSubmit"); $submit->attr('id+name', 'submit_forgot'); $form->add($submit); @@ -219,14 +227,10 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ protected function step2_processForm() { - /** @var Sanitizer $sanitizer */ - $sanitizer = $this->wire('sanitizer'); - /** @var WireInput $input */ - $input = $this->wire('input'); - /** @var Users $users */ - $users = $this->wire('users'); - /** @var User $user */ - $user = null; + $sanitizer = $this->wire()->sanitizer; + $input = $this->wire()->input; + $users = $this->wire()->users; + $user = null; /** @var User|null $user */ $name = ''; // track quantity of submitted requests in session qty variable @@ -324,13 +328,13 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * * @param User $user * @param string $token - * @return bool|int + * @return int * */ protected function step2_sendEmail(User $user, $token) { $verify = $this->sessionGet('verify'); - $url = $this->page->httpUrl() . + $url = $this->wire()->page->httpUrl() . "?forgot=1" . "&u={$user->id}" . "&t=" . urlencode($token); @@ -339,8 +343,8 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $bodyHTML = $this->renderEmailBody($url, $verify, true); $email = null; - if($this->wireMailer) $email = $this->wire('mail')->new(array('module' => $this->wireMailer)); - if(!$email) $email = $this->wire('mail')->new(); + if($this->wireMailer) $email = $this->wire()->mail->new(array('module' => $this->wireMailer)); + if(!$email) $email = $this->wire()->mail->new(); $email->to($user->email)->from($this->getEmailFrom()); $email->subject($this->emailSubject)->body($body)->bodyHTML($bodyHTML); @@ -353,13 +357,13 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * * @param User $user * @param $error - * @return bool|int + * @return int * */ protected function step2_sendErrorEmail(User $user, $error) { $body = $this->renderErrorEmailBody($error); if(self::debug) $this->message("

" . nl2br($body) . "

", Notice::allowMarkup); - $email = $this->wire('mail')->new(); + $email = $this->wire()->mail->new(); $email->to($user->email)->from($this->getEmailFrom()); $email->subject($this->emailSubject)->body($body); return $email->send(); @@ -419,7 +423,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ protected function ___renderErrorEmailBody($error) { return - sprintf($this->_('You requested a password reset for your account at %s.'), $this->wire('config')->httpHost) . ' ' . + sprintf($this->_('You requested a password reset for your account at %s.'), $this->wire()->config->httpHost) . ' ' . $this->_('The system is unable to complete this request for the reason listed below:') . "\n\n$error\n\n" . $this->_('Please contact the administrator for assistance with logging in to your account and/or changing your password.') . @@ -438,10 +442,8 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ protected function step3_processEmailClick() { - /** @var WireInput $input */ - $input = $this->wire('input'); - /** @var WireDatabasePDO $database */ - $database = $this->wire('database'); + $input = $this->wire()->input; + $database = $this->wire()->database; $id = (int) $input->get('u'); $token = $input->get('t'); @@ -490,15 +492,19 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ protected function step3_buildForm($id, $token) { + $modules = $this->wire()->modules; + $templates = $this->wire()->templates; + $id = (int) $id; $token = urlencode($token); /** @var InputfieldForm $form */ - $form = $this->modules->get("InputfieldForm"); + $form = $modules->get("InputfieldForm"); $form->attr('method', 'post'); $form->attr('action', "./?forgot=1&u=$id&t=$token"); - - $f = $this->wire('modules')->get('InputfieldText'); + + /** @var InputfieldText $f */ + $f = $modules->get('InputfieldText'); $f->attr('name', 'verify'); $f->label = $this->_('Verification Code'); $f->description = $this->_('Please type or paste in the code you received in your email.'); @@ -506,10 +512,11 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $f->attr('required', 'required'); $form->add($f); + $template = $templates->get('user'); + $fieldgroup = $template->fieldgroup; $confirmFields = array(); + foreach($this->confirmFields as $key => $fieldName) { - /** @var Fieldgroup $fieldgroup */ - $fieldgroup = $this->wire('templates')->get('user')->fieldgroup; if(strpos($fieldName, ':') === false) { $field = $fieldgroup->getFieldContext($fieldName); } else { @@ -530,8 +537,8 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { } $this->confirmFields = $confirmFields; // normalized to only known field names - /** @var Field $field */ - $field = $this->wire('fields')->get('pass'); + $field = $this->wire()->fields->get('pass'); + /** @var InputfieldPassword $inputfield */ $inputfield = $field->getInputfield(new NullPage(), $field); $inputfield->required = true; @@ -541,7 +548,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $form->add($inputfield); /** @var InputfieldSubmit $submit */ - $submit = $this->modules->get("InputfieldSubmit"); + $submit = $modules->get("InputfieldSubmit"); $submit->attr('id+name', 'submit_reset'); $form->add($submit); @@ -557,6 +564,8 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * */ protected function step4_completeReset($id, $form) { + + $input = $this->wire()->input; $confirmInputfields = array(); foreach($this->confirmFields as $fieldName) { @@ -570,8 +579,6 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $confirmInputfields[$fieldName] = $inputfield; } - /** @var WireInput $input */ - $input = $this->wire('input'); $form->processInput($input->post); $attempts = (int) $this->sessionGet('attempts'); $this->sessionSet('attempts', ++$attempts); @@ -589,8 +596,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $numErrors++; } - /** @var User $user */ - $user = $this->wire('users')->get((int) $id); + $user = $this->wire()->users->get((int) $id); foreach($confirmInputfields as $fieldName => $f) { $fv = $f->attr('value'); @@ -608,7 +614,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $pass = $form->getChildByName('pass')->attr('value'); if($numErrors || count($form->getErrors()) || !$user->id || !strlen($pass)) { - $this->wire('session')->redirect($form->attr('action')); + $this->wire()->session->redirect($form->attr('action')); return ''; } @@ -639,13 +645,13 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ protected function insertNewResetRequest($user) { - /** @var WireDatabasePDO $database */ - $database = $this->wire('database'); + $database = $this->wire()->database; + $session = $this->wire()->session; // create the unique verification token that is stored on the server and sent in the email $pass = new Password(); $token = $pass->randomBase64String(32); - $ip = $this->wire('session')->getIP(); + $ip = $session->getIP(); if(!strlen($token)) return false; @@ -671,7 +677,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { } catch(\Exception $e) { // catch any errors, just to prevent anything from ever being reported to screen - $this->wire('session')->removeNotices(); + $session->removeNotices(); $this->errors('all clear'); $this->error($this->_('Unable to complete this step')); $this->deleteReset(); @@ -691,12 +697,10 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ protected function deleteReset($id = 0, $token = null) { - /** @var WireDatabasePDO $database */ - $database = $this->wire('database'); + $database = $this->wire()->database; if(!$id) $id = (int) $this->sessionGet('id'); - /** @var Session $session */ $this->sessionRemove('step'); $this->sessionRemove('name'); $this->sessionRemove('id'); @@ -723,7 +727,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ protected function deleteResetAndRedirect($id = 0, $token = null) { $this->deleteReset($id, $token); - $this->wire('session')->redirect('./'); + $this->wire()->session->redirect('./'); return ''; } @@ -735,8 +739,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ protected function setupResetTable() { - /** @var WireDatabasePDO $database */ - $database = $this->wire('database'); + $database = $this->wire()->database; try { $query = $database->prepare("SHOW COLUMNS FROM `" . self::table . "`"); @@ -761,7 +764,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * */ protected function sessionSet($key, $value) { - $this->wire('session')->setFor($this, $key, $value); + $this->wire()->session->setFor($this, $key, $value); } /** @@ -772,7 +775,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * */ protected function sessionGet($key) { - return $this->wire('session')->getFor($this, $key); + return $this->wire()->session->getFor($this, $key); } /** @@ -782,7 +785,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * */ protected function sessionRemove($key) { - $this->wire('session')->removeFor($this, $key); + $this->wire()->session->removeFor($this, $key); } /** @@ -806,31 +809,32 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { } else if($user->isUnpublished()) { $reason = $this->_('User is unpublished'); return false; - } else if(!$this->wire('session')->allowLogin($user->name, $user)) { + } else if(!$this->wire()->session->allowLogin($user->name, $user)) { $reason = $this->_('User is not allowed to login per site configuration'); return false; } $allow = true; + $roles = $this->wire()->roles; foreach(array('allowRoles', 'blockRoles') as $type) { - $roles = array(); + $testRoles = array(); foreach($this->get($type) as $roleName) { $roleID = 0; if(strpos($roleName, ':')) list($roleName, $roleID) = explode(':', $roleName, 2); - $role = $this->wire('roles')->get($roleName); - if(!$role || !$role->id) $role = $this->wire('roles')->get((int) $roleID); + $role = $roles->get($roleName); + if(!$role || !$role->id) $role = $roles->get((int) $roleID); if(!$role || !$role->id) continue; - $roles[] = $role; + $testRoles[] = $role; } - if(!count($roles)) continue; + if(!count($testRoles)) continue; $hasRole = false; - foreach($roles as $role) { + foreach($testRoles as $role) { if($user->hasRole($role)) { $hasRole = $role; break; @@ -888,8 +892,8 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { } // check the quantity of *successful* attempts recorded in the database for this IP - if($ip === null) $ip = $this->wire('session')->getIP(); - $query = $this->wire('database')->prepare('SELECT COUNT(*) FROM ' . self::table . ' WHERE ip=:ip'); + if($ip === null) $ip = $this->wire()->session->getIP(); + $query = $this->wire()->database->prepare('SELECT COUNT(*) FROM ' . self::table . ' WHERE ip=:ip'); $query->bindValue(':ip', $ip); $query->execute(); $qty = $query->fetchColumn(); @@ -905,7 +909,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { // check the quantity of *any) requests recorded in our hourly cache for this IP address $ip = ip2long($ip); - $qty = (int) $this->wire('cache')->get("forgotpass$ip", $this->expireSecs); + $qty = (int) $this->wire()->cache->get("forgotpass$ip", $this->expireSecs); if($qty >= $maxPerIP) { if(self::debug) { $this->error("Max per IP limit ($qty) reached (via cache)"); @@ -923,14 +927,15 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * */ protected function trackNewRequest() { + $cache = $this->wire()->cache; $pass = new Password(); $verify = $pass->randomBase64String(22); $this->sessionSet('verify', $verify); $qty = (int) $this->sessionGet('qty'); $this->sessionSet('qty', $qty + 1); - $ip = $this->wire('session')->getIP(true); // int - $qty = (int) $this->wire('cache')->get("forgotpass$ip", $this->expireSecs); - $this->wire('cache')->save("forgotpass$ip", $qty + 1, $this->expireSecs); + $ip = $this->wire()->session->getIP(true); // int + $qty = (int) $cache->get("forgotpass$ip", $this->expireSecs); + $cache->save("forgotpass$ip", $qty + 1, $this->expireSecs); } /** @@ -938,9 +943,9 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * */ public function clearRequests() { - $this->wire('database')->exec("DELETE FROM " . self::table); - $this->wire('cache')->delete("forgotpass*"); - $this->wire('session')->removeAllFor($this); + $this->wire()->database->exec("DELETE FROM " . self::table); + $this->wire()->cache->delete("forgotpass*"); + $this->wire()->session->removeAllFor($this); } /** @@ -950,13 +955,14 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * */ protected function getEmailFrom() { + $config = $this->wire()->config; $emailFrom = $this->emailFrom; if(empty($emailFrom)) { - $settings = $this->wire()->config->wireMail; + $settings = $config->wireMail; if(!empty($settings['from'])) $emailFrom = $settings['from']; } - if(empty($emailFrom)) $emailFrom = $this->wire('config')->adminEmail; - if(empty($emailFrom)) $emailFrom = 'noreply@' . $this->wire('config')->httpHost; + if(empty($emailFrom)) $emailFrom = $config->adminEmail; + if(empty($emailFrom)) $emailFrom = 'noreply@' . $config->httpHost; return $emailFrom; } @@ -969,7 +975,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { * */ public function ___log($str = '', array $options = array()) { - if(!$this->useLog) return $this->wire('log'); + if(!$this->useLog) return $this->wire()->log; if(empty($options['name'])) $options['name'] = 'forgot-password'; if($this->logUser) $options['user'] = $this->logUser; return parent::___log($str, $options); @@ -998,11 +1004,13 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { } protected function ___renderError($str) { - return "

" . $this->wire('sanitizer')->entities1($str) . "

"; + $str = $this->wire()->sanitizer->entities1($str); + return "

$str

"; } protected function ___renderMessage($str) { - return "

" . $this->wire('sanitizer')->entities1($str) . "

"; + $str = $this->wire()->sanitizer->entities1($str); + return "

$str

"; } /** @@ -1025,9 +1033,8 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ public function ___install() { - /** @var WireDatabasePDO $database */ - $database = $this->wire('database'); - $engine = $this->wire('config')->dbEngine; + $database = $this->wire()->database; + $engine = $this->wire()->config->dbEngine; $sql = "CREATE TABLE `" . self::table . "` ( " . "id INT unsigned NOT NULL PRIMARY KEY, " . @@ -1049,8 +1056,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { } public function ___uninstall() { - /** @var WireDatabasePDO $database */ - $database = $this->wire('database'); + $database = $this->wire()->database; $database->exec("DROP TABLE `" . self::table ."`"); } @@ -1071,18 +1077,20 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { */ public function getModuleConfigInputfields(InputfieldWrapper $inputfields) { + $modules = $this->wire()->modules; + $form = $inputfields; $optional = ' ' . $this->_('(optional)'); /** @var InputfieldEmail $f */ - $f = $this->wire('modules')->get('InputfieldEmail'); + $f = $modules->get('InputfieldEmail'); $f->attr('name', 'emailFrom'); $f->label = $this->_('Email address to send messages from'); $f->attr('value', $this->emailFrom); $form->add($f); /** @var InputfieldCheckbox $f */ - $f = $this->wire('modules')->get('InputfieldCheckbox'); + $f = $modules->get('InputfieldCheckbox'); $f->attr('name', 'askEmail'); $f->label = $this->_('Use email rather than user name'); $f->description = @@ -1095,7 +1103,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $form->add($f); /** @var InputfieldInteger $f */ - $f = $this->wire('modules')->get('InputfieldInteger'); + $f = $modules->get('InputfieldInteger'); $f->attr('name', 'maxPerIP'); $f->label = $this->_('Max password reset requests per IP address or session'); $f->description = $this->_('Use this option to prevent the same IP address or session from flooding reset requests.'); @@ -1103,8 +1111,9 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $f->columnWidth = 50; $f->attr('value', $this->maxPerIP); $form->add($f); - - $f = $this->wire('modules')->get('InputfieldCheckbox'); + + /** @var InputfieldCheckbox $f */ + $f = $modules->get('InputfieldCheckbox'); $f->attr('name', 'useLog'); $f->label = $this->_('Log activity?'); $f->description = $this->_('When enabled, password reset requests will be logged.'); @@ -1116,7 +1125,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $form->add($f); /** @var InputfieldAsmSelect $f */ - $f = $this->wire('modules')->get('InputfieldAsmSelect'); + $f = $modules->get('InputfieldAsmSelect'); $f->attr('name', 'confirmFields'); $f->label = $this->_('Confirm field values') . $optional; $f->description = $this->_('As an extra verification in the last step, ask user to confirm values of these fields before accepting new password.'); @@ -1131,7 +1140,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $form->add($f); /** @var InputfieldCheckboxes $f */ - $f = $this->wire('modules')->get('InputfieldCheckboxes'); + $f = $modules->get('InputfieldCheckboxes'); $f->attr('name', 'allowRoles'); $f->label = $this->_('Allowed roles') . $optional; $f->description = $this->_('To only allow certain roles to reset password, select them here.'); @@ -1145,7 +1154,7 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $form->add($f); /** @var InputfieldCheckboxes $f */ - $f = $this->wire('modules')->get('InputfieldCheckboxes'); + $f = $modules->get('InputfieldCheckboxes'); $f->attr('name', 'blockRoles'); $f->label = $this->_('Blocked roles') . $optional; $f->description = $this->_('To block certain roles from resetting password, select them here.'); @@ -1158,14 +1167,14 @@ class ProcessForgotPassword extends Process implements ConfigurableModule { $form->add($f); /** @var InputfieldCheckbox $f */ - $f = $this->wire('modules')->get('InputfieldCheckbox'); + $f = $modules->get('InputfieldCheckbox'); $f->attr('name', '_clearCache'); $f->label = $this->_('Clear password reset request caches and tables'); $f->description = $this->_('This happens automatically over time but can be cleared manually if desired.'); $f->collapsed = Inputfield::collapsedYes; $form->add($f); - if($this->wire('input')->post('_clearCache')) { + if($this->wire()->input->post('_clearCache')) { $this->clearRequests(); $this->message($this->_('Cleared password reset requests')); } diff --git a/wire/modules/Process/ProcessList.module b/wire/modules/Process/ProcessList.module index 2e0ef0bb..1a32fa89 100644 --- a/wire/modules/Process/ProcessList.module +++ b/wire/modules/Process/ProcessList.module @@ -8,7 +8,7 @@ * For more details about how Process modules work, please see: * /wire/core/Process.php * - * ProcessWire 3.x, Copyright 2016 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @@ -23,7 +23,7 @@ class ProcessList extends Process { 'version' => 101, 'permanent' => true, 'permission' => 'page-view', - ); + ); } @@ -32,6 +32,10 @@ class ProcessList extends Process { } protected function render() { + + $modules = $this->wire()->modules; + $sanitizer = $this->wire()->sanitizer; + $defaults = array( 'dlClass' => 'nav', 'dtClass' => '', @@ -40,13 +44,14 @@ class ProcessList extends Process { 'disabledClass' => 'ui-priority-secondary', 'showIcon' => true, ); - $settings = $this->wire('config')->ProcessList; + + $settings = $this->wire()->config->ProcessList; if(!is_array($settings)) $settings = array(); $settings = array_merge($defaults, $settings); $out = "\n
"; $cnt = 0; - foreach($this->page->children("check_access=0") as $child) { + foreach($this->wire()->page->children("check_access=0") as $child) { if(!$child->viewable()) continue; @@ -56,7 +61,7 @@ class ProcessList extends Process { if($child->process) { - $info = $this->modules->getModuleInfoVerbose($child->process, array('noCache' => true)); + $info = $modules->getModuleInfoVerbose($child->process, array('noCache' => true)); if($settings['showIcon']) { $icon = $child->get('page_icon'); if(!$icon) $icon = $info['icon']; @@ -71,14 +76,14 @@ class ProcessList extends Process { if(!strlen($title)) $title = $child->name; $titleTranslated = __($title, '/wire/templates-admin/default.php'); if($titleTranslated && $titleTranslated != $title) $title = $titleTranslated; - $title = $this->wire('sanitizer')->entities1($title); + $title = $sanitizer->entities1($title); if($child->summary) { $summary = $child->summary; } else { $summary = $info['summary']; } - $summary = $this->wire('sanitizer')->entities1($summary); + $summary = $sanitizer->entities1($summary); } else { @@ -88,7 +93,7 @@ class ProcessList extends Process { $dtClass .= ' ' . $settings['disabledClass']; $ddClass .= ' ' . $settings['disabledClass']; } else if($child->summary) { - $summary = $this->wire('sanitizer')->entities($child->getUnformatted('summary')); + $summary = $sanitizer->entities($child->getUnformatted('summary')); } else { $summary = ''; } @@ -104,6 +109,7 @@ class ProcessList extends Process { $out .= "\n
"; if(!$cnt) $out = ''; + return $out; } } diff --git a/wire/modules/Process/ProcessLogin/ProcessLogin.module b/wire/modules/Process/ProcessLogin/ProcessLogin.module index 37a7dbd5..777e6c2d 100644 --- a/wire/modules/Process/ProcessLogin/ProcessLogin.module +++ b/wire/modules/Process/ProcessLogin/ProcessLogin.module @@ -8,7 +8,7 @@ * For more details about how Process modules work, please see: * /wire/core/Process.php * - * ProcessWire 3.x, Copyright 2020 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @property bool $allowForgot Whether the ProcessForgotPassword module is installed. @@ -179,10 +179,10 @@ class ProcessLogin extends Process implements ConfigurableModule { $this->id = isset($_GET['id']) ? (int) $_GET['id'] : ''; // id no longer used as anything but a toggle (on/off) $this->set('allowForgot', $this->modules->isInstalled('ProcessForgotPassword')); - $this->isAdmin = $this->wire('page')->template == 'admin'; + $this->isAdmin = $this->wire()->page->template == 'admin'; $this->useEmailLogin = $this->useEmailLogin(); - return parent::init(); + parent::init(); } /** @@ -250,13 +250,13 @@ class ProcessLogin extends Process implements ConfigurableModule { if(!$this->emailField) return false; /** @var Field $field */ - $field = $this->fields->get($this->emailField); + $field = $this->wire()->fields->get($this->emailField); if(!$field) return false; if(!$field->type instanceof FieldtypeEmail) return false; if(!$field->hasFlag(Field::flagUnique)) return false; /** @var Template $template */ - $template = $this->templates->get($this->config->userTemplateID); + $template = $this->wire()->templates->get($this->wire()->config->userTemplateID); if(!$template || !$template->hasField($field)) return false; return (int) $this->allowEmail; @@ -274,7 +274,7 @@ class ProcessLogin extends Process implements ConfigurableModule { * */ public function setLoginURL($url) { - $url = $this->wire('sanitizer')->url($url, array('throw' => true)); + $url = $this->wire()->sanitizer->url($url, array('throw' => true)); $this->loginURL = $url; return $this; } @@ -290,7 +290,7 @@ class ProcessLogin extends Process implements ConfigurableModule { * */ public function setLogoutURL($url) { - $url = $this->wire('sanitizer')->url($url, array('throw' => true)); + $url = $this->wire()->sanitizer->url($url, array('throw' => true)); $this->logoutURL = $url; return $this; } @@ -344,7 +344,7 @@ class ProcessLogin extends Process implements ConfigurableModule { // two factor authentication if($tfa->success()) { $this->tfaLoginSuccess = true; - $this->loginSuccess($this->wire('user')); + $this->loginSuccess($this->wire()->user); $this->afterLoginRedirect('./'); } else { return $tfa->render(); @@ -395,9 +395,8 @@ class ProcessLogin extends Process implements ConfigurableModule { * */ public function getTfa() { - $tfa = null; $tfas = $this->wire()->modules->findByPrefix('Tfa'); - if(!count($tfas)) return $tfa; + if(!count($tfas)) return null; $tfa = new Tfa(); $this->wire($tfa); $tfa->rememberDays = $this->tfaRememberDays; @@ -416,6 +415,10 @@ class ProcessLogin extends Process implements ConfigurableModule { */ protected function getLoginName() { + $sanitizer = $this->wire()->sanitizer; + $config = $this->wire()->config; + $users = $this->wire()->users; + $value = $this->nameField->attr('value'); if(!strlen($value)) return false; @@ -433,7 +436,7 @@ class ProcessLogin extends Process implements ConfigurableModule { } // at this point we are dealing with an email login - $value = strtolower($this->sanitizer->email($value)); + $value = strtolower($sanitizer->email($value)); $this->submitLoginName = $value; if(empty($value)) return false; @@ -444,7 +447,7 @@ class ProcessLogin extends Process implements ConfigurableModule { } $error = $this->labels('email-not-supported'); - $items = $this->users->find("include=all, $this->emailField=" . $this->sanitizer->selectorValue($value)); + $items = $users->find("include=all, $this->emailField=" . $sanitizer->selectorValue($value)); if(!$items->count()) { // fail: no matches @@ -453,7 +456,7 @@ class ProcessLogin extends Process implements ConfigurableModule { } else if($items->count() > 1) { // fail: more than one match - if($this->config->debug) $error .= ' (not unique)'; + if($config->debug) $error .= ' (not unique)'; $this->loginFailed($value, $error); return false; } @@ -463,7 +466,7 @@ class ProcessLogin extends Process implements ConfigurableModule { if($user->status > Page::statusHidden) { // hidden, unpublished, trash - if($this->config->debug) $error .= ' (inactive)'; + if($config->debug) $error .= ' (inactive)'; $this->loginFailed($value, $error); return false; } @@ -566,13 +569,14 @@ class ProcessLogin extends Process implements ConfigurableModule { public function ___executeLogout() { if($this->logoutURL) { $url = $this->logoutURL; - } else if($this->isAdmin || $this->wire('page')->template == 'admin') { - $url = $this->config->urls->admin . './?loggedout=1'; + } else if($this->isAdmin || $this->wire()->page->template->name === 'admin') { + $url = $this->wire()->config->urls->admin . './?loggedout=1'; } else { $url = "./?logout=2"; } - $this->session->logout(); - $this->session->redirect($url, false); + $session = $this->wire()->session; + $session->logout(); + $session->redirect($url, false); return ''; } @@ -585,8 +589,7 @@ class ProcessLogin extends Process implements ConfigurableModule { */ protected function ___beforeLogin() { - /** @var Session $session */ - $session = $this->wire('session'); + $session = $this->wire()->session; $beforeLoginVars = $this->getBeforeLoginVars(); $session->setFor($this, 'beforeLoginVars', $beforeLoginVars); @@ -596,24 +599,30 @@ class ProcessLogin extends Process implements ConfigurableModule { // if checks already completed don't run them again if($session->getFor($this, 'beforeLoginChecks')) return; + + $modules = $this->wire()->modules; + $config = $this->wire()->config; + $input = $this->wire()->input; + $files = $this->wire()->files; + $log = $this->wire()->log; // any remaining checks only if currently in the admin if(!$this->isAdmin) return; if( ini_get('session.save_handler') == 'files' - && !$this->wire('modules')->isInstalled('SessionHandlerDB') - && !$this->wire('input')->get('db') + && !$modules->isInstalled('SessionHandlerDB') + && !$input->get('db') ) { $installSessionDB = false; - $path = $this->config->paths->sessions; + $path = $config->paths->sessions; $error = ''; if(!file_exists($path)) { - $this->wire('files')->mkdir($path); + $files->mkdir($path); clearstatcache(); if(file_exists($path)) { - $this->wire('log')->message("Created session path $path"); + $log->message("Created session path $path"); } else { $installSessionDB = true; $error = "Session path $path does not exist and we are unable to create it."; @@ -621,10 +630,10 @@ class ProcessLogin extends Process implements ConfigurableModule { } if(!is_writable($path)) { - $this->wire('files')->chmod($path); + $files->chmod($path); clearstatcache(); if(is_writable($path)) { - $this->wire('log')->message("Updated session path to be writable $path"); + $log->message("Updated session path to be writable $path"); } else { $installSessionDB = true; $error = "Unable to write to session path $path, and unable to fix the permissions."; @@ -633,12 +642,12 @@ class ProcessLogin extends Process implements ConfigurableModule { // if we can't get file-based sessions going, switch to database sessions to ensure admin can login if($installSessionDB) { - if($error) $this->wire('log')->error($error); - if($this->wire('modules')->get('SessionHandlerDB')) { - $this->wire('log')->error("Installed SessionHandlerDB as an alternate session handler. If you wish to uninstall this, do so after correcting the session path error."); - $this->wire('session')->redirect("./?db=1"); // db param to prevent potential infinite redirect + if($error) $log->error($error); + if($modules->get('SessionHandlerDB')) { + $log->error("Installed SessionHandlerDB as an alternate session handler. If you wish to uninstall this, do so after correcting the session path error."); + $session->redirect("./?db=1"); // db param to prevent potential infinite redirect } else { - $this->wire('log')->error("Unable to install alternate session handler module SessionHandlerDB"); + $log->error("Unable to install alternate session handler module SessionHandlerDB"); $this->error("Session write error. Login may not be possible."); } } @@ -655,9 +664,9 @@ class ProcessLogin extends Process implements ConfigurableModule { * */ protected function ___afterLogin() { - if($this->wire('user')->isSuperuser()) { + if($this->wire()->user->isSuperuser()) { /** @var SystemUpdater $systemUpdater */ - $systemUpdater = $this->wire('modules')->get('SystemUpdater'); + $systemUpdater = $this->wire()->modules->get('SystemUpdater'); if($systemUpdater) { $updatesApplied = $systemUpdater->getUpdatesApplied(); $checks = $systemUpdater->getChecks(); @@ -688,6 +697,8 @@ class ProcessLogin extends Process implements ConfigurableModule { */ protected function ___buildLoginForm() { + $modules = $this->wire()->modules; + $useEmailLogin = $this->useEmailLogin(); $nameInputType = 'InputfieldText'; $nameInputLabel = $this->labels('username'); // Login form: username field label @@ -699,28 +710,28 @@ class ProcessLogin extends Process implements ConfigurableModule { $nameInputLabel = $this->labels('username-or-email'); // Login form: username OR email field label } - $this->nameField = $this->modules->get($nameInputType); + $this->nameField = $modules->get($nameInputType); $this->nameField->label = $nameInputLabel; $this->nameField->attr('id+name', 'login_name'); $this->nameField->attr('class', $this->className() . 'Name'); $this->nameField->addClass('InputfieldFocusFirst'); $this->nameField->collapsed = Inputfield::collapsedNever; - $this->passField = $this->modules->get('InputfieldText'); + $this->passField = $modules->get('InputfieldText'); $this->passField->set('label', $this->labels('password')); // Login form: password field label $this->passField->attr('id+name', 'login_pass'); $this->passField->attr('type', 'password'); $this->passField->attr('class', $this->className() . 'Pass'); $this->passField->collapsed = Inputfield::collapsedNever; - $this->submitField = $this->modules->get('InputfieldSubmit'); + $this->submitField = $modules->get('InputfieldSubmit'); $this->submitField->attr('name', 'login_submit'); $this->submitField->attr('value', $this->labels('login')); // Login form: submit login button - $this->form = $this->modules->get('InputfieldForm'); + $this->form = $modules->get('InputfieldForm'); // we'll retain an ID field in the GET url, if it was there (note: no longer used as anything but a toggle on/off) - $this->form->attr('action', "./" . ($this->id ? "?id={$this->id}" : '')); + $this->form->attr('action', "./" . ($this->id ? "?id=$this->id" : '')); $this->form->addClass('InputfieldFormFocusFirst'); $this->form->attr('id', $this->className() . 'Form'); @@ -731,19 +742,21 @@ class ProcessLogin extends Process implements ConfigurableModule { if($this->isAdmin) { // detect hidpi at login (populated from js) /** @var InputfieldHidden $f */ - $f = $this->modules->get('InputfieldHidden'); + $f = $modules->get('InputfieldHidden'); $f->attr('id+name', 'login_hidpi'); $f->attr('value', 0); $this->form->add($f); // detect touch device login (populated from js) - $f = $this->modules->get('InputfieldHidden'); + /** @var InputfieldHidden $f */ + $f = $modules->get('InputfieldHidden'); $f->attr('id+name', 'login_touch'); $f->attr('value', 0); $this->form->add($f); // detect touch device login (populated from js) - $f = $this->modules->get('InputfieldHidden'); + /** @var InputfieldHidden $f */ + $f = $modules->get('InputfieldHidden'); $f->attr('id+name', 'login_width'); $f->attr('value', 0); $this->form->add($f); @@ -765,10 +778,10 @@ class ProcessLogin extends Process implements ConfigurableModule { * */ protected function ___renderLoginForm() { - $loggedIn = $this->wire('user')->isLoggedin(); + $loggedIn = $this->wire()->user->isLoggedin(); $out = ''; - if($this->wire('input')->get('login') && $loggedIn) { + if($this->wire()->input->get('login') && $loggedIn) { // redirect to page after login $this->afterLoginRedirect(); } else if($loggedIn) { @@ -784,9 +797,8 @@ class ProcessLogin extends Process implements ConfigurableModule { if(count($links)) { $out .= str_replace('{out}', implode($this->markup('login-links-split'), $links), $this->markup('login-links')); } - if(!$this->wire('modules')->isInstalled('InputDetect')) { - /** @var Config $config */ - $config = $this->wire('config'); + if(!$this->wire()->modules->isInstalled('InputDetect')) { + $config = $this->wire()->config; $config->scripts->prepend($config->urls('ProcessLogin') . 'what-input.min.js'); } } @@ -840,14 +852,15 @@ class ProcessLogin extends Process implements ConfigurableModule { * */ protected function ___afterLoginOutput() { + $config = $this->wire()->config; /** @var InputfieldButton $btn */ - $btn = $this->wire('modules')->get('InputfieldButton'); - if($this->wire('user')->hasPermission('profile-edit')) { + $btn = $this->wire()->modules->get('InputfieldButton'); + if($this->wire()->user->hasPermission('profile-edit')) { $btn->value = $this->labels('edit-profile'); - $btn->href = $this->config->urls->admin . 'profile/'; + $btn->href = $config->urls->admin . 'profile/'; } else { $btn->value = $this->labels('continue'); - $btn->href = $this->wire('config')->urls->root; + $btn->href = $config->urls->root; } return "

" . $btn->render() . "

"; } @@ -961,7 +974,6 @@ class ProcessLogin extends Process implements ConfigurableModule { */ protected function ___loginSuccess(User $user) { - /** @var Session $session */ $session = $this->wire()->session; if($this->isAdmin) { @@ -978,9 +990,10 @@ class ProcessLogin extends Process implements ConfigurableModule { if(!$user->hasTfa() && count($this->tfaRecRoleIDs) && !$this->tfaLoginSuccess) { // determine if Tfa module is installed and user has role requiring Tfa $requireTfa = false; - if(count($this->wire('modules')->findByPrefix('Tfa'))) { + $roles = $this->wire()->roles; + if(count($this->wire()->modules->findByPrefix('Tfa'))) { foreach($this->tfaRecRoleIDs as $roleID) { - $role = $this->wire('roles')->get((int) $roleID); + $role = $roles->get((int) $roleID); if($role && $user->hasRole($role)) { $requireTfa = true; break; @@ -988,7 +1001,7 @@ class ProcessLogin extends Process implements ConfigurableModule { } } if($requireTfa) { - $url = $this->wire('config')->urls('admin') . 'profile/#wrap_Inputfield_tfa_type'; + $url = $this->wire()->config->urls('admin') . 'profile/#wrap_Inputfield_tfa_type'; $session->setFor('_user', 'requireTfa', $url); } } @@ -1004,14 +1017,13 @@ class ProcessLogin extends Process implements ConfigurableModule { */ public function getModuleConfigInputfields(InputfieldWrapper $inputfields) { - /** @var Modules $modules */ - $modules = $this->wire('modules'); + $modules = $this->wire()->modules; /** @var InputfieldRadios $f */ $f = $modules->get('InputfieldRadios'); $emailAllow = true; - $emailField = $this->fields->get($this->emailField); /** @var Field $field */ + $emailField = $this->wire()->fields->get($this->emailField); /** @var Field $field */ $emailAttrs = array(); $emailLabel = $this->_('Email address'); $emailNotes = array(); diff --git a/wire/modules/System/SystemUpdater/SystemUpdater.module b/wire/modules/System/SystemUpdater/SystemUpdater.module index 9d37f1cf..a529375d 100644 --- a/wire/modules/System/SystemUpdater/SystemUpdater.module +++ b/wire/modules/System/SystemUpdater/SystemUpdater.module @@ -5,7 +5,7 @@ * * ProcessWire System Helper Module * - * ProcessWire 3.x, Copyright 2020 by Ryan Cramer + * ProcessWire 3.x, Copyright 2022 by Ryan Cramer * https://processwire.com * * @method coreVersionChange($fromVersion, $toVersion) @@ -75,7 +75,7 @@ class SystemUpdater extends WireData implements Module, ConfigurableModule { */ public function init() { - $config = $this->wire('config'); + $config = $this->wire()->config; $info = self::getModuleInfo(); $moduleVersion = $info['version']; @@ -88,7 +88,7 @@ class SystemUpdater extends WireData implements Module, ConfigurableModule { if(empty($systemVersion)) { // double check, just in case (should not be possible for this to occur) - $this->configData = $this->wire('modules')->getModuleConfigData($this); + $this->configData = $this->wire()->modules->getModuleConfigData($this); $systemVersion = (int) isset($this->configData['systemVersion']) ? $this->configData['systemVersion'] : 0; } @@ -122,11 +122,13 @@ class SystemUpdater extends WireData implements Module, ConfigurableModule { static $called = false; if($called) return; // just in case we add auto-ready support to non-autoload modules - if($this->wire('page')->template != 'admin') return; - if($this->wire('config')->ajax) return; + if($this->wire()->page->template != 'admin') return; + + $config = $this->wire()->config; + if($config->ajax) return; $coreVersion = isset($this->configData['coreVersion']) ? $this->configData['coreVersion'] : ''; - $configVersion = $this->wire('config')->version; + $configVersion = $config->version; if($coreVersion != $configVersion) $this->coreVersionChange($coreVersion, $configVersion); $called = true; } @@ -143,32 +145,35 @@ class SystemUpdater extends WireData implements Module, ConfigurableModule { */ protected function ___coreVersionChange($fromVersion, $toVersion) { + $modules = $this->wire()->modules; + $session = $this->wire()->session; + $config = $this->wire()->config; + $this->message(sprintf($this->_('Detected core version change %1$s => %2$s'), $fromVersion, $toVersion)); if( (strpos($fromVersion, '2') === 0 && strpos($toVersion, '3') === 0) || (strpos($fromVersion, '3') === 0 && strpos($toVersion, '2') === 0)) { // clear FileCompiler cache - $config = $this->wire('config'); if($config->templateCompile || $config->moduleCompile) { /** @var FileCompiler $compiler */ - $compiler = $this->wire(new FileCompiler($this->wire('config')->paths->templates)); + $compiler = $this->wire(new FileCompiler($config->paths->templates)); $compiler->clearCache(true); $this->message($this->_('Cleared file compiler cache')); } } - + if(!$this->numUpdatesApplied) { // reset modules cache, only if it hasn't been reset already by a system update - $this->modules->resetCache(); + $modules->resetCache(); } $this->configData['coreVersion'] = $toVersion; - $this->wire('modules')->saveModuleConfigData($this, $this->configData); + $modules->saveModuleConfigData($this, $this->configData); // remove admin theme cached info in session - foreach($this->wire('session') as $key => $value) { + foreach($session as $key => $value) { if(strpos($key, 'AdminTheme') === 0) { - $this->wire('session')->remove($key); + $session->remove($key); } } } @@ -182,11 +187,12 @@ class SystemUpdater extends WireData implements Module, ConfigurableModule { */ public function saveSystemVersion($version) { if($this->manualVersion == $version) return false; + $config = $this->wire()->config; $version = (int) $version; - $this->wire('config')->systemVersion = $version; + $config->systemVersion = $version; $this->configData['systemVersion'] = $version; - $this->configData['coreVersion'] = $this->wire('config')->version; - $this->wire('modules')->saveModuleConfigData($this, $this->configData); + $this->configData['coreVersion'] = $config->version; + $this->wire()->modules->saveModuleConfigData($this, $this->configData); $this->message("Update #$version: Completed!"); return true; } @@ -357,12 +363,12 @@ class SystemUpdater extends WireData implements Module, ConfigurableModule { /** * Log a message to system-updater.txt log file * - * @param string $text + * @param string $str * */ - public function log($text) { + public function log($str) { $options = array('showUser' => false, 'showPage' => false); - $this->wire('log')->save('system-updater', $text, $options); + $this->wire()->log->save('system-updater', $str, $options); } /** @@ -374,29 +380,36 @@ class SystemUpdater extends WireData implements Module, ConfigurableModule { */ public function getModuleConfigInputfields(array $data) { + $modules = $this->wire()->modules; + $config = $this->wire()->config; + $sanitizer = $this->wire()->sanitizer; + $inputfields = $this->wire(new InputfieldWrapper()); - $logfile = $this->wire('config')->paths->logs . 'system-updater.txt'; + $logfile = $config->paths->logs . 'system-updater.txt'; if(is_file($logfile)) { - $f = $this->wire('modules')->get('InputfieldMarkup'); + /** @var InputfieldMarkup $f */ + $f = $modules->get('InputfieldMarkup'); $f->attr('name', '_log'); $f->label = $this->_('System Update Log'); - $logContent = $this->wire('sanitizer')->unentities(file_get_contents($logfile)); + $logContent = $sanitizer->unentities(file_get_contents($logfile)); $logContent = preg_replace('!(.+?)!', '$1', $logContent); - $f->value = '
' . $this->wire('sanitizer')->entities($logContent) . '
'; + $f->value = '
' . $sanitizer->entities($logContent) . '
'; $inputfields->add($f); } - - $f = $this->wire('modules')->get('InputfieldInteger'); + + /** @var InputfieldInteger $f */ + $f = $modules->get('InputfieldInteger'); $f->attr('name', 'systemVersion'); $f->label = $this->_('System Version'); $f->description = $this->_('This lets you re-apply a system version update by reducing the version number.'); $f->attr('value', $data['systemVersion']); $inputfields->add($f); - - $f = $this->wire('modules')->get('InputfieldHidden'); + + /** @var InputfieldHidden $f */ + $f = $modules->get('InputfieldHidden'); $f->attr('name', 'coreVersion'); - $f->attr('value', $this->wire('config')->version); + $f->attr('value', $config->version); $inputfields->add($f); return $inputfields;