From a86ccb86190d867bd144a76a4c8d777e6c74a7b2 Mon Sep 17 00:00:00 2001 From: Jon Stovell Date: Wed, 15 Nov 2023 14:04:44 -0700 Subject: [PATCH] Updates coding style Signed-off-by: Jon Stovell --- Sources/Actions/Activate.php | 101 +- Sources/Actions/Admin/ACP.php | 1551 +++++----- Sources/Actions/Admin/AntiSpam.php | 322 +- Sources/Actions/Admin/Attachments.php | 1809 ++++++------ Sources/Actions/Admin/Bans.php | 1759 ++++++----- Sources/Actions/Admin/Boards.php | 583 ++-- Sources/Actions/Admin/Calendar.php | 339 ++- Sources/Actions/Admin/EndSession.php | 23 +- Sources/Actions/Admin/ErrorLog.php | 324 +- Sources/Actions/Admin/Features.php | 1251 ++++---- Sources/Actions/Admin/Find.php | 226 +- Sources/Actions/Admin/Home.php | 54 +- Sources/Actions/Admin/Languages.php | 1215 ++++---- Sources/Actions/Admin/Logs.php | 201 +- Sources/Actions/Admin/Mail.php | 315 +- Sources/Actions/Admin/Maintenance.php | 1371 +++++---- Sources/Actions/Admin/Membergroups.php | 690 ++--- Sources/Actions/Admin/Members.php | 1234 ++++---- Sources/Actions/Admin/Mods.php | 66 +- Sources/Actions/Admin/News.php | 695 +++-- Sources/Actions/Admin/PackageManager.php | 3 +- Sources/Actions/Admin/Permissions.php | 2166 +++++++------- Sources/Actions/Admin/Posts.php | 249 +- Sources/Actions/Admin/Registration.php | 243 +- Sources/Actions/Admin/RepairBoards.php | 1223 ++++---- Sources/Actions/Admin/Reports.php | 696 +++-- Sources/Actions/Admin/Search.php | 621 ++-- Sources/Actions/Admin/SearchEngines.php | 717 ++--- Sources/Actions/Admin/Server.php | 753 +++-- Sources/Actions/Admin/Smileys.php | 1864 ++++++------ Sources/Actions/Admin/Subscriptions.php | 1423 ++++----- Sources/Actions/Admin/Tasks.php | 428 +-- Sources/Actions/Admin/Themes.php | 1267 ++++---- Sources/Actions/Admin/Warnings.php | 108 +- Sources/Actions/Agreement.php | 70 +- Sources/Actions/AgreementAccept.php | 48 +- Sources/Actions/Announce.php | 137 +- Sources/Actions/AttachmentApprove.php | 72 +- Sources/Actions/AttachmentDownload.php | 164 +- Sources/Actions/AttachmentUpload.php | 318 +- Sources/Actions/AutoSuggest.php | 179 +- Sources/Actions/BoardIndex.php | 382 ++- Sources/Actions/BuddyListToggle.php | 46 +- Sources/Actions/Calendar.php | 933 +++--- Sources/Actions/CoppaForm.php | 59 +- Sources/Actions/Credits.php | 230 +- Sources/Actions/Display.php | 708 +++-- Sources/Actions/DisplayAdminFile.php | 46 +- Sources/Actions/Feed.php | 2542 ++++++++-------- Sources/Actions/FindMember.php | 45 +- Sources/Actions/Groups.php | 571 ++-- Sources/Actions/Help.php | 37 +- Sources/Actions/HelpAdmin.php | 46 +- Sources/Actions/JavaScriptModify.php | 252 +- Sources/Actions/Like.php | 361 +-- Sources/Actions/Login.php | 41 +- Sources/Actions/Login2.php | 363 ++- Sources/Actions/LoginTFA.php | 56 +- Sources/Actions/Logout.php | 72 +- Sources/Actions/Memberlist.php | 498 ++-- Sources/Actions/MessageIndex.php | 557 ++-- Sources/Actions/Moderation/EndSession.php | 23 +- Sources/Actions/Moderation/Groups.php | 3 +- Sources/Actions/Moderation/Home.php | 305 +- Sources/Actions/Moderation/Logs.php | 554 ++-- Sources/Actions/Moderation/Main.php | 246 +- Sources/Actions/Moderation/Posts.php | 582 ++-- .../Actions/Moderation/ReportedContent.php | 757 ++--- Sources/Actions/Moderation/ShowNotice.php | 35 +- Sources/Actions/Moderation/Warnings.php | 491 ++-- Sources/Actions/Moderation/WatchedUsers.php | 329 ++- Sources/Actions/MsgDelete.php | 80 +- Sources/Actions/Notify.php | 204 +- Sources/Actions/NotifyAnnouncements.php | 25 +- Sources/Actions/NotifyBoard.php | 21 +- Sources/Actions/NotifyTopic.php | 52 +- Sources/Actions/PersonalMessage.php | 403 ++- Sources/Actions/Post.php | 983 +++---- Sources/Actions/Post2.php | 623 ++-- Sources/Actions/Profile/Account.php | 61 +- Sources/Actions/Profile/Activate.php | 39 +- Sources/Actions/Profile/AlertsPopup.php | 26 +- Sources/Actions/Profile/BuddyIgnoreLists.php | 299 +- Sources/Actions/Profile/Delete.php | 145 +- Sources/Actions/Profile/Export.php | 331 ++- Sources/Actions/Profile/ExportAttachment.php | 45 +- Sources/Actions/Profile/ExportDownload.php | 62 +- Sources/Actions/Profile/ForumProfile.php | 45 +- Sources/Actions/Profile/GroupMembership.php | 203 +- Sources/Actions/Profile/IgnoreBoards.php | 81 +- Sources/Actions/Profile/IssueWarning.php | 329 +-- Sources/Actions/Profile/Main.php | 679 +++-- Sources/Actions/Profile/Notification.php | 823 +++--- Sources/Actions/Profile/PaidSubs.php | 205 +- Sources/Actions/Profile/Popup.php | 99 +- Sources/Actions/Profile/ShowAlerts.php | 89 +- Sources/Actions/Profile/ShowPermissions.php | 150 +- Sources/Actions/Profile/ShowPosts.php | 586 ++-- Sources/Actions/Profile/StatPanel.php | 150 +- Sources/Actions/Profile/Summary.php | 153 +- Sources/Actions/Profile/TFADisable.php | 47 +- Sources/Actions/Profile/TFASetup.php | 53 +- Sources/Actions/Profile/ThemeOptions.php | 39 +- Sources/Actions/Profile/Tracking.php | 681 +++-- Sources/Actions/Profile/ViewWarning.php | 105 +- Sources/Actions/QuickModeration.php | 553 ++-- Sources/Actions/QuickModerationInTopic.php | 101 +- Sources/Actions/QuoteFast.php | 79 +- Sources/Actions/Recent.php | 320 +- Sources/Actions/Register.php | 173 +- Sources/Actions/Register2.php | 543 ++-- Sources/Actions/Reminder.php | 179 +- Sources/Actions/ReportToMod.php | 294 +- Sources/Actions/RequestMembers.php | 42 +- Sources/Actions/Search.php | 174 +- Sources/Actions/Search2.php | 215 +- Sources/Actions/SendActivation.php | 15 +- Sources/Actions/SmStats.php | 50 +- Sources/Actions/Stats.php | 525 ++-- Sources/Actions/TopicMerge.php | 634 ++-- Sources/Actions/TopicMove.php | 79 +- Sources/Actions/TopicMove2.php | 219 +- Sources/Actions/TopicPrint.php | 122 +- Sources/Actions/TopicRemove.php | 107 +- Sources/Actions/TopicRestore.php | 362 ++- Sources/Actions/TopicSplit.php | 515 ++-- Sources/Actions/TrackIP.php | 345 +-- Sources/Actions/Unread.php | 440 +-- Sources/Actions/UnreadReplies.php | 145 +- Sources/Actions/VerificationCode.php | 421 ++- Sources/Actions/ViewQuery.php | 97 +- Sources/Actions/Who.php | 490 ++-- Sources/Actions/XmlHttp.php | 236 +- Sources/Alert.php | 762 ++--- Sources/Attachment.php | 1325 ++++----- Sources/Autoloader.php | 39 +- Sources/BBCodeParser.php | 2537 ++++++++-------- Sources/BackwardCompatibility.php | 24 +- Sources/Board.php | 1392 +++++---- Sources/BrowserDetector.php | 190 +- Sources/Cache/APIs/Apcu.php | 13 +- Sources/Cache/APIs/FileBased.php | 112 +- Sources/Cache/APIs/MemcacheImplementation.php | 75 +- .../Cache/APIs/MemcachedImplementation.php | 80 +- Sources/Cache/APIs/Postgres.php | 80 +- Sources/Cache/APIs/Sqlite.php | 72 +- Sources/Cache/APIs/Zend.php | 18 +- Sources/Cache/CacheApi.php | 189 +- Sources/Cache/CacheApiInterface.php | 8 +- Sources/Category.php | 400 ++- Sources/Class-BrowserDetect.php | 3 +- Sources/Class-CurlFetchWeb.php | 3 +- Sources/Class-Graphics.php | 3 +- Sources/Class-Package.php | 3 +- Sources/Class-Punycode.php | 3 +- Sources/Class-SearchAPI.php | 3 +- Sources/Class-TOTP.php | 3 +- Sources/Config.php | 1473 ++++------ Sources/Cookie.php | 179 +- Sources/Db/APIs/MySQL.php | 1271 ++++---- Sources/Db/APIs/PostgreSQL.php | 1376 +++++---- Sources/Db/DatabaseApi.php | 93 +- Sources/Db/DatabaseApiInterface.php | 55 +- Sources/Draft.php | 320 +- Sources/DynamicPropertyHelper.php | 127 +- Sources/Editor.php | 515 ++-- Sources/ErrorHandler.php | 334 ++- Sources/Event.php | 837 +++--- Sources/Forum.php | 278 +- Sources/Graphics/Gif/ColorTable.php | 18 +- Sources/Graphics/Gif/File.php | 71 +- Sources/Graphics/Gif/FileHeader.php | 31 +- Sources/Graphics/Gif/Image.php | 67 +- Sources/Graphics/Gif/ImageHeader.php | 27 +- Sources/Graphics/Gif/LzwCompression.php | 114 +- Sources/Graphics/Image.php | 470 +-- Sources/Group.php | 1358 +++++---- Sources/IP.php | 257 +- Sources/IntegrationHook.php | 140 +- Sources/ItemList.php | 218 +- Sources/Lang.php | 290 +- Sources/Logging.php | 548 ++-- Sources/Mail.php | 716 ++--- Sources/Mentions.php | 262 +- Sources/Menu.php | 257 +- Sources/Msg.php | 1883 ++++++------ Sources/News.php | 3 +- Sources/PackageManager/FtpConnection.php | 260 +- Sources/PackageManager/PackageManager.php | 2582 ++++++++-------- Sources/PackageManager/SubsPackage.php | 2373 +++++++-------- Sources/PackageManager/XmlArray.php | 386 +-- Sources/PageIndex.php | 88 +- Sources/PersonalMessage.php | 3 +- Sources/PersonalMessage/Conversation.php | 113 +- Sources/PersonalMessage/DraftPM.php | 148 +- Sources/PersonalMessage/Folder.php | 271 +- Sources/PersonalMessage/Label.php | 254 +- Sources/PersonalMessage/PM.php | 1297 ++++---- Sources/PersonalMessage/Popup.php | 27 +- Sources/PersonalMessage/Received.php | 254 +- Sources/PersonalMessage/Rule.php | 355 ++- Sources/PersonalMessage/Search.php | 273 +- Sources/PersonalMessage/SearchResult.php | 9 +- Sources/Poll.php | 757 ++--- Sources/PollChoice.php | 48 +- Sources/Profile-Actions.php | 3 +- Sources/Profile-Modify.php | 3 +- Sources/Profile-View.php | 3 +- Sources/Profile.php | 1657 +++++------ Sources/ProxyServer.php | 67 +- Sources/Punycode.php | 265 +- Sources/QueryString.php | 336 +-- Sources/ScheduledTasks.php | 3 +- Sources/Search.php | 3 +- Sources/Search/APIs/Custom.php | 193 +- Sources/Search/APIs/Fulltext.php | 179 +- Sources/Search/APIs/Standard.php | 3 +- Sources/Search/SearchApi.php | 1270 ++++---- Sources/Search/SearchApiInterface.php | 22 +- Sources/Search/SearchResult.php | 215 +- Sources/SearchAPI-Custom.php | 3 +- Sources/SearchAPI-Fulltext.php | 3 +- Sources/SearchAPI-Standard.php | 3 +- Sources/Security.php | 308 +- Sources/SecurityToken.php | 43 +- Sources/ServerSideIncludes.php | 1241 ++++---- Sources/Session.php | 115 +- Sources/Subs-Admin.php | 3 +- Sources/Subs-Auth.php | 3 +- Sources/Subs-BoardIndex.php | 3 +- Sources/Subs-Boards.php | 3 +- Sources/Subs-Calendar.php | 3 +- Sources/Subs-Categories.php | 3 +- Sources/Subs-Charset.php | 3 +- Sources/Subs-Compat.php | 191 +- Sources/Subs-Editor.php | 3 +- Sources/Subs-Graphics.php | 3 +- Sources/Subs-List.php | 3 +- Sources/Subs-Membergroups.php | 3 +- Sources/Subs-Members.php | 3 +- Sources/Subs-MembersOnline.php | 3 +- Sources/Subs-MessageIndex.php | 3 +- Sources/Subs-Package.php | 3 +- Sources/Subs-ReportedContent.php | 3 +- Sources/Subs-Sound.php | 3 +- Sources/Subs-Timezones.php | 3 +- Sources/Subscriptions/PayPal/Display.php | 42 +- Sources/Subscriptions/PayPal/Payment.php | 169 +- Sources/TOTP/Auth.php | 75 +- Sources/TaskRunner.php | 491 ++-- Sources/Theme.php | 1856 ++++++------ Sources/Time.php | 408 +-- Sources/TimeZone.php | 1720 ++++++----- Sources/Topic.php | 772 ++--- Sources/Unicode/Utf8String.php | 513 ++-- Sources/Url.php | 210 +- Sources/User.php | 2600 ++++++++--------- Sources/Utils.php | 1022 +++---- Sources/Verifier.php | 226 +- Sources/WebFetch/APIs/CurlFetcher.php | 91 +- Sources/WebFetch/APIs/FtpFetcher.php | 48 +- Sources/WebFetch/APIs/SocketFetcher.php | 110 +- Sources/WebFetch/WebFetchApi.php | 63 +- Sources/WebFetch/WebFetchApiInterface.php | 6 +- Sources/tasks/ApprovePost_Notify.php | 51 +- Sources/tasks/ApproveReply_Notify.php | 49 +- Sources/tasks/BackgroundTask.php | 12 +- Sources/tasks/Birthday_Notify.php | 64 +- Sources/tasks/Buddy_Notify.php | 11 +- Sources/tasks/CreateAttachment_Notify.php | 74 +- Sources/tasks/CreatePost_Notify.php | 460 +-- Sources/tasks/DailyMaintenance.php | 90 +- Sources/tasks/EventNew_Notify.php | 52 +- Sources/tasks/ExportProfileData.php | 2048 +++++++------ Sources/tasks/FetchSMFiles.php | 34 +- Sources/tasks/GroupAct_Notify.php | 68 +- Sources/tasks/GroupReq_Notify.php | 68 +- Sources/tasks/Likes_Notify.php | 70 +- Sources/tasks/MemberReportReply_Notify.php | 90 +- Sources/tasks/MemberReport_Notify.php | 69 +- Sources/tasks/MsgReportReply_Notify.php | 123 +- Sources/tasks/MsgReport_Notify.php | 102 +- Sources/tasks/PaidSubs.php | 74 +- Sources/tasks/PruneLogTopics.php | 91 +- Sources/tasks/Register_Notify.php | 68 +- Sources/tasks/RemoveOldDrafts.php | 23 +- Sources/tasks/RemoveTempAttachments.php | 30 +- Sources/tasks/RemoveTopicRedirects.php | 19 +- Sources/tasks/ScheduledTask.php | 34 +- Sources/tasks/SendDigests.php | 262 +- Sources/tasks/UpdateTldRegex.php | 1 + Sources/tasks/UpdateUnicode.php | 1270 ++++---- Sources/tasks/WeeklyMaintenance.php | 169 +- 293 files changed, 52437 insertions(+), 53606 deletions(-) diff --git a/Sources/Actions/Activate.php b/Sources/Actions/Activate.php index f4098fdbd9..fb2c486066 100644 --- a/Sources/Actions/Activate.php +++ b/Sources/Actions/Activate.php @@ -14,8 +14,8 @@ namespace SMF\Actions; use SMF\BackwardCompatibility; - use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\ErrorHandler; use SMF\IntegrationHook; use SMF\Lang; @@ -25,7 +25,6 @@ use SMF\Theme; use SMF\User; use SMF\Utils; -use SMF\Db\DatabaseApi as Db; /** * Activates a user's account. @@ -39,11 +38,11 @@ class Activate implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'Activate', - ), - ); + ], + ]; /******************* @@ -66,10 +65,10 @@ class Activate implements ActionInterface * * Available sub-actions. */ - public static array $subactions = array( + public static array $subactions = [ 'activate' => 'activate', 'resend' => 'resend', - ); + ]; /**************************** * Internal static properties @@ -94,36 +93,37 @@ class Activate implements ActionInterface */ public function execute(): void { - if (empty($_REQUEST['u']) && empty($_POST['user'])) - { - if (empty(Config::$modSettings['registration_method']) || Config::$modSettings['registration_method'] == '3') + if (empty($_REQUEST['u']) && empty($_POST['user'])) { + if (empty(Config::$modSettings['registration_method']) || Config::$modSettings['registration_method'] == '3') { ErrorHandler::fatalLang('no_access', false); + } Utils::$context['member_id'] = 0; Utils::$context['sub_template'] = 'resend'; Utils::$context['page_title'] = Lang::$txt['invalid_activation_resend']; Utils::$context['can_activate'] = empty(Config::$modSettings['registration_method']) || Config::$modSettings['registration_method'] == '1'; - Utils::$context['default_username'] = isset($_GET['user']) ? $_GET['user'] : ''; + Utils::$context['default_username'] = $_GET['user'] ?? ''; return; } // Get the code from the database... - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_member, validation_code, member_name, real_name, email_address, is_activated, passwd, lngfile FROM {db_prefix}members' . (empty($_REQUEST['u']) ? ' WHERE member_name = {string:email_address} OR email_address = {string:email_address}' : ' WHERE id_member = {int:id_member}') . ' LIMIT 1', - array( + [ 'id_member' => isset($_REQUEST['u']) ? (int) $_REQUEST['u'] : 0, - 'email_address' => isset($_POST['user']) ? $_POST['user'] : '', - ) + 'email_address' => $_POST['user'] ?? '', + ], ); // Does this user exist at all? - if (Db::$db->num_rows($request) == 0) - { + if (Db::$db->num_rows($request) == 0) { Utils::$context['sub_template'] = 'retry_activate'; Utils::$context['page_title'] = Lang::$txt['invalid_userid']; Utils::$context['member_id'] = 0; @@ -143,33 +143,37 @@ public function execute(): void $row['is_activated'] == 0 || $row['is_activated'] == 2 ) - ) - { - if (empty(Config::$modSettings['registration_method']) || Config::$modSettings['registration_method'] == 3) + ) { + if (empty(Config::$modSettings['registration_method']) || Config::$modSettings['registration_method'] == 3) { ErrorHandler::fatalLang('no_access', false); + } - if (!filter_var($_POST['new_email'], FILTER_VALIDATE_EMAIL)) + if (!filter_var($_POST['new_email'], FILTER_VALIDATE_EMAIL)) { ErrorHandler::fatal(sprintf(Lang::$txt['valid_email_needed'], Utils::htmlspecialchars($_POST['new_email'])), false); + } // Make sure their email isn't banned. User::isBannedEmail($_POST['new_email'], 'cannot_register', Lang::$txt['ban_register_prohibited']); // Ummm... don't even dare try to take someone else's email!! - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_member FROM {db_prefix}members WHERE email_address = {string:email_address} LIMIT 1', - array( + [ 'email_address' => $_POST['new_email'], - ) + ], ); - if (Db::$db->num_rows($request) != 0) - ErrorHandler::fatalLang('email_in_use', false, array(Utils::htmlspecialchars($_POST['new_email']))); + if (Db::$db->num_rows($request) != 0) { + ErrorHandler::fatalLang('email_in_use', false, [Utils::htmlspecialchars($_POST['new_email'])]); + } Db::$db->free_result($request); - User::updateMemberData($row['id_member'], array('email_address' => $_POST['new_email'])); + User::updateMemberData($row['id_member'], ['email_address' => $_POST['new_email']]); $row['email_address'] = $_POST['new_email']; $email_change = true; @@ -181,16 +185,15 @@ public function execute(): void && $_REQUEST['sa'] == 'resend' && ($row['is_activated'] == 0 || $row['is_activated'] == 2) && (!isset($_REQUEST['code']) || $_REQUEST['code'] == '') - ) - { - $replacements = array( + ) { + $replacements = [ 'REALNAME' => $row['real_name'], 'USERNAME' => $row['member_name'], 'ACTIVATIONLINK' => Config::$scripturl . '?action=activate;u=' . $row['id_member'] . ';code=' . $row['validation_code'], 'ACTIVATIONLINKWITHOUTCODE' => Config::$scripturl . '?action=activate;u=' . $row['id_member'], 'ACTIVATIONCODE' => $row['validation_code'], 'FORGOTPASSWORDLINK' => Config::$scripturl . '?action=reminder', - ); + ]; $emaildata = Mail::loadEmailTemplate('resend_activate_message', $replacements, empty($row['lngfile']) || empty(Config::$modSettings['userLanguage']) ? Lang::$default : $row['lngfile']); @@ -201,18 +204,14 @@ public function execute(): void // This will ensure we don't actually get an error message if it works! Utils::$context['error_title'] = Lang::$txt['invalid_activation_resend']; - ErrorHandler::fatalLang(!empty($email_change) ? 'change_email_success' : 'resend_email_success', false, array(), false); + ErrorHandler::fatalLang(!empty($email_change) ? 'change_email_success' : 'resend_email_success', false, [], false); } // Quit if this code is not right. - if (empty($_REQUEST['code']) || $row['validation_code'] != $_REQUEST['code']) - { - if (!empty($row['is_activated'])) - { + if (empty($_REQUEST['code']) || $row['validation_code'] != $_REQUEST['code']) { + if (!empty($row['is_activated'])) { ErrorHandler::fatalLang('already_activated', false); - } - elseif ($row['validation_code'] == '') - { + } elseif ($row['validation_code'] == '') { Lang::load('Profile'); ErrorHandler::fatal(sprintf(Lang::$txt['registration_not_approved'], Config::$scripturl . '?action=activate;user=' . $row['member_name']), false); } @@ -225,28 +224,27 @@ public function execute(): void } // Let the integration know that they've been activated! - IntegrationHook::call('integrate_activate', array($row['member_name'])); + IntegrationHook::call('integrate_activate', [$row['member_name']]); // Validation complete - update the database! - User::updateMemberData($row['id_member'], array('is_activated' => 1, 'validation_code' => '')); + User::updateMemberData($row['id_member'], ['is_activated' => 1, 'validation_code' => '']); // Also do a proper member stat re-evaluation. Logging::updateStats('member', false); // Notify the admin about new activations, but not re-activations. - if (empty($row['is_activated'])) - { + if (empty($row['is_activated'])) { Mail::adminNotify('activation', $row['id_member'], $row['member_name']); } - Utils::$context += array( + Utils::$context += [ 'page_title' => Lang::$txt['registration_successful'], 'sub_template' => 'login', 'default_username' => $row['member_name'], 'default_password' => '', 'never_expire' => false, - 'description' => Lang::$txt['activate_success'] - ); + 'description' => Lang::$txt['activate_success'], + ]; } /*********************** @@ -260,8 +258,9 @@ public function execute(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -284,8 +283,9 @@ public static function call(): void protected function __construct() { // Logged in users should not bother to activate their accounts - if (!empty(User::$me->id)) + if (!empty(User::$me->id)) { Utils::redirectexit(); + } Lang::load('Login'); Theme::loadTemplate('Login'); @@ -293,7 +293,8 @@ protected function __construct() } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Activate::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Activate::exportStatic')) { Activate::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/ACP.php b/Sources/Actions/Admin/ACP.php index a465fc356f..f4c072615d 100644 --- a/Sources/Actions/Admin/ACP.php +++ b/Sources/Actions/Admin/ACP.php @@ -13,11 +13,14 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\Actions\MessageIndex; +use SMF\Actions\Notify; +use SMF\BackwardCompatibility; use SMF\BBCodeParser; +use SMF\Cache\CacheApi; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\ErrorHandler; use SMF\IntegrationHook; use SMF\Lang; @@ -28,10 +31,6 @@ use SMF\Url; use SMF\User; use SMF\Utils; -use SMF\Actions\MessageIndex; -use SMF\Actions\Notify; -use SMF\Cache\CacheApi; -use SMF\Db\DatabaseApi as Db; /** * This class, unpredictable as this might be, handles basic administration. @@ -45,8 +44,8 @@ class ACP implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'AdminMain', 'prepareDBSettingContext' => 'prepareDBSettingContext', 'saveSettings' => 'saveSettings', @@ -56,8 +55,8 @@ class ACP implements ActionInterface 'updateAdminPreferences' => 'updateAdminPreferences', 'emailAdmins' => 'emailAdmins', 'adminLogin' => 'adminLogin', - ), - ); + ], + ]; /******************* * Public properties @@ -89,10 +88,10 @@ class ACP implements ActionInterface * please use the integrate_admin_areas hook to add your settings page to * $admin_areas['config']['areas']['modsettings']['subsections']. */ - public array $admin_areas = array( - 'forum' => array( + public array $admin_areas = [ + 'forum' => [ 'title' => 'admin_main', - 'permission' => array( + 'permission' => [ 'admin_forum', 'manage_permissions', 'moderate_forum', @@ -103,629 +102,629 @@ class ACP implements ActionInterface 'manage_boards', 'manage_smileys', 'manage_attachments', - ), - 'areas' => array( - 'index' => array( + ], + 'areas' => [ + 'index' => [ 'label' => 'admin_center', 'function' => __NAMESPACE__ . '\\Home::call', 'icon' => 'administration', - ), - 'credits' => array( + ], + 'credits' => [ 'label' => 'support_credits_title', 'function' => __NAMESPACE__ . '\\Home::call', 'icon' => 'support', - ), - 'news' => array( + ], + 'news' => [ 'label' => 'news_title', 'function' => __NAMESPACE__ . '\\News::call', 'icon' => 'news', - 'permission' => array( + 'permission' => [ 'edit_news', 'send_mail', 'admin_forum', - ), - 'subsections' => array( - 'editnews' => array( + ], + 'subsections' => [ + 'editnews' => [ 'label' => 'admin_edit_news', 'permission' => 'edit_news', - ), - 'mailingmembers' => array( + ], + 'mailingmembers' => [ 'label' => 'admin_newsletters', 'permission' => 'send_mail', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'settings', 'permission' => 'admin_forum', - ), - ), - ), - 'packages' => array( + ], + ], + ], + 'packages' => [ 'label' => 'package', 'function' => 'SMF\\PackageManager\\PackageManager::call', - 'permission' => array('admin_forum'), + 'permission' => ['admin_forum'], 'icon' => 'packages', - 'subsections' => array( - 'browse' => array( + 'subsections' => [ + 'browse' => [ 'label' => 'browse_packages', - ), - 'packageget' => array( + ], + 'packageget' => [ 'label' => 'download_packages', 'url' => '{scripturl}?action=admin;area=packages;sa=packageget;get', - ), - 'perms' => array( + ], + 'perms' => [ 'label' => 'package_file_perms', - ), - 'options' => array( + ], + 'options' => [ 'label' => 'package_settings', - ), - ), - ), - 'search' => array( + ], + ], + ], + 'search' => [ 'function' => __NAMESPACE__ . '\\Find::call', - 'permission' => array('admin_forum'), - 'select' => 'index' - ), - 'adminlogoff' => array( + 'permission' => ['admin_forum'], + 'select' => 'index', + ], + 'adminlogoff' => [ 'label' => 'admin_logoff', 'function' => __NAMESPACE__ . '\\EndSession::call', 'enabled' => true, 'icon' => 'exit', - ), - ), - ), - 'config' => array( + ], + ], + ], + 'config' => [ 'title' => 'admin_config', - 'permission' => array('admin_forum'), - 'areas' => array( - 'featuresettings' => array( + 'permission' => ['admin_forum'], + 'areas' => [ + 'featuresettings' => [ 'label' => 'modSettings_title', 'function' => __NAMESPACE__ . '\\Features::call', 'icon' => 'features', - 'subsections' => array( - 'basic' => array( + 'subsections' => [ + 'basic' => [ 'label' => 'mods_cat_features', - ), - 'bbc' => array( + ], + 'bbc' => [ 'label' => 'manageposts_bbc_settings', - ), - 'layout' => array( + ], + 'layout' => [ 'label' => 'mods_cat_layout', - ), - 'sig' => array( + ], + 'sig' => [ 'label' => 'signature_settings_short', - ), - 'profile' => array( + ], + 'profile' => [ 'label' => 'custom_profile_shorttitle', - ), - 'likes' => array( + ], + 'likes' => [ 'label' => 'likes', - ), - 'mentions' => array( + ], + 'mentions' => [ 'label' => 'mentions', - ), - 'alerts' => array( + ], + 'alerts' => [ 'label' => 'notifications', - ), - ), - ), - 'antispam' => array( + ], + ], + ], + 'antispam' => [ 'label' => 'antispam_title', 'function' => __NAMESPACE__ . '\\AntiSpam::call', 'icon' => 'security', - ), - 'languages' => array( + ], + 'languages' => [ 'label' => 'language_configuration', 'function' => __NAMESPACE__ . '\\Languages::call', 'icon' => 'languages', - 'subsections' => array( - 'edit' => array( + 'subsections' => [ + 'edit' => [ 'label' => 'language_edit', - ), - 'add' => array( + ], + 'add' => [ 'label' => 'language_add', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'language_settings', - ), - ), - ), - 'current_theme' => array( + ], + ], + ], + 'current_theme' => [ 'label' => 'theme_current_settings', 'function' => __NAMESPACE__ . '\\Themes::call', 'custom_url' => '{scripturl}?action=admin;area=theme;sa=list;th=%1$d', 'icon' => 'current_theme', - ), - 'theme' => array( + ], + 'theme' => [ 'label' => 'theme_admin', 'function' => __NAMESPACE__ . '\\Themes::call', 'custom_url' => '{scripturl}?action=admin;area=theme', 'icon' => 'themes', - 'subsections' => array( - 'admin' => array( + 'subsections' => [ + 'admin' => [ 'label' => 'themeadmin_admin_title', - ), - 'list' => array( + ], + 'list' => [ 'label' => 'themeadmin_list_title', - ), - 'reset' => array( + ], + 'reset' => [ 'label' => 'themeadmin_reset_title', - ), - 'edit' => array( + ], + 'edit' => [ 'label' => 'themeadmin_edit_title', - ), - ), - ), - 'modsettings' => array( + ], + ], + ], + 'modsettings' => [ 'label' => 'admin_modifications', 'function' => __NAMESPACE__ . '\\Mods::call', 'icon' => 'modifications', - 'subsections' => array( + 'subsections' => [ // MOD AUTHORS: If your mod has just a few simple // settings and doesn't need its own settings page, you // can use the integrate_general_mod_settings hook to // add them to the 'general' page. - 'general' => array( + 'general' => [ 'label' => 'mods_cat_modifications_misc', - ), + ], // MOD AUTHORS: If your mod has a custom settings page, // use the integrate_admin_areas hook to insert it here. - ), - ), - ), - ), - 'layout' => array( + ], + ], + ], + ], + 'layout' => [ 'title' => 'layout_controls', - 'permission' => array('manage_boards', 'admin_forum', 'manage_smileys', 'manage_attachments', 'moderate_forum'), - 'areas' => array( - 'manageboards' => array( + 'permission' => ['manage_boards', 'admin_forum', 'manage_smileys', 'manage_attachments', 'moderate_forum'], + 'areas' => [ + 'manageboards' => [ 'label' => 'admin_boards', 'function' => __NAMESPACE__ . '\\Boards::call', 'icon' => 'boards', - 'permission' => array('manage_boards'), - 'subsections' => array( - 'main' => array( + 'permission' => ['manage_boards'], + 'subsections' => [ + 'main' => [ 'label' => 'boards_edit', - ), - 'newcat' => array( + ], + 'newcat' => [ 'label' => 'mboards_new_cat', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'settings', 'admin_forum', - ), - ), - ), - 'postsettings' => array( + ], + ], + ], + 'postsettings' => [ 'label' => 'manageposts', 'function' => __NAMESPACE__ . '\\Posts::call', - 'permission' => array('admin_forum'), + 'permission' => ['admin_forum'], 'icon' => 'posts', - 'subsections' => array( - 'posts' => array( + 'subsections' => [ + 'posts' => [ 'label' => 'manageposts_settings', - ), - 'censor' => array( + ], + 'censor' => [ 'label' => 'admin_censored_words', - ), - 'topics' => array( + ], + 'topics' => [ 'label' => 'manageposts_topic_settings', - ), - 'drafts' => array( + ], + 'drafts' => [ 'label' => 'manage_drafts', - ), - ), - ), - 'managecalendar' => array( + ], + ], + ], + 'managecalendar' => [ 'label' => 'manage_calendar', 'function' => __NAMESPACE__ . '\\Calendar::call', 'icon' => 'calendar', - 'permission' => array('admin_forum'), + 'permission' => ['admin_forum'], 'inactive' => false, - 'subsections' => array( - 'holidays' => array( + 'subsections' => [ + 'holidays' => [ 'label' => 'manage_holidays', 'permission' => 'admin_forum', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'calendar_settings', 'permission' => 'admin_forum', - ), - ), - ), - 'managesearch' => array( + ], + ], + ], + 'managesearch' => [ 'label' => 'manage_search', 'function' => __NAMESPACE__ . '\\Search::call', 'icon' => 'search', - 'permission' => array('admin_forum'), - 'subsections' => array( - 'weights' => array( + 'permission' => ['admin_forum'], + 'subsections' => [ + 'weights' => [ 'label' => 'search_weights', - ), - 'method' => array( + ], + 'method' => [ 'label' => 'search_method', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'settings', - ), - ), - ), - 'smileys' => array( + ], + ], + ], + 'smileys' => [ 'label' => 'smileys_manage', 'function' => __NAMESPACE__ . '\\Smileys::call', 'icon' => 'smiley', - 'permission' => array('manage_smileys'), - 'subsections' => array( - 'editsets' => array( + 'permission' => ['manage_smileys'], + 'subsections' => [ + 'editsets' => [ 'label' => 'smiley_sets', - ), - 'addsmiley' => array( + ], + 'addsmiley' => [ 'label' => 'smileys_add', 'enabled' => true, - ), - 'editsmileys' => array( + ], + 'editsmileys' => [ 'label' => 'smileys_edit', 'enabled' => true, - ), - 'setorder' => array( + ], + 'setorder' => [ 'label' => 'smileys_set_order', 'enabled' => true, - ), - 'editicons' => array( + ], + 'editicons' => [ 'label' => 'icons_edit_message_icons', 'enabled' => true, - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'settings', - ), - ), - ), - 'manageattachments' => array( + ], + ], + ], + 'manageattachments' => [ 'label' => 'attachments_avatars', 'function' => __NAMESPACE__ . '\\Attachments::call', 'icon' => 'attachment', - 'permission' => array('manage_attachments'), - 'subsections' => array( - 'browse' => array( + 'permission' => ['manage_attachments'], + 'subsections' => [ + 'browse' => [ 'label' => 'attachment_manager_browse', - ), - 'attachments' => array( + ], + 'attachments' => [ 'label' => 'attachment_manager_settings', - ), - 'avatars' => array( + ], + 'avatars' => [ 'label' => 'attachment_manager_avatar_settings', - ), - 'attachpaths' => array( + ], + 'attachpaths' => [ 'label' => 'attach_directories', - ), - 'maintenance' => array( + ], + 'maintenance' => [ 'label' => 'attachment_manager_maintenance', - ), - ), - ), - 'sengines' => array( + ], + ], + ], + 'sengines' => [ 'label' => 'search_engines', 'inactive' => false, 'function' => __NAMESPACE__ . '\\SearchEngines::call', 'icon' => 'engines', 'permission' => 'admin_forum', - 'subsections' => array( - 'stats' => array( + 'subsections' => [ + 'stats' => [ 'label' => 'spider_stats', - ), - 'logs' => array( + ], + 'logs' => [ 'label' => 'spider_logs', - ), - 'spiders' => array( + ], + 'spiders' => [ 'label' => 'spiders', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'settings', - ), - ), - ), - ), - ), - 'members' => array( + ], + ], + ], + ], + ], + 'members' => [ 'title' => 'admin_manage_members', - 'permission' => array( + 'permission' => [ 'moderate_forum', 'manage_membergroups', 'manage_bans', 'manage_permissions', 'admin_forum', - ), - 'areas' => array( - 'viewmembers' => array( + ], + 'areas' => [ + 'viewmembers' => [ 'label' => 'admin_users', 'function' => __NAMESPACE__ . '\\Members::call', 'icon' => 'members', - 'permission' => array('moderate_forum'), - 'subsections' => array( - 'all' => array( + 'permission' => ['moderate_forum'], + 'subsections' => [ + 'all' => [ 'label' => 'view_all_members', - ), - 'search' => array( + ], + 'search' => [ 'label' => 'mlist_search', - ), - ), - ), - 'membergroups' => array( + ], + ], + ], + 'membergroups' => [ 'label' => 'admin_groups', 'function' => __NAMESPACE__ . '\\Membergroups::call', 'icon' => 'membergroups', - 'permission' => array('manage_membergroups'), - 'subsections' => array( - 'index' => array( + 'permission' => ['manage_membergroups'], + 'subsections' => [ + 'index' => [ 'label' => 'membergroups_edit_groups', 'permission' => 'manage_membergroups', - ), - 'add' => array( + ], + 'add' => [ 'label' => 'membergroups_new_group', 'permission' => 'manage_membergroups', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'settings', 'permission' => 'admin_forum', - ), - ), - ), - 'permissions' => array( + ], + ], + ], + 'permissions' => [ 'label' => 'edit_permissions', 'function' => __NAMESPACE__ . '\\Permissions::call', 'icon' => 'permissions', - 'permission' => array('manage_permissions'), - 'subsections' => array( - 'index' => array( + 'permission' => ['manage_permissions'], + 'subsections' => [ + 'index' => [ 'label' => 'permissions_groups', 'permission' => 'manage_permissions', - ), - 'board' => array( + ], + 'board' => [ 'label' => 'permissions_boards', 'permission' => 'manage_permissions', - ), - 'profiles' => array( + ], + 'profiles' => [ 'label' => 'permissions_profiles', 'permission' => 'manage_permissions', - ), - 'postmod' => array( + ], + 'postmod' => [ 'label' => 'permissions_post_moderation', 'permission' => 'manage_permissions', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'settings', 'permission' => 'admin_forum', - ), - ), - ), - 'regcenter' => array( + ], + ], + ], + 'regcenter' => [ 'label' => 'registration_center', 'function' => __NAMESPACE__ . '\\Registration::call', 'icon' => 'regcenter', - 'permission' => array( + 'permission' => [ 'admin_forum', 'moderate_forum', - ), - 'subsections' => array( - 'register' => array( + ], + 'subsections' => [ + 'register' => [ 'label' => 'admin_browse_register_new', 'permission' => 'moderate_forum', - ), - 'agreement' => array( + ], + 'agreement' => [ 'label' => 'registration_agreement', 'permission' => 'admin_forum', - ), - 'policy' => array( + ], + 'policy' => [ 'label' => 'privacy_policy', 'permission' => 'admin_forum', - ), - 'reservednames' => array( + ], + 'reservednames' => [ 'label' => 'admin_reserved_set', 'permission' => 'admin_forum', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'settings', 'permission' => 'admin_forum', - ), - ), - ), - 'warnings' => array( + ], + ], + ], + 'warnings' => [ 'label' => 'warnings', 'function' => __NAMESPACE__ . '\\Warnings::call', 'icon' => 'warning', 'inactive' => false, - 'permission' => array('admin_forum'), - ), - 'ban' => array( + 'permission' => ['admin_forum'], + ], + 'ban' => [ 'label' => 'ban_title', 'function' => __NAMESPACE__ . '\\Bans::call', 'icon' => 'ban', 'permission' => 'manage_bans', - 'subsections' => array( - 'list' => array( + 'subsections' => [ + 'list' => [ 'label' => 'ban_edit_list', - ), - 'add' => array( + ], + 'add' => [ 'label' => 'ban_add_new', - ), - 'browse' => array( + ], + 'browse' => [ 'label' => 'ban_trigger_browse', - ), - 'log' => array( + ], + 'log' => [ 'label' => 'ban_log', - ), - ), - ), - 'paidsubscribe' => array( + ], + ], + ], + 'paidsubscribe' => [ 'label' => 'paid_subscriptions', 'inactive' => false, 'function' => __NAMESPACE__ . '\\Subscriptions::call', 'icon' => 'paid', 'permission' => 'admin_forum', - 'subsections' => array( - 'view' => array( + 'subsections' => [ + 'view' => [ 'label' => 'paid_subs_view', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'settings', - ), - ), - ), - ), - ), - 'maintenance' => array( + ], + ], + ], + ], + ], + 'maintenance' => [ 'title' => 'admin_maintenance', - 'permission' => array('admin_forum'), - 'areas' => array( - 'serversettings' => array( + 'permission' => ['admin_forum'], + 'areas' => [ + 'serversettings' => [ 'label' => 'admin_server_settings', 'function' => __NAMESPACE__ . '\\Server::call', 'icon' => 'server', - 'subsections' => array( - 'general' => array( + 'subsections' => [ + 'general' => [ 'label' => 'general_settings', - ), - 'database' => array( + ], + 'database' => [ 'label' => 'database_settings', - ), - 'cookie' => array( + ], + 'cookie' => [ 'label' => 'cookies_sessions_settings', - ), - 'security' => array( + ], + 'security' => [ 'label' => 'security_settings', - ), - 'cache' => array( + ], + 'cache' => [ 'label' => 'caching_settings', - ), - 'export' => array( + ], + 'export' => [ 'label' => 'export_settings', - ), - 'loads' => array( + ], + 'loads' => [ 'label' => 'load_balancing_settings', - ), - 'phpinfo' => array( + ], + 'phpinfo' => [ 'label' => 'phpinfo_settings', - ), - ), - ), - 'maintain' => array( + ], + ], + ], + 'maintain' => [ 'label' => 'maintain_title', 'function' => __NAMESPACE__ . '\\Maintenance::call', 'icon' => 'maintain', - 'subsections' => array( - 'routine' => array( + 'subsections' => [ + 'routine' => [ 'label' => 'maintain_sub_routine', 'permission' => 'admin_forum', - ), - 'database' => array( + ], + 'database' => [ 'label' => 'maintain_sub_database', 'permission' => 'admin_forum', - ), - 'members' => array( + ], + 'members' => [ 'label' => 'maintain_sub_members', 'permission' => 'admin_forum', - ), - 'topics' => array( + ], + 'topics' => [ 'label' => 'maintain_sub_topics', 'permission' => 'admin_forum', - ), - 'hooks' => array( + ], + 'hooks' => [ 'label' => 'hooks_title_list', 'permission' => 'admin_forum', - ), - ), - ), - 'scheduledtasks' => array( + ], + ], + ], + 'scheduledtasks' => [ 'label' => 'maintain_tasks', 'function' => __NAMESPACE__ . '\\Tasks::call', 'icon' => 'scheduled', - 'subsections' => array( - 'tasks' => array( + 'subsections' => [ + 'tasks' => [ 'label' => 'maintain_tasks', 'permission' => 'admin_forum', - ), - 'tasklog' => array( + ], + 'tasklog' => [ 'label' => 'scheduled_log', 'permission' => 'admin_forum', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'scheduled_tasks_settings', 'permission' => 'admin_forum', - ), - ), - ), - 'mailqueue' => array( + ], + ], + ], + 'mailqueue' => [ 'label' => 'mailqueue_title', 'function' => __NAMESPACE__ . '\\Mail::call', 'icon' => 'mail', - 'subsections' => array( - 'browse' => array( + 'subsections' => [ + 'browse' => [ 'label' => 'mailqueue_browse', 'permission' => 'admin_forum', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'mailqueue_settings', 'permission' => 'admin_forum', - ), - 'test' => array( + ], + 'test' => [ 'label' => 'mailqueue_test', 'permission' => 'admin_forum', - ), - ), - ), - 'reports' => array( + ], + ], + ], + 'reports' => [ 'label' => 'generate_reports', 'function' => __NAMESPACE__ . '\\Reports::call', 'icon' => 'reports', - ), - 'logs' => array( + ], + 'logs' => [ 'label' => 'logs', 'function' => __NAMESPACE__ . '\\Logs::call', 'icon' => 'logs', - 'subsections' => array( - 'errorlog' => array( + 'subsections' => [ + 'errorlog' => [ 'label' => 'errorlog', 'permission' => 'admin_forum', 'enabled' => true, 'url' => '{scripturl}?action=admin;area=logs;sa=errorlog;desc', - ), - 'adminlog' => array( + ], + 'adminlog' => [ 'label' => 'admin_log', 'permission' => 'admin_forum', 'enabled' => true, - ), - 'modlog' => array( + ], + 'modlog' => [ 'label' => 'moderation_log', 'permission' => 'admin_forum', 'enabled' => true, - ), - 'banlog' => array( + ], + 'banlog' => [ 'label' => 'ban_log', 'permission' => 'manage_bans', - ), - 'spiderlog' => array( + ], + 'spiderlog' => [ 'label' => 'spider_logs', 'permission' => 'admin_forum', 'enabled' => true, - ), - 'tasklog' => array( + ], + 'tasklog' => [ 'label' => 'scheduled_log', 'permission' => 'admin_forum', - ), - 'settings' => array( + ], + 'settings' => [ 'label' => 'log_settings', 'permission' => 'admin_forum', - ), - ), - ), - 'repairboards' => array( + ], + ], + ], + 'repairboards' => [ 'label' => 'admin_repair', 'function' => __NAMESPACE__ . '\\RepairBoards::call', 'select' => 'maintain', 'hidden' => true, - ), - ), - ), - ); + ], + ], + ], + ]; /**************************** @@ -758,35 +757,34 @@ public function execute(): void // Actually create the menu! // Hook call disabled because we already called it in setAdminAreas() - $menu = new Menu($this->admin_areas, array( + $menu = new Menu($this->admin_areas, [ 'do_big_icons' => true, 'disable_hook_call' => true, - )); + ]); // Nothing valid? - if (empty($menu->include_data)) + if (empty($menu->include_data)) { ErrorHandler::fatalLang('no_access', false); + } // Build the link tree. - Utils::$context['linktree'][] = array( + Utils::$context['linktree'][] = [ 'url' => Config::$scripturl . '?action=admin', 'name' => Lang::$txt['admin_center'], - ); + ]; - if (isset($menu->current_area) && $menu->current_area != 'index') - { - Utils::$context['linktree'][] = array( + if (isset($menu->current_area) && $menu->current_area != 'index') { + Utils::$context['linktree'][] = [ 'url' => Config::$scripturl . '?action=admin;area=' . $menu->current_area . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'], 'name' => $menu->include_data['label'], - ); + ]; } - if (!empty($menu->current_subsection) && $menu->include_data['subsections'][$menu->current_subsection]['label'] != $menu->include_data['label']) - { - Utils::$context['linktree'][] = array( + if (!empty($menu->current_subsection) && $menu->include_data['subsections'][$menu->current_subsection]['label'] != $menu->include_data['label']) { + Utils::$context['linktree'][] = [ 'url' => Config::$scripturl . '?action=admin;area=' . $menu->current_area . ';sa=' . $menu->current_subsection . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'], 'name' => $menu->include_data['subsections'][$menu->current_subsection]['label'], - ); + ]; } // Make a note of the Unique ID for this menu. @@ -797,15 +795,17 @@ public function execute(): void Utils::$context['admin_area'] = $menu->current_area; // Now - finally - call the right place! - if (isset($menu->include_data['file'])) - require_once(Config::$sourcedir . '/' . $menu->include_data['file']); + if (isset($menu->include_data['file'])) { + require_once Config::$sourcedir . '/' . $menu->include_data['file']; + } // Get the right callable. $call = Utils::getCallable($menu->include_data['function']); // Is it valid? - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } /*********************** @@ -819,8 +819,9 @@ public function execute(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -844,92 +845,85 @@ public static function prepareDBSettingContext(&$config_vars): void { Lang::load('Help'); - if (isset($_SESSION['adm-save'])) - { - if ($_SESSION['adm-save'] === true) - { + if (isset($_SESSION['adm-save'])) { + if ($_SESSION['adm-save'] === true) { Utils::$context['saved_successful'] = true; - } - else - { + } else { Utils::$context['saved_failed'] = $_SESSION['adm-save']; } unset($_SESSION['adm-save']); } - Utils::$context['config_vars'] = array(); - $inlinePermissions = array(); - $bbcChoice = array(); + Utils::$context['config_vars'] = []; + $inlinePermissions = []; + $bbcChoice = []; $board_list = false; - foreach ($config_vars as $config_var) - { + foreach ($config_vars as $config_var) { // HR? - if (!is_array($config_var)) - { + if (!is_array($config_var)) { Utils::$context['config_vars'][] = $config_var; - } - else - { + } else { // If it has no name it doesn't have any purpose! - if (empty($config_var[1])) + if (empty($config_var[1])) { continue; + } // Special case for inline permissions - if ($config_var[0] == 'permissions' && User::$me->allowedTo('manage_permissions')) - { + if ($config_var[0] == 'permissions' && User::$me->allowedTo('manage_permissions')) { $inlinePermissions[] = $config_var[1]; - } - elseif ($config_var[0] == 'permissions') - { + } elseif ($config_var[0] == 'permissions') { continue; } - if ($config_var[0] == 'boards') + if ($config_var[0] == 'boards') { $board_list = true; + } // Are we showing the BBC selection box? - if ($config_var[0] == 'bbc') + if ($config_var[0] == 'bbc') { $bbcChoice[] = $config_var[1]; + } // We need to do some parsing of the value before we pass it in. - if (isset(Config::$modSettings[$config_var[1]])) - { - switch ($config_var[0]) - { + if (isset(Config::$modSettings[$config_var[1]])) { + switch ($config_var[0]) { case 'select': $value = Config::$modSettings[$config_var[1]]; + break; case 'json': $value = Utils::htmlspecialchars(Utils::jsonEncode(Config::$modSettings[$config_var[1]])); + break; case 'boards': $value = explode(',', Config::$modSettings[$config_var[1]]); + break; default: $value = Utils::htmlspecialchars(Config::$modSettings[$config_var[1]]); } - } - else - { + } else { // Darn, it's empty. What type is expected? - switch ($config_var[0]) - { + switch ($config_var[0]) { case 'int': case 'float': $value = 0; + break; case 'select': - $value = !empty($config_var['multiple']) ? Utils::jsonEncode(array()) : ''; + $value = !empty($config_var['multiple']) ? Utils::jsonEncode([]) : ''; + break; case 'boards': - $value = array(); + $value = []; + break; default: @@ -937,96 +931,77 @@ public static function prepareDBSettingContext(&$config_vars): void } } - Utils::$context['config_vars'][$config_var[1]] = array( - 'label' => isset($config_var['text_label']) ? $config_var['text_label'] : (isset(Lang::$txt[$config_var[1]]) ? Lang::$txt[$config_var[1]] : (isset($config_var[3]) && !is_array($config_var[3]) ? $config_var[3] : '')), + Utils::$context['config_vars'][$config_var[1]] = [ + 'label' => $config_var['text_label'] ?? (Lang::$txt[$config_var[1]] ?? (isset($config_var[3]) && !is_array($config_var[3]) ? $config_var[3] : '')), 'help' => isset(Lang::$helptxt[$config_var[1]]) ? $config_var[1] : '', 'type' => $config_var[0], - 'size' => !empty($config_var['size']) ? $config_var['size'] : (!empty($config_var[2]) && !is_array($config_var[2]) ? $config_var[2] : (in_array($config_var[0], array('int', 'float')) ? 6 : 0)), - 'data' => array(), + 'size' => !empty($config_var['size']) ? $config_var['size'] : (!empty($config_var[2]) && !is_array($config_var[2]) ? $config_var[2] : (in_array($config_var[0], ['int', 'float']) ? 6 : 0)), + 'data' => [], 'name' => $config_var[1], 'value' => $value, 'disabled' => false, 'invalid' => !empty($config_var['invalid']), 'javascript' => '', 'var_message' => !empty($config_var['message']) && isset(Lang::$txt[$config_var['message']]) ? Lang::$txt[$config_var['message']] : '', - 'preinput' => isset($config_var['preinput']) ? $config_var['preinput'] : '', - 'postinput' => isset($config_var['postinput']) ? $config_var['postinput'] : '', - ); + 'preinput' => $config_var['preinput'] ?? '', + 'postinput' => $config_var['postinput'] ?? '', + ]; // Handle min/max/step if necessary - if ($config_var[0] == 'int' || $config_var[0] == 'float') - { + if ($config_var[0] == 'int' || $config_var[0] == 'float') { // Default to a min of 0 if one isn't set - if (isset($config_var['min'])) - { + if (isset($config_var['min'])) { Utils::$context['config_vars'][$config_var[1]]['min'] = $config_var['min']; - } - else - { + } else { Utils::$context['config_vars'][$config_var[1]]['min'] = 0; } - if (isset($config_var['max'])) - { + if (isset($config_var['max'])) { Utils::$context['config_vars'][$config_var[1]]['max'] = $config_var['max']; } - if (isset($config_var['step'])) - { + if (isset($config_var['step'])) { Utils::$context['config_vars'][$config_var[1]]['step'] = $config_var['step']; } } // If this is a select box handle any data. - if (!empty($config_var[2]) && is_array($config_var[2])) - { + if (!empty($config_var[2]) && is_array($config_var[2])) { // If we allow multiple selections, we need to adjust a few things. - if ($config_var[0] == 'select' && !empty($config_var['multiple'])) - { + if ($config_var[0] == 'select' && !empty($config_var['multiple'])) { Utils::$context['config_vars'][$config_var[1]]['name'] .= '[]'; - Utils::$context['config_vars'][$config_var[1]]['value'] = !empty(Utils::$context['config_vars'][$config_var[1]]['value']) ? Utils::jsonDecode(Utils::$context['config_vars'][$config_var[1]]['value'], true) : array(); + Utils::$context['config_vars'][$config_var[1]]['value'] = !empty(Utils::$context['config_vars'][$config_var[1]]['value']) ? Utils::jsonDecode(Utils::$context['config_vars'][$config_var[1]]['value'], true) : []; } // If it's associative - if (isset($config_var[2][0]) && is_array($config_var[2][0])) - { + if (isset($config_var[2][0]) && is_array($config_var[2][0])) { Utils::$context['config_vars'][$config_var[1]]['data'] = $config_var[2]; - } - else - { - foreach ($config_var[2] as $key => $item) - Utils::$context['config_vars'][$config_var[1]]['data'][] = array($key, $item); + } else { + foreach ($config_var[2] as $key => $item) { + Utils::$context['config_vars'][$config_var[1]]['data'][] = [$key, $item]; + } } - if (empty($config_var['size']) && !empty($config_var['multiple'])) - { + if (empty($config_var['size']) && !empty($config_var['multiple'])) { Utils::$context['config_vars'][$config_var[1]]['size'] = max(4, count($config_var[2])); } } // Finally allow overrides - and some final cleanups. - foreach ($config_var as $k => $v) - { - if (!is_numeric($k)) - { - if (substr($k, 0, 2) == 'on') - { + foreach ($config_var as $k => $v) { + if (!is_numeric($k)) { + if (substr($k, 0, 2) == 'on') { Utils::$context['config_vars'][$config_var[1]]['javascript'] .= ' ' . $k . '="' . $v . '"'; - } - else - { + } else { Utils::$context['config_vars'][$config_var[1]][$k] = $v; } } // See if there are any other labels that might fit? - if (isset(Lang::$txt['setting_' . $config_var[1]])) - { + if (isset(Lang::$txt['setting_' . $config_var[1]])) { Utils::$context['config_vars'][$config_var[1]]['label'] = Lang::$txt['setting_' . $config_var[1]]; - } - elseif (isset(Lang::$txt['groups_' . $config_var[1]])) - { + } elseif (isset(Lang::$txt['groups_' . $config_var[1]])) { Utils::$context['config_vars'][$config_var[1]]['label'] = Lang::$txt['groups_' . $config_var[1]]; } } @@ -1035,8 +1010,7 @@ public static function prepareDBSettingContext(&$config_vars): void // @todo Temporary. Preventing divs inside label tags. $divPos = strpos(Utils::$context['config_vars'][$config_var[1]]['label'], ']*>~', '', substr(Utils::$context['config_vars'][$config_var[1]]['label'], $divPos)); Utils::$context['config_vars'][$config_var[1]]['label'] = substr(Utils::$context['config_vars'][$config_var[1]]['label'], 0, $divPos); @@ -1045,52 +1019,45 @@ public static function prepareDBSettingContext(&$config_vars): void } // If we have inline permissions we need to prep them. - if (!empty($inlinePermissions) && User::$me->allowedTo('manage_permissions')) - { + if (!empty($inlinePermissions) && User::$me->allowedTo('manage_permissions')) { Permissions::init_inline_permissions($inlinePermissions); } - if ($board_list) - { + if ($board_list) { Utils::$context['board_list'] = MessageIndex::getBoardList(); } // What about any BBC selection boxes? - if (!empty($bbcChoice)) - { + if (!empty($bbcChoice)) { // What are the options, eh? $temp = BBCodeParser::getCodes(); - $bbcTags = array(); + $bbcTags = []; - foreach ($temp as $tag) - { - if (!isset($tag['require_parents'])) + foreach ($temp as $tag) { + if (!isset($tag['require_parents'])) { $bbcTags[] = $tag['tag']; + } } $bbcTags = array_unique($bbcTags); // The number of columns we want to show the BBC tags in. - $numColumns = isset(Utils::$context['num_bbc_columns']) ? Utils::$context['num_bbc_columns'] : 3; + $numColumns = Utils::$context['num_bbc_columns'] ?? 3; // Now put whatever BBC options we may have into context too! - Utils::$context['bbc_sections'] = array(); + Utils::$context['bbc_sections'] = []; - foreach ($bbcChoice as $bbcSection) - { - Utils::$context['bbc_sections'][$bbcSection] = array( - 'title' => isset(Lang::$txt['bbc_title_' . $bbcSection]) ? Lang::$txt['bbc_title_' . $bbcSection] : Lang::$txt['enabled_bbc_select'], - 'disabled' => empty(Config::$modSettings['bbc_disabled_' . $bbcSection]) ? array() : Config::$modSettings['bbc_disabled_' . $bbcSection], + foreach ($bbcChoice as $bbcSection) { + Utils::$context['bbc_sections'][$bbcSection] = [ + 'title' => Lang::$txt['bbc_title_' . $bbcSection] ?? Lang::$txt['enabled_bbc_select'], + 'disabled' => empty(Config::$modSettings['bbc_disabled_' . $bbcSection]) ? [] : Config::$modSettings['bbc_disabled_' . $bbcSection], 'all_selected' => empty(Config::$modSettings['bbc_disabled_' . $bbcSection]), - 'columns' => array(), - ); + 'columns' => [], + ]; - if ($bbcSection == 'legacyBBC') - { + if ($bbcSection == 'legacyBBC') { $sectionTags = array_intersect(Utils::$context['legacy_bbc'], $bbcTags); - } - else - { + } else { $sectionTags = array_diff($bbcTags, Utils::$context['legacy_bbc']); } @@ -1100,22 +1067,22 @@ public static function prepareDBSettingContext(&$config_vars): void $col = 0; $i = 0; - foreach ($sectionTags as $tag) - { - if ($i % $tagsPerColumn == 0 && $i != 0) + foreach ($sectionTags as $tag) { + if ($i % $tagsPerColumn == 0 && $i != 0) { $col++; + } - Utils::$context['bbc_sections'][$bbcSection]['columns'][$col][] = array( + Utils::$context['bbc_sections'][$bbcSection]['columns'][$col][] = [ 'tag' => $tag, 'show_help' => isset(Lang::$helptxt['tag_' . $tag]), - ); + ]; $i++; } } } - IntegrationHook::call('integrate_prepare_db_settings', array(&$config_vars)); + IntegrationHook::call('integrate_prepare_db_settings', [&$config_vars]); SecurityToken::create('admin-dbsc'); } @@ -1133,25 +1100,19 @@ public static function saveSettings(&$config_vars): void SecurityToken::validate('admin-ssc'); // Fix the darn stupid cookiename! (more may not be allowed, but these for sure!) - if (isset($_POST['cookiename'])) - { - $_POST['cookiename'] = preg_replace('~[,;\s\.$]+~' . (Utils::$context['utf8'] ? 'u' : ''), '', $_POST['cookiename']); + if (isset($_POST['cookiename'])) { + $_POST['cookiename'] = preg_replace('~[,;\\s\\.$]+~' . (Utils::$context['utf8'] ? 'u' : ''), '', $_POST['cookiename']); } // Fix the forum's URL if necessary. - if (isset($_POST['boardurl'])) - { - if (substr($_POST['boardurl'], -10) == '/index.php') - { + if (isset($_POST['boardurl'])) { + if (substr($_POST['boardurl'], -10) == '/index.php') { $_POST['boardurl'] = substr($_POST['boardurl'], 0, -10); - } - elseif (substr($_POST['boardurl'], -1) == '/') - { + } elseif (substr($_POST['boardurl'], -1) == '/') { $_POST['boardurl'] = substr($_POST['boardurl'], 0, -1); } - if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://') - { + if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://') { $_POST['boardurl'] = 'http://' . $_POST['boardurl']; } @@ -1159,80 +1120,75 @@ public static function saveSettings(&$config_vars): void } // Any passwords? - $config_passwords = array(); + $config_passwords = []; // All the numeric variables. - $config_nums = array(); + $config_nums = []; // All the checkboxes - $config_bools = array(); + $config_bools = []; // Ones that accept multiple types (should be rare) - $config_multis = array(); + $config_multis = []; // Get all known setting definitions and assign them to our groups above. $settings_defs = Config::getSettingsDefs(); - foreach ($settings_defs as $var => $def) - { - if (!is_string($var)) + + foreach ($settings_defs as $var => $def) { + if (!is_string($var)) { continue; + } - if (!empty($def['is_password'])) - { + if (!empty($def['is_password'])) { $config_passwords[] = $var; - } - else - { + } else { // Special handling if multiple types are allowed. - if (is_array($def['type'])) - { + if (is_array($def['type'])) { // Obviously, we don't need null here. $def['type'] = array_filter( $def['type'], - function ($type) - { + function ($type) { return $type !== 'NULL'; - } + }, ); $type = count($def['type']) == 1 ? reset($def['type']) : 'multiple'; - } - else - { + } else { $type = $def['type']; } - switch ($type) - { + switch ($type) { case 'multiple': $config_multis[$var] = $def['type']; + // no break case 'double': $config_nums[] = $var; + break; case 'integer': // Some things saved as integers are presented as booleans - foreach ($config_vars as $config_var) - { - if (is_array($config_var) && $config_var[0] == $var) - { - if ($config_var[3] == 'check') - { + foreach ($config_vars as $config_var) { + if (is_array($config_var) && $config_var[0] == $var) { + if ($config_var[3] == 'check') { $config_bools[] = $var; + break 2; } - else - { - break; - } + + + break; + } } $config_nums[] = $var; + break; case 'boolean': $config_bools[] = $var; + break; default: @@ -1242,27 +1198,28 @@ function ($type) } // Now sort everything into a big array, and figure out arrays and etc. - $new_settings = array(); + $new_settings = []; + // Figure out which config vars we're saving here... - foreach ($config_vars as $config_var) - { - if (!is_array($config_var) || $config_var[2] != 'file') + foreach ($config_vars as $config_var) { + if (!is_array($config_var) || $config_var[2] != 'file') { continue; + } $var_name = $config_var[0]; // Unknown setting? - if (!isset($settings_defs[$var_name]) && isset($config_var[3])) - { - switch ($config_var[3]) - { + if (!isset($settings_defs[$var_name]) && isset($config_var[3])) { + switch ($config_var[3]) { case 'int': case 'float': $config_nums[] = $var_name; + break; case 'check': $config_bools[] = $var_name; + break; default: @@ -1270,41 +1227,35 @@ function ($type) } } - if (!in_array($var_name, $config_bools) && !isset($_POST[$var_name])) + if (!in_array($var_name, $config_bools) && !isset($_POST[$var_name])) { continue; + } - if (in_array($var_name, $config_passwords)) - { - if (isset($_POST[$var_name][1]) && $_POST[$var_name][0] == $_POST[$var_name][1]) + if (in_array($var_name, $config_passwords)) { + if (isset($_POST[$var_name][1]) && $_POST[$var_name][0] == $_POST[$var_name][1]) { $new_settings[$var_name] = $_POST[$var_name][0]; - } - elseif (in_array($var_name, $config_nums)) - { + } + } elseif (in_array($var_name, $config_nums)) { $new_settings[$var_name] = (int) $_POST[$var_name]; // If no min is specified, assume 0. This is done to avoid having to specify 'min => 0' for all settings where 0 is the min... - $min = isset($config_var['min']) ? $config_var['min'] : 0; + $min = $config_var['min'] ?? 0; $new_settings[$var_name] = max($min, $new_settings[$var_name]); // Is there a max value for this as well? - if (isset($config_var['max'])) + if (isset($config_var['max'])) { $new_settings[$var_name] = min($config_var['max'], $new_settings[$var_name]); - } - elseif (in_array($var_name, $config_bools)) - { + } + } elseif (in_array($var_name, $config_bools)) { $new_settings[$var_name] = !empty($_POST[$var_name]); - } - elseif (isset($config_multis[$var_name])) - { + } elseif (isset($config_multis[$var_name])) { $is_acceptable_type = false; - foreach ($config_multis[$var_name] as $type) - { + foreach ($config_multis[$var_name] as $type) { $temp = $_POST[$var_name]; settype($temp, $type); - if ($temp == $_POST[$var_name]) - { + if ($temp == $_POST[$var_name]) { $new_settings[$var_name] = $temp; $is_acceptable_type = true; @@ -1312,11 +1263,10 @@ function ($type) } } - if (!$is_acceptable_type) + if (!$is_acceptable_type) { ErrorHandler::fatal('Invalid config_var \'' . $var_name . '\''); - } - else - { + } + } else { $new_settings[$var_name] = $_POST[$var_name]; } } @@ -1325,33 +1275,38 @@ function ($type) Config::updateSettingsFile($new_settings); // Now loop through the remaining (database-based) settings. - $new_settings = array(); - foreach ($config_vars as $config_var) - { + $new_settings = []; + + foreach ($config_vars as $config_var) { // We just saved the file-based settings, so skip their definitions. - if (!is_array($config_var) || $config_var[2] == 'file') + if (!is_array($config_var) || $config_var[2] == 'file') { continue; + } - $new_setting = array($config_var[3], $config_var[0]); + $new_setting = [$config_var[3], $config_var[0]]; // Select options need carried over, too. - if (isset($config_var[4])) + if (isset($config_var[4])) { $new_setting[] = $config_var[4]; + } // Include min and max if necessary - if (isset($config_var['min'])) + if (isset($config_var['min'])) { $new_setting['min'] = $config_var['min']; + } - if (isset($config_var['max'])) + if (isset($config_var['max'])) { $new_setting['max'] = $config_var['max']; + } // Rewrite the definition a bit. $new_settings[] = $new_setting; } // Save the new database-based settings, if any. - if (!empty($new_settings)) + if (!empty($new_settings)) { ACP::saveDBSettings($new_settings); + } } /** @@ -1367,133 +1322,126 @@ public static function saveDBSettings(&$config_vars) SecurityToken::validate('admin-dbsc'); - $inlinePermissions = array(); + $inlinePermissions = []; - foreach ($config_vars as $var) - { - if (!isset($var[1]) || (!isset($_POST[$var[1]]) && $var[0] != 'check' && $var[0] != 'permissions' && $var[0] != 'boards' && ($var[0] != 'bbc' || !isset($_POST[$var[1] . '_enabledTags'])))) - { + foreach ($config_vars as $var) { + if (!isset($var[1]) || (!isset($_POST[$var[1]]) && $var[0] != 'check' && $var[0] != 'permissions' && $var[0] != 'boards' && ($var[0] != 'bbc' || !isset($_POST[$var[1] . '_enabledTags'])))) { continue; } // Checkboxes! - if ($var[0] == 'check') - { + if ($var[0] == 'check') { $setArray[$var[1]] = !empty($_POST[$var[1]]) ? '1' : '0'; } // Select boxes! - elseif ($var[0] == 'select' && in_array($_POST[$var[1]], array_keys($var[2]))) - { + elseif ($var[0] == 'select' && in_array($_POST[$var[1]], array_keys($var[2]))) { $setArray[$var[1]] = $_POST[$var[1]]; - } - elseif ($var[0] == 'select' && !empty($var['multiple']) && array_intersect($_POST[$var[1]], array_keys($var[2])) != array()) - { + } elseif ($var[0] == 'select' && !empty($var['multiple']) && array_intersect($_POST[$var[1]], array_keys($var[2])) != []) { // For security purposes we validate this line by line. - $lOptions = array(); + $lOptions = []; - foreach ($_POST[$var[1]] as $invar) - { - if (in_array($invar, array_keys($var[2]))) + foreach ($_POST[$var[1]] as $invar) { + if (in_array($invar, array_keys($var[2]))) { $lOptions[] = $invar; + } } $setArray[$var[1]] = Utils::jsonEncode($lOptions); } // List of boards! - elseif ($var[0] == 'boards') - { + elseif ($var[0] == 'boards') { // We just need a simple list of valid boards, nothing more. - if ($board_list === null) - { - $board_list = array(); - $request = Db::$db->query('', ' + if ($board_list === null) { + $board_list = []; + $request = Db::$db->query( + '', + ' SELECT id_board - FROM {db_prefix}boards' + FROM {db_prefix}boards', ); - while ($row = Db::$db->fetch_row($request)) - { + + while ($row = Db::$db->fetch_row($request)) { $board_list[$row[0]] = true; } Db::$db->free_result($request); } - $lOptions = array(); + $lOptions = []; - if (!empty($_POST[$var[1]])) - { - foreach ($_POST[$var[1]] as $invar => $dummy) - { - if (isset($board_list[$invar])) + if (!empty($_POST[$var[1]])) { + foreach ($_POST[$var[1]] as $invar => $dummy) { + if (isset($board_list[$invar])) { $lOptions[] = $invar; + } } } $setArray[$var[1]] = !empty($lOptions) ? implode(',', $lOptions) : ''; } // Integers! - elseif ($var[0] == 'int') - { + elseif ($var[0] == 'int') { $setArray[$var[1]] = (int) $_POST[$var[1]]; // If no min is specified, assume 0. This is done to avoid having to specify 'min => 0' for all settings where 0 is the min... - $min = isset($var['min']) ? $var['min'] : 0; + $min = $var['min'] ?? 0; $setArray[$var[1]] = max($min, $setArray[$var[1]]); // Do we have a max value for this as well? - if (isset($var['max'])) + if (isset($var['max'])) { $setArray[$var[1]] = min($var['max'], $setArray[$var[1]]); + } } // Floating point! - elseif ($var[0] == 'float') - { + elseif ($var[0] == 'float') { $setArray[$var[1]] = (float) $_POST[$var[1]]; // If no min is specified, assume 0. This is done to avoid having to specify 'min => 0' for all settings where 0 is the min... - $min = isset($var['min']) ? $var['min'] : 0; + $min = $var['min'] ?? 0; $setArray[$var[1]] = max($min, $setArray[$var[1]]); // Do we have a max value for this as well? - if (isset($var['max'])) + if (isset($var['max'])) { $setArray[$var[1]] = min($var['max'], $setArray[$var[1]]); + } } // Text! - elseif (in_array($var[0], array('text', 'large_text', 'color', 'date', 'datetime', 'datetime-local', 'email', 'month', 'time'))) - { + elseif (in_array($var[0], ['text', 'large_text', 'color', 'date', 'datetime', 'datetime-local', 'email', 'month', 'time'])) { $setArray[$var[1]] = $_POST[$var[1]]; } // Passwords! - elseif ($var[0] == 'password') - { - if (isset($_POST[$var[1]][1]) && $_POST[$var[1]][0] == $_POST[$var[1]][1]) + elseif ($var[0] == 'password') { + if (isset($_POST[$var[1]][1]) && $_POST[$var[1]][0] == $_POST[$var[1]][1]) { $setArray[$var[1]] = $_POST[$var[1]][0]; + } } // BBC. - elseif ($var[0] == 'bbc') - { - $bbcTags = array(); - foreach (BBCodeParser::getCodes() as $tag) + elseif ($var[0] == 'bbc') { + $bbcTags = []; + + foreach (BBCodeParser::getCodes() as $tag) { $bbcTags[] = $tag['tag']; + } - if (!isset($_POST[$var[1] . '_enabledTags'])) - $_POST[$var[1] . '_enabledTags'] = array(); - elseif (!is_array($_POST[$var[1] . '_enabledTags'])) - $_POST[$var[1] . '_enabledTags'] = array($_POST[$var[1] . '_enabledTags']); + if (!isset($_POST[$var[1] . '_enabledTags'])) { + $_POST[$var[1] . '_enabledTags'] = []; + } elseif (!is_array($_POST[$var[1] . '_enabledTags'])) { + $_POST[$var[1] . '_enabledTags'] = [$_POST[$var[1] . '_enabledTags']]; + } $setArray[$var[1]] = implode(',', array_diff($bbcTags, $_POST[$var[1] . '_enabledTags'])); } // Permissions? - elseif ($var[0] == 'permissions') - { + elseif ($var[0] == 'permissions') { $inlinePermissions[] = $var[1]; } } - if (!empty($setArray)) + if (!empty($setArray)) { Config::updateModSettings($setArray); + } // If we have inline permissions we need to save them. - if (!empty($inlinePermissions) && User::$me->allowedTo('manage_permissions')) - { + if (!empty($inlinePermissions) && User::$me->allowedTo('manage_permissions')) { Permissions::save_inline_permissions($inlinePermissions); } } @@ -1509,89 +1457,75 @@ public static function getServerVersions($checkFor) Lang::load('Admin'); Lang::load('ManageSettings'); - $versions = array(); + $versions = []; // Is GD available? If it is, we should show version information for it too. - if (in_array('gd', $checkFor) && function_exists('gd_info')) - { + if (in_array('gd', $checkFor) && function_exists('gd_info')) { $temp = gd_info(); - $versions['gd'] = array('title' => Lang::$txt['support_versions_gd'], 'version' => $temp['GD Version']); + $versions['gd'] = ['title' => Lang::$txt['support_versions_gd'], 'version' => $temp['GD Version']]; } // Why not have a look at ImageMagick? If it's installed, we should show version information for it too. - if (in_array('imagemagick', $checkFor) && (class_exists('Imagick') || function_exists('MagickGetVersionString'))) - { - if (class_exists('Imagick')) - { + if (in_array('imagemagick', $checkFor) && (class_exists('Imagick') || function_exists('MagickGetVersionString'))) { + if (class_exists('Imagick')) { $temp = new \Imagick(); $temp2 = $temp->getVersion(); $im_version = $temp2['versionString']; $extension_version = 'Imagick ' . phpversion('Imagick'); - } - else - { + } else { $im_version = MagickGetVersionString(); $extension_version = 'MagickWand ' . phpversion('MagickWand'); } // We already know it's ImageMagick and the website isn't needed... - $im_version = str_replace(array('ImageMagick ', ' https://www.imagemagick.org'), '', $im_version); + $im_version = str_replace(['ImageMagick ', ' https://www.imagemagick.org'], '', $im_version); - $versions['imagemagick'] = array('title' => Lang::$txt['support_versions_imagemagick'], 'version' => $im_version . ' (' . $extension_version . ')'); + $versions['imagemagick'] = ['title' => Lang::$txt['support_versions_imagemagick'], 'version' => $im_version . ' (' . $extension_version . ')']; } // Now lets check for the Database. - if (in_array('db_server', $checkFor)) - { - if (!isset(Db::$db_connection) || Db::$db_connection === false) - { + if (in_array('db_server', $checkFor)) { + if (!isset(Db::$db_connection) || Db::$db_connection === false) { Lang::load('Errors'); trigger_error(Lang::$txt['get_server_versions_no_database'], E_USER_NOTICE); - } - else - { - $versions['db_engine'] = array( + } else { + $versions['db_engine'] = [ 'title' => sprintf(Lang::$txt['support_versions_db_engine'], Db::$db->title), 'version' => Db::$db->get_vendor(), - ); + ]; - $versions['db_server'] = array( + $versions['db_server'] = [ 'title' => sprintf(Lang::$txt['support_versions_db'], Db::$db->title), 'version' => Db::$db->get_version(), - ); + ]; } } // Check to see if we have any accelerators installed. - foreach (CacheApi::detect() as $class_name => $cache_api) - { + foreach (CacheApi::detect() as $class_name => $cache_api) { $class_name_txt_key = strtolower($cache_api->getImplementationClassKeyName()); - if (in_array($class_name_txt_key, $checkFor)) - { - $versions[$class_name_txt_key] = array( - 'title' => isset(Lang::$txt[$class_name_txt_key . '_cache']) ? - Lang::$txt[$class_name_txt_key . '_cache'] : $class_name, + if (in_array($class_name_txt_key, $checkFor)) { + $versions[$class_name_txt_key] = [ + 'title' => Lang::$txt[$class_name_txt_key . '_cache'] ?? $class_name, 'version' => $cache_api->getVersion(), - ); + ]; } } - if (in_array('php', $checkFor)) - { - $versions['php'] = array( + if (in_array('php', $checkFor)) { + $versions['php'] = [ 'title' => 'PHP', 'version' => PHP_VERSION, 'more' => '?action=admin;area=serversettings;sa=phpinfo', - ); + ]; } - if (in_array('server', $checkFor)) - { - $versions['server'] = array( + if (in_array('server', $checkFor)) { + $versions['server'] = [ 'title' => Lang::$txt['support_versions_server'], 'version' => $_SERVER['SERVER_SOFTWARE'], - ); + ]; } return $versions; @@ -1614,67 +1548,62 @@ public static function getFileVersions(&$versionOptions) // Default place to find the languages would be the default theme dir. $lang_dir = Theme::$current->settings['default_theme_dir'] . '/languages'; - $version_info = array( - 'file_versions' => array(), - 'default_template_versions' => array(), - 'template_versions' => array(), - 'default_language_versions' => array(), - 'tasks_versions' => array(), - ); + $version_info = [ + 'file_versions' => [], + 'default_template_versions' => [], + 'template_versions' => [], + 'default_language_versions' => [], + 'tasks_versions' => [], + ]; // Find the version in SSI.php's file header. - if (!empty($versionOptions['include_ssi']) && file_exists(Config::$boarddir . '/SSI.php')) - { + if (!empty($versionOptions['include_ssi']) && file_exists(Config::$boarddir . '/SSI.php')) { $fp = fopen(Config::$boarddir . '/SSI.php', 'rb'); $header = fread($fp, 4096); fclose($fp); // The comment looks rougly like... that. - if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1) + if (preg_match('~\\*\\s@version\\s+(.+)[\\s]{2}~i', $header, $match) == 1) { $version_info['file_versions']['SSI.php'] = $match[1]; + } // Not found! This is bad. - else + else { $version_info['file_versions']['SSI.php'] = '??'; + } } // Do the paid subscriptions handler? - if (!empty($versionOptions['include_subscriptions']) && file_exists(Config::$boarddir . '/subscriptions.php')) - { + if (!empty($versionOptions['include_subscriptions']) && file_exists(Config::$boarddir . '/subscriptions.php')) { $fp = fopen(Config::$boarddir . '/subscriptions.php', 'rb'); $header = fread($fp, 4096); fclose($fp); // Found it? - if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1) - { + if (preg_match('~\\*\\s@version\\s+(.+)[\\s]{2}~i', $header, $match) == 1) { $version_info['file_versions']['subscriptions.php'] = $match[1]; } // If we haven't how do we all get paid? - else - { + else { $version_info['file_versions']['subscriptions.php'] = '??'; } } // Load all the files in the Sources directory, except this file and the redirect. $sources_dir = dir(Config::$sourcedir); - while ($entry = $sources_dir->read()) - { - if (substr($entry, -4) === '.php' && !is_dir(Config::$sourcedir . '/' . $entry) && $entry !== 'index.php') - { + + while ($entry = $sources_dir->read()) { + if (substr($entry, -4) === '.php' && !is_dir(Config::$sourcedir . '/' . $entry) && $entry !== 'index.php') { // Read the first 4k from the file.... enough for the header. $fp = fopen(Config::$sourcedir . '/' . $entry, 'rb'); $header = fread($fp, 4096); fclose($fp); // Look for the version comment in the file header. - if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1) - { + if (preg_match('~\\*\\s@version\\s+(.+)[\\s]{2}~i', $header, $match) == 1) { $version_info['file_versions'][$entry] = $match[1]; } // It wasn't found, but the file was... show a '??'. - else - { + else { $version_info['file_versions'][$entry] = '??'; } } @@ -1682,27 +1611,22 @@ public static function getFileVersions(&$versionOptions) $sources_dir->close(); // Load all the files in the tasks directory. - if (!empty($versionOptions['include_tasks'])) - { + if (!empty($versionOptions['include_tasks'])) { $tasks_dir = dir(Config::$tasksdir); - while ($entry = $tasks_dir->read()) - { - if (substr($entry, -4) === '.php' && !is_dir(Config::$tasksdir . '/' . $entry) && $entry !== 'index.php') - { + while ($entry = $tasks_dir->read()) { + if (substr($entry, -4) === '.php' && !is_dir(Config::$tasksdir . '/' . $entry) && $entry !== 'index.php') { // Read the first 4k from the file.... enough for the header. $fp = fopen(Config::$tasksdir . '/' . $entry, 'rb'); $header = fread($fp, 4096); fclose($fp); // Look for the version comment in the file header. - if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1) - { + if (preg_match('~\\*\\s@version\\s+(.+)[\\s]{2}~i', $header, $match) == 1) { $version_info['tasks_versions'][$entry] = $match[1]; } // It wasn't found, but the file was... show a '??'. - else - { + else { $version_info['tasks_versions'][$entry] = '??'; } } @@ -1711,34 +1635,28 @@ public static function getFileVersions(&$versionOptions) } // Load all the files in the default template directory - and the current theme if applicable. - $directories = array('default_template_versions' => Theme::$current->settings['default_theme_dir']); + $directories = ['default_template_versions' => Theme::$current->settings['default_theme_dir']]; - if (Theme::$current->settings['theme_id'] != 1) - { - $directories += array('template_versions' => Theme::$current->settings['theme_dir']); + if (Theme::$current->settings['theme_id'] != 1) { + $directories += ['template_versions' => Theme::$current->settings['theme_dir']]; } - foreach ($directories as $type => $dirname) - { + foreach ($directories as $type => $dirname) { $this_dir = dir($dirname); - while ($entry = $this_dir->read()) - { - if (substr($entry, -12) == 'template.php' && !is_dir($dirname . '/' . $entry)) - { + while ($entry = $this_dir->read()) { + if (substr($entry, -12) == 'template.php' && !is_dir($dirname . '/' . $entry)) { // Read the first 768 bytes from the file.... enough for the header. $fp = fopen($dirname . '/' . $entry, 'rb'); $header = fread($fp, 768); fclose($fp); // Look for the version comment in the file header. - if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1) - { + if (preg_match('~\\*\\s@version\\s+(.+)[\\s]{2}~i', $header, $match) == 1) { $version_info[$type][$entry] = $match[1]; } // It wasn't found, but the file was... show a '??'. - else - { + else { $version_info[$type][$entry] = '??'; } } @@ -1749,26 +1667,22 @@ public static function getFileVersions(&$versionOptions) // Load up all the files in the default language directory and sort by language. $this_dir = dir($lang_dir); - while ($entry = $this_dir->read()) - { - if (substr($entry, -4) == '.php' && $entry != 'index.php' && !is_dir($lang_dir . '/' . $entry)) - { + while ($entry = $this_dir->read()) { + if (substr($entry, -4) == '.php' && $entry != 'index.php' && !is_dir($lang_dir . '/' . $entry)) { // Read the first 768 bytes from the file.... enough for the header. $fp = fopen($lang_dir . '/' . $entry, 'rb'); $header = fread($fp, 768); fclose($fp); // Split the file name off into useful bits. - list ($name, $language) = explode('.', $entry); + list($name, $language) = explode('.', $entry); // Look for the version comment in the file header. - if (preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '(?:[\s]{2}|\*/)~i', $header, $match) == 1) - { + if (preg_match('~(?://|/\\*)\\s*Version:\\s+(.+?);\\s*' . preg_quote($name, '~') . '(?:[\\s]{2}|\\*/)~i', $header, $match) == 1) { $version_info['default_language_versions'][$language][$name] = $match[1]; } // It wasn't found, but the file was... show a '??'. - else - { + else { $version_info['default_language_versions'][$language][$name] = '??'; } } @@ -1777,8 +1691,7 @@ public static function getFileVersions(&$versionOptions) $this_dir->close(); // Sort the file versions by filename. - if (!empty($versionOptions['sort_results'])) - { + if (!empty($versionOptions['sort_results'])) { ksort($version_info['file_versions']); ksort($version_info['default_template_versions']); ksort($version_info['template_versions']); @@ -1786,8 +1699,9 @@ public static function getFileVersions(&$versionOptions) ksort($version_info['tasks_versions']); // For languages sort each language too. - foreach ($version_info['default_language_versions'] as $language => $dummy) + foreach ($version_info['default_language_versions'] as $language => $dummy) { ksort($version_info['default_language_versions'][$language]); + } } return $version_info; @@ -1799,29 +1713,33 @@ public static function getFileVersions(&$versionOptions) public static function updateAdminPreferences() { // This must exist! - if (!isset(Utils::$context['admin_preferences'])) + if (!isset(Utils::$context['admin_preferences'])) { return false; + } // This is what we'll be saving. Theme::$current->options['admin_preferences'] = Utils::jsonEncode(Utils::$context['admin_preferences']); // Just check we haven't ended up with something theme exclusive somehow. - Db::$db->query('', ' + Db::$db->query( + '', + ' DELETE FROM {db_prefix}themes WHERE id_theme != {int:default_theme} AND variable = {string:admin_preferences}', - array( + [ 'default_theme' => 1, 'admin_preferences' => 'admin_preferences', - ) + ], ); // Update the themes table. - Db::$db->insert('replace', + Db::$db->insert( + 'replace', '{db_prefix}themes', - array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'), - array(User::$me->id, 1, 'admin_preferences', Theme::$current->options['admin_preferences']), - array('id_member', 'id_theme', 'variable') + ['id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'], + [User::$me->id, 1, 'admin_preferences', Theme::$current->options['admin_preferences']], + ['id_member', 'id_theme', 'variable'], ); // Make sure we invalidate any cache. @@ -1838,7 +1756,7 @@ public static function updateAdminPreferences() * @param array $replacements An array of items to replace the variables in the template * @param array $additional_recipients An array of arrays of info for additional recipients. Should have 'id', 'email' and 'name' for each. */ - public static function emailAdmins($template, $replacements = array(), $additional_recipients = array()) + public static function emailAdmins($template, $replacements = [], $additional_recipients = []) { // Load all members which are effectively admins. $members = User::membersAllowedTo('admin_forum'); @@ -1846,20 +1764,23 @@ public static function emailAdmins($template, $replacements = array(), $addition // Load their alert preferences $prefs = Notify::getNotifyPrefs($members, 'announcements', true); - $emails_sent = array(); + $emails_sent = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_member, member_name, real_name, lngfile, email_address FROM {db_prefix}members WHERE id_member IN({array_int:members})', - array( + [ 'members' => $members, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { - if (empty($prefs[$row['id_member']]['announcements'])) + + while ($row = Db::$db->fetch_assoc($request)) { + if (empty($prefs[$row['id_member']]['announcements'])) { continue; + } // Stick their particulars in the replacement data. $replacements['IDMEMBER'] = $row['id_member']; @@ -1878,12 +1799,11 @@ public static function emailAdmins($template, $replacements = array(), $addition Db::$db->free_result($request); // Any additional users we must email this to? - if (!empty($additional_recipients)) - { - foreach ($additional_recipients as $recipient) - { - if (in_array($recipient['email'], $emails_sent)) + if (!empty($additional_recipients)) { + foreach ($additional_recipients as $recipient) { + if (in_array($recipient['email'], $emails_sent)) { continue; + } $replacements['IDMEMBER'] = $recipient['id']; $replacements['REALNAME'] = $recipient['name']; @@ -1912,20 +1832,22 @@ public static function adminLogin($type = 'admin') Theme::loadTemplate('Login'); // Validate what type of session check this is. - $types = array(); - IntegrationHook::call('integrate_validateSession', array(&$types)); + $types = []; + IntegrationHook::call('integrate_validateSession', [&$types]); $type = in_array($type, $types) || $type == 'moderate' ? $type : 'admin'; // They used a wrong password, log it and unset that. - if (isset($_POST[$type . '_hash_pass']) || isset($_POST[$type . '_pass'])) - { - Lang::$txt['security_wrong'] = sprintf(Lang::$txt['security_wrong'], isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : Lang::$txt['unknown'], $_SERVER['HTTP_USER_AGENT'], User::$me->ip); + if (isset($_POST[$type . '_hash_pass']) || isset($_POST[$type . '_pass'])) { + Lang::$txt['security_wrong'] = sprintf(Lang::$txt['security_wrong'], $_SERVER['HTTP_REFERER'] ?? Lang::$txt['unknown'], $_SERVER['HTTP_USER_AGENT'], User::$me->ip); ErrorHandler::log(Lang::$txt['security_wrong'], 'critical'); - if (isset($_POST[$type . '_hash_pass'])) + if (isset($_POST[$type . '_hash_pass'])) { unset($_POST[$type . '_hash_pass']); - if (isset($_POST[$type . '_pass'])) + } + + if (isset($_POST[$type . '_pass'])) { unset($_POST[$type . '_pass']); + } Utils::$context['incorrect_password'] = true; } @@ -1938,15 +1860,18 @@ public static function adminLogin($type = 'admin') // Now go through $_POST. Make sure the session hash is sent. $_POST[Utils::$context['session_var']] = Utils::$context['session_id']; - foreach ($_POST as $k => $v) + + foreach ($_POST as $k => $v) { Utils::$context['post_data'] .= self::adminLogin_outputPostVars($k, $v); + } // Now we'll use the admin_login sub template of the Login template. Utils::$context['sub_template'] = 'admin_login'; // And title the page something like "Login". - if (!isset(Utils::$context['page_title'])) + if (!isset(Utils::$context['page_title'])) { Utils::$context['page_title'] = Lang::$txt['login']; + } // The type of action. Utils::$context['sessionCheckType'] = $type; @@ -1969,8 +1894,8 @@ protected function __construct() // Load the language and templates.... Lang::load('Admin'); Theme::loadTemplate('Admin'); - Theme::loadJavaScriptFile('admin.js', array('minimize' => true), 'smf_admin'); - Theme::loadCSSFile('admin.css', array(), 'smf_admin'); + Theme::loadJavaScriptFile('admin.js', ['minimize' => true], 'smf_admin'); + Theme::loadCSSFile('admin.css', [], 'smf_admin'); // Set any dynamic values in $this->admin_areas. $this->setAdminAreas(); @@ -1979,23 +1904,22 @@ protected function __construct() Utils::$context['robot_no_index'] = true; // Some preferences. - Utils::$context['admin_preferences'] = !empty(Theme::$current->options['admin_preferences']) ? Utils::jsonDecode(Theme::$current->options['admin_preferences'], true) : array(); + Utils::$context['admin_preferences'] = !empty(Theme::$current->options['admin_preferences']) ? Utils::jsonDecode(Theme::$current->options['admin_preferences'], true) : []; // Any files to include for administration? - if (!empty(Config::$modSettings['integrate_admin_include'])) - { + if (!empty(Config::$modSettings['integrate_admin_include'])) { $admin_includes = explode(',', Config::$modSettings['integrate_admin_include']); - foreach ($admin_includes as $include) - { - $include = strtr(trim($include), array( + foreach ($admin_includes as $include) { + $include = strtr(trim($include), [ '$boarddir' => Config::$boarddir, '$sourcedir' => Config::$sourcedir, '$themedir' => Theme::$current->settings['theme_dir'], - )); + ]); - if (file_exists($include)) - require_once($include); + if (file_exists($include)) { + require_once $include; + } } } } @@ -2008,16 +1932,16 @@ protected function setAdminAreas(): void // Finalize various string values. array_walk_recursive( $this->admin_areas, - function(&$value, $key) - { - if (in_array($key, array('title', 'label'))) + function (&$value, $key) { + if (in_array($key, ['title', 'label'])) { $value = Lang::$txt[$value] ?? $value; + } - $value = strtr($value, array( + $value = strtr($value, [ '{scripturl}' => Config::$scripturl, '{boardurl}' => Config::$boardurl, - )); - } + ]); + }, ); // Fill in the ID number for the current theme URL. @@ -2026,10 +1950,9 @@ function(&$value, $key) // Figure out what is enabled or not. $this->admin_areas['forum']['areas']['adminlogoff']['enabled'] = empty(Config::$modSettings['securityDisable']); - if (empty(Config::$modSettings['cal_enabled'])) - { + if (empty(Config::$modSettings['cal_enabled'])) { $this->admin_areas['layout']['areas']['managecalendar']['inactive'] = true; - $this->admin_areas['layout']['areas']['managecalendar']['subsections'] = array(); + $this->admin_areas['layout']['areas']['managecalendar']['subsections'] = []; } $this->admin_areas['layout']['areas']['smileys']['subsections']['addsmiley']['enabled'] = !empty(Config::$modSettings['smiley_enable']); @@ -2037,18 +1960,16 @@ function(&$value, $key) $this->admin_areas['layout']['areas']['smileys']['subsections']['setorder']['enabled'] = !empty(Config::$modSettings['smiley_enable']); $this->admin_areas['layout']['areas']['smileys']['subsections']['editicons']['enabled'] = !empty(Config::$modSettings['messageIcons_enable']); - if (empty(Config::$modSettings['spider_mode'])) - { + if (empty(Config::$modSettings['spider_mode'])) { $this->admin_areas['layout']['areas']['sengines']['inactive'] = true; - $this->admin_areas['layout']['areas']['sengines']['subsections'] = array(); + $this->admin_areas['layout']['areas']['sengines']['subsections'] = []; } $this->admin_areas['members']['areas']['warnings']['inactive'] = Config::$modSettings['warning_settings'][0] == 0; - if (empty(Config::$modSettings['paid_enabled'])) - { + if (empty(Config::$modSettings['paid_enabled'])) { $this->admin_areas['members']['areas']['paidsubscribe']['inactive'] = true; - $this->admin_areas['members']['areas']['paidsubscribe']['subsections'] = array(); + $this->admin_areas['members']['areas']['paidsubscribe']['subsections'] = []; } $this->admin_areas['maintenance']['areas']['logs']['subsections']['errorlog']['enabled'] = !empty(Config::$modSettings['enableErrorLogging']); @@ -2057,7 +1978,7 @@ function(&$value, $key) $this->admin_areas['maintenance']['areas']['logs']['subsections']['spiderlog']['enabled'] = !empty(Config::$modSettings['spider_mode']); // Give mods access to the menu. - IntegrationHook::call('integrate_admin_areas', array(&$this->admin_areas)); + IntegrationHook::call('integrate_admin_areas', [&$this->admin_areas]); } /************************* @@ -2075,19 +1996,19 @@ function(&$value, $key) */ protected static function adminLogin_outputPostVars($k, $v) { - if (!is_array($v)) - { - return "\n" . ' '"', '<' => '<', '>' => '>')) . '">'; + if (!is_array($v)) { + return "\n" . ' '"', '<' => '<', '>' => '>']) . '">'; } - else - { - $ret = ''; - foreach ($v as $k2 => $v2) - $ret .= self::adminLogin_outputPostVars($k . '[' . $k2 . ']', $v2); - return $ret; + $ret = ''; + + foreach ($v as $k2 => $v2) { + $ret .= self::adminLogin_outputPostVars($k . '[' . $k2 . ']', $v2); } + + return $ret; + } /** @@ -2103,29 +2024,24 @@ protected static function construct_query_string($get) // Awww, darn. The Config::$scripturl contains GET stuff! $q = strpos(Config::$scripturl, '?'); - if ($q !== false) - { - parse_str(preg_replace('/&(\w+)(?=&|$)/', '&$1=', strtr(substr(Config::$scripturl, $q + 1), ';', '&')), $temp); + if ($q !== false) { + parse_str(preg_replace('/&(\\w+)(?=&|$)/', '&$1=', strtr(substr(Config::$scripturl, $q + 1), ';', '&')), $temp); - foreach ($get as $k => $v) - { + foreach ($get as $k => $v) { // Only if it's not already in the Config::$scripturl! - if (!isset($temp[$k])) - { + if (!isset($temp[$k])) { $query_string .= urlencode($k) . '=' . urlencode($v) . ';'; } // If it changed, put it out there, but with an ampersand. - elseif ($temp[$k] != $get[$k]) - { + elseif ($temp[$k] != $get[$k]) { $query_string .= urlencode($k) . '=' . urlencode($v) . '&'; } } - } - else - { + } else { // Add up all the data from $_GET into get_data. - foreach ($get as $k => $v) + foreach ($get as $k => $v) { $query_string .= urlencode($k) . '=' . urlencode($v) . ';'; + } } $query_string = substr($query_string, 0, -1); @@ -2136,7 +2052,8 @@ protected static function construct_query_string($get) } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\ACP::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\ACP::exportStatic')) { ACP::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/AntiSpam.php b/Sources/Actions/Admin/AntiSpam.php index c1dea35f8e..1840b92993 100644 --- a/Sources/Actions/Admin/AntiSpam.php +++ b/Sources/Actions/Admin/AntiSpam.php @@ -13,18 +13,17 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\BackwardCompatibility; +use SMF\Cache\CacheApi; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\IntegrationHook; use SMF\Lang; use SMF\Menu; use SMF\Theme; use SMF\User; use SMF\Utils; -use SMF\Cache\CacheApi; -use SMF\Db\DatabaseApi as Db; /** * Handles anti-spam settings. @@ -38,11 +37,11 @@ class AntiSpam implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'modifyAntispamSettings' => 'ModifyAntispamSettings', - ), - ); + ], + ]; /**************************** * Internal static properties @@ -75,40 +74,41 @@ public function execute(): void // Firstly, figure out what languages we're dealing with, and do a little processing for the form's benefit. Lang::get(); - Utils::$context['qa_languages'] = array(); + Utils::$context['qa_languages'] = []; - foreach (Utils::$context['languages'] as $lang_id => $lang) - { - $lang_id = strtr($lang_id, array('-utf8' => '')); - $lang['name'] = strtr($lang['name'], array('-utf8' => '')); + foreach (Utils::$context['languages'] as $lang_id => $lang) { + $lang_id = strtr($lang_id, ['-utf8' => '']); + $lang['name'] = strtr($lang['name'], ['-utf8' => '']); Utils::$context['qa_languages'][$lang_id] = $lang; } // Secondly, load any questions we currently have. - Utils::$context['question_answers'] = array(); + Utils::$context['question_answers'] = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_question, lngfile, question, answers - FROM {db_prefix}qanda' + FROM {db_prefix}qanda', ); - while ($row = Db::$db->fetch_assoc($request)) - { - $lang = strtr($row['lngfile'], array('-utf8' => '')); - Utils::$context['question_answers'][$row['id_question']] = array( + while ($row = Db::$db->fetch_assoc($request)) { + $lang = strtr($row['lngfile'], ['-utf8' => '']); + + Utils::$context['question_answers'][$row['id_question']] = [ 'lngfile' => $lang, 'question' => $row['question'], 'answers' => (array) Utils::jsonDecode($row['answers'], true), - ); + ]; Utils::$context['qa_by_lang'][$lang][] = $row['id_question']; } Db::$db->free_result($request); - if (empty(Utils::$context['qa_by_lang'][strtr(Lang::$default, array('-utf8' => ''))]) && !empty(Utils::$context['question_answers'])) - { - if (empty(Utils::$context['settings_insert_above'])) + if (empty(Utils::$context['qa_by_lang'][strtr(Lang::$default, ['-utf8' => ''])]) && !empty(Utils::$context['question_answers'])) { + if (empty(Utils::$context['settings_insert_above'])) { Utils::$context['settings_insert_above'] = ''; + } Utils::$context['settings_insert_above'] .= '
' . sprintf(Lang::$txt['question_not_defined'], Utils::$context['languages'][Lang::$default]['name']) . '
'; } @@ -116,94 +116,90 @@ public function execute(): void // Thirdly, push some JavaScript for the form to make it work. $nextrow = !empty(Utils::$context['question_answers']) ? max(array_keys(Utils::$context['question_answers'])) + 1 : 1; $setup_verification_add_answer = Utils::JavaScriptEscape(Lang::$txt['setup_verification_add_answer']); - $default_lang = strtr(Lang::$default, array('-utf8' => '')); + $default_lang = strtr(Lang::$default, ['-utf8' => '']); Theme::addInlineJavaScript(<<
').insertBefore($(this).parent()); - nextrow++; - }); - $(".qa_fieldset ").on("click", ".qa_add_answer a", function() { - var attr = $(this).closest("dd").find(".verification_answer:last").attr("name"); - $('').insertBefore($(this).closest("div")); - return false; - }); - $("#qa_dt_$default_lang a").click(); - END, true); + var nextrow = {$nextrow}; + $(".qa_link a").click(function() { + var id = $(this).parent().attr("id").substring(6); + $("#qa_fs_" + id).show(); + $(this).parent().hide(); + }); + $(".qa_fieldset legend a").click(function() { + var id = $(this).closest("fieldset").attr("id").substring(6); + $("#qa_dt_" + id).show(); + $(this).closest("fieldset").hide(); + }); + $(".qa_add_question a").click(function() { + var id = $(this).closest("fieldset").attr("id").substring(6); + $('
').insertBefore($(this).parent()); + nextrow++; + }); + $(".qa_fieldset ").on("click", ".qa_add_answer a", function() { + var attr = $(this).closest("dd").find(".verification_answer:last").attr("name"); + $('').insertBefore($(this).closest("div")); + return false; + }); + $("#qa_dt_{$default_lang} a").click(); + END, true); // Saving? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); // Fix PM settings. $_POST['pm_spam_settings'] = (int) $_POST['max_pm_recipients'] . ',' . (int) $_POST['pm_posts_verification'] . ',' . (int) $_POST['pm_posts_per_hour']; // Hack in guest requiring verification! - if (empty($_POST['posts_require_captcha']) && !empty($_POST['guests_require_captcha'])) + if (empty($_POST['posts_require_captcha']) && !empty($_POST['guests_require_captcha'])) { $_POST['posts_require_captcha'] = -1; + } $save_vars = $config_vars; unset($save_vars['pm1'], $save_vars['pm2'], $save_vars['pm3'], $save_vars['guest_verify']); - $save_vars[] = array('text', 'pm_spam_settings'); + $save_vars[] = ['text', 'pm_spam_settings']; // Handle verification questions. - $changes = array( - 'insert' => array(), - 'replace' => array(), - 'delete' => array(), - ); + $changes = [ + 'insert' => [], + 'replace' => [], + 'delete' => [], + ]; - $qs_per_lang = array(); + $qs_per_lang = []; - foreach (Utils::$context['qa_languages'] as $lang_id => $dummy) - { + foreach (Utils::$context['qa_languages'] as $lang_id => $dummy) { // If we had some questions for this language before, but don't now, delete everything from that language. - if ((!isset($_POST['question'][$lang_id]) || !is_array($_POST['question'][$lang_id])) && !empty(Utils::$context['qa_by_lang'][$lang_id])) - { + if ((!isset($_POST['question'][$lang_id]) || !is_array($_POST['question'][$lang_id])) && !empty(Utils::$context['qa_by_lang'][$lang_id])) { $changes['delete'] = array_merge($changes['delete'], Utils::$context['qa_by_lang'][$lang_id]); } // Now step through and see if any existing questions no longer exist. - if (!empty(Utils::$context['qa_by_lang'][$lang_id])) - { - foreach (Utils::$context['qa_by_lang'][$lang_id] as $q_id) - { - if (empty($_POST['question'][$lang_id][$q_id])) + if (!empty(Utils::$context['qa_by_lang'][$lang_id])) { + foreach (Utils::$context['qa_by_lang'][$lang_id] as $q_id) { + if (empty($_POST['question'][$lang_id][$q_id])) { $changes['delete'][] = $q_id; + } } } // Now let's see if there are new questions or ones that need updating. - if (isset($_POST['question'][$lang_id])) - { - foreach ($_POST['question'][$lang_id] as $q_id => $question) - { + if (isset($_POST['question'][$lang_id])) { + foreach ($_POST['question'][$lang_id] as $q_id => $question) { // Ignore junky ids. $q_id = (int) $q_id; - if ($q_id <= 0) + if ($q_id <= 0) { continue; + } // Check the question isn't empty (because they want to delete it?) - if (empty($question) || trim($question) == '') - { - if (isset(Utils::$context['question_answers'][$q_id])) + if (empty($question) || trim($question) == '') { + if (isset(Utils::$context['question_answers'][$q_id])) { $changes['delete'][] = $q_id; + } continue; } @@ -211,101 +207,103 @@ public function execute(): void $question = Utils::htmlspecialchars(trim($question)); // Get the answers. Firstly check there actually might be some. - if (!isset($_POST['answer'][$lang_id][$q_id]) || !is_array($_POST['answer'][$lang_id][$q_id])) - { - if (isset(Utils::$context['question_answers'][$q_id])) + if (!isset($_POST['answer'][$lang_id][$q_id]) || !is_array($_POST['answer'][$lang_id][$q_id])) { + if (isset(Utils::$context['question_answers'][$q_id])) { $changes['delete'][] = $q_id; + } continue; } // Now get them and check that they might be viable. - $answers = array(); + $answers = []; - foreach ($_POST['answer'][$lang_id][$q_id] as $answer) - { - if (!empty($answer) && trim($answer) !== '') + foreach ($_POST['answer'][$lang_id][$q_id] as $answer) { + if (!empty($answer) && trim($answer) !== '') { $answers[] = Utils::htmlspecialchars(trim($answer)); + } } - if (empty($answers)) - { - if (isset(Utils::$context['question_answers'][$q_id])) + if (empty($answers)) { + if (isset(Utils::$context['question_answers'][$q_id])) { $changes['delete'][] = $q_id; + } + continue; } $answers = Utils::jsonEncode($answers); // At this point we know we have a question and some answers. What are we doing with it? - if (!isset(Utils::$context['question_answers'][$q_id])) - { + if (!isset(Utils::$context['question_answers'][$q_id])) { // New question. Now, we don't want to randomly consume ids, so we'll set those, rather than trusting the browser's supplied ids. - $changes['insert'][] = array($lang_id, $question, $answers); - } - else - { + $changes['insert'][] = [$lang_id, $question, $answers]; + } else { // It's an existing question. Let's see what's changed, if anything. - if ($lang_id != Utils::$context['question_answers'][$q_id]['lngfile'] || $question != Utils::$context['question_answers'][$q_id]['question'] || $answers != Utils::$context['question_answers'][$q_id]['answers']) - $changes['replace'][$q_id] = array('lngfile' => $lang_id, 'question' => $question, 'answers' => $answers); + if ($lang_id != Utils::$context['question_answers'][$q_id]['lngfile'] || $question != Utils::$context['question_answers'][$q_id]['question'] || $answers != Utils::$context['question_answers'][$q_id]['answers']) { + $changes['replace'][$q_id] = ['lngfile' => $lang_id, 'question' => $question, 'answers' => $answers]; + } } - if (!isset($qs_per_lang[$lang_id])) + if (!isset($qs_per_lang[$lang_id])) { $qs_per_lang[$lang_id] = 0; + } $qs_per_lang[$lang_id]++; } } } // OK, so changes? - if (!empty($changes['delete'])) - { - Db::$db->query('', ' + if (!empty($changes['delete'])) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}qanda WHERE id_question IN ({array_int:questions})', - array( + [ 'questions' => $changes['delete'], - ) + ], ); } - if (!empty($changes['replace'])) - { - foreach ($changes['replace'] as $q_id => $question) - { - Db::$db->query('', ' + if (!empty($changes['replace'])) { + foreach ($changes['replace'] as $q_id => $question) { + Db::$db->query( + '', + ' UPDATE {db_prefix}qanda SET lngfile = {string:lngfile}, question = {string:question}, answers = {string:answers} WHERE id_question = {int:id_question}', - array( + [ 'id_question' => $q_id, 'lngfile' => $question['lngfile'], 'question' => $question['question'], 'answers' => $question['answers'], - ) + ], ); } } - if (!empty($changes['insert'])) - { - Db::$db->insert('insert', + if (!empty($changes['insert'])) { + Db::$db->insert( + 'insert', '{db_prefix}qanda', - array('lngfile' => 'string-50', 'question' => 'string-255', 'answers' => 'string-65534'), + ['lngfile' => 'string-50', 'question' => 'string-255', 'answers' => 'string-65534'], $changes['insert'], - array('id_question') + ['id_question'], ); } // Lastly, the count of messages needs to be no more than the lowest number of questions for any one language. $count_questions = empty($qs_per_lang) ? 0 : min($qs_per_lang); - if (empty($count_questions) || $_POST['qa_verification_number'] > $count_questions) + if (empty($count_questions) || $_POST['qa_verification_number'] > $count_questions) { $_POST['qa_verification_number'] = $count_questions; + } - IntegrationHook::call('integrate_save_spam_settings', array(&$save_vars)); + IntegrationHook::call('integrate_save_spam_settings', [&$save_vars]); // Now save. ACP::saveDBSettings($save_vars); @@ -316,16 +314,17 @@ public function execute(): void Utils::redirectexit('action=admin;area=antispam'); } - $character_range = array_merge(range('A', 'H'), array('K', 'M', 'N', 'P', 'R'), range('T', 'Y')); + $character_range = array_merge(range('A', 'H'), ['K', 'M', 'N', 'P', 'R'], range('T', 'Y')); $_SESSION['visual_verification_code'] = ''; - for ($i = 0; $i < 6; $i++) + for ($i = 0; $i < 6; $i++) { $_SESSION['visual_verification_code'] .= $character_range[array_rand($character_range)]; + } // Some javascript for CAPTCHA. Utils::$context['settings_post_javascript'] = ''; - if (Utils::$context['use_graphic_library']) - { + + if (Utils::$context['use_graphic_library']) { Utils::$context['settings_post_javascript'] .= ' function refreshImages() { @@ -335,12 +334,9 @@ function refreshImages() } // Show the image itself, or text saying we can't. - if (Utils::$context['use_graphic_library']) - { + if (Utils::$context['use_graphic_library']) { $config_vars['vv']['postinput'] = '
' . Lang::$txt['setting_image_verification_sample'] . '
'; - } - else - { + } else { $config_vars['vv']['postinput'] = '
' . Lang::$txt['setting_image_verification_nogd'] . ''; } @@ -352,8 +348,7 @@ function refreshImages() Config::$modSettings['posts_require_captcha'] = !isset(Config::$modSettings['posts_require_captcha']) || Config::$modSettings['posts_require_captcha'] == -1 ? 0 : Config::$modSettings['posts_require_captcha']; // Some minor javascript for the guest post setting. - if (Config::$modSettings['posts_require_captcha']) - { + if (Config::$modSettings['posts_require_captcha']) { Utils::$context['settings_post_javascript'] .= ' document.getElementById(\'guests_require_captcha\').disabled = true;'; } @@ -364,10 +359,10 @@ function refreshImages() Utils::$context['page_title'] = Lang::$txt['antispam_title']; Utils::$context['sub_template'] = 'show_settings'; - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['antispam_title'], 'description' => Lang::$txt['antispam_Settings_desc'], - ); + ]; ACP::prepareDBSettingContext($config_vars); } @@ -383,8 +378,9 @@ function refreshImages() */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -410,60 +406,60 @@ public static function getConfigVars(): array // Generate a sample registration image. Utils::$context['use_graphic_library'] = in_array('gd', get_loaded_extensions()); - $config_vars = array( - array('check', 'reg_verification'), - array('check', 'search_enable_captcha'), + $config_vars = [ + ['check', 'reg_verification'], + ['check', 'search_enable_captcha'], // This, my friend, is a cheat :p - 'guest_verify' => array( + 'guest_verify' => [ 'check', 'guests_require_captcha', - 'subtext' => Lang::$txt['setting_guests_require_captcha_desc'] - ), - array( + 'subtext' => Lang::$txt['setting_guests_require_captcha_desc'], + ], + [ 'int', 'posts_require_captcha', 'subtext' => Lang::$txt['posts_require_captcha_desc'], 'min' => -1, - 'onchange' => 'if (this.value > 0){ document.getElementById(\'guests_require_captcha\').checked = true; document.getElementById(\'guests_require_captcha\').disabled = true;} else {document.getElementById(\'guests_require_captcha\').disabled = false;}' - ), + 'onchange' => 'if (this.value > 0){ document.getElementById(\'guests_require_captcha\').checked = true; document.getElementById(\'guests_require_captcha\').disabled = true;} else {document.getElementById(\'guests_require_captcha\').disabled = false;}', + ], '', // PM Settings - 'pm1' => array('int', 'max_pm_recipients', 'subtext' => Lang::$txt['max_pm_recipients_note']), - 'pm2' => array('int', 'pm_posts_verification', 'subtext' => Lang::$txt['pm_posts_verification_note']), - 'pm3' => array('int', 'pm_posts_per_hour', 'subtext' => Lang::$txt['pm_posts_per_hour_note']), + 'pm1' => ['int', 'max_pm_recipients', 'subtext' => Lang::$txt['max_pm_recipients_note']], + 'pm2' => ['int', 'pm_posts_verification', 'subtext' => Lang::$txt['pm_posts_verification_note']], + 'pm3' => ['int', 'pm_posts_per_hour', 'subtext' => Lang::$txt['pm_posts_per_hour_note']], // Visual verification. - array('title', 'configure_verification_means'), - array('desc', 'configure_verification_means_desc'), - 'vv' => array( + ['title', 'configure_verification_means'], + ['desc', 'configure_verification_means_desc'], + 'vv' => [ 'select', 'visual_verification_type', - array( + [ Lang::$txt['setting_image_verification_off'], Lang::$txt['setting_image_verification_vsimple'], Lang::$txt['setting_image_verification_simple'], Lang::$txt['setting_image_verification_medium'], Lang::$txt['setting_image_verification_high'], - Lang::$txt['setting_image_verification_extreme'] - ), + Lang::$txt['setting_image_verification_extreme'], + ], 'subtext' => Lang::$txt['setting_visual_verification_type_desc'], - 'onchange' => Utils::$context['use_graphic_library'] ? 'refreshImages();' : '' - ), + 'onchange' => Utils::$context['use_graphic_library'] ? 'refreshImages();' : '', + ], // reCAPTCHA - array('title', 'recaptcha_configure'), - array('desc', 'recaptcha_configure_desc', 'class' => 'windowbg'), - array('check', 'recaptcha_enabled', 'subtext' => Lang::$txt['recaptcha_enable_desc']), - array('text', 'recaptcha_site_key', 'subtext' => Lang::$txt['recaptcha_site_key_desc']), - array('text', 'recaptcha_secret_key', 'subtext' => Lang::$txt['recaptcha_secret_key_desc']), - array('select', 'recaptcha_theme', array('light' => Lang::$txt['recaptcha_theme_light'], 'dark' => Lang::$txt['recaptcha_theme_dark'])), + ['title', 'recaptcha_configure'], + ['desc', 'recaptcha_configure_desc', 'class' => 'windowbg'], + ['check', 'recaptcha_enabled', 'subtext' => Lang::$txt['recaptcha_enable_desc']], + ['text', 'recaptcha_site_key', 'subtext' => Lang::$txt['recaptcha_site_key_desc']], + ['text', 'recaptcha_secret_key', 'subtext' => Lang::$txt['recaptcha_secret_key_desc']], + ['select', 'recaptcha_theme', ['light' => Lang::$txt['recaptcha_theme_light'], 'dark' => Lang::$txt['recaptcha_theme_dark']]], // Clever Thomas, who is looking sheepy now? Not I, the mighty sword swinger did say. - array('title', 'setup_verification_questions'), - array('desc', 'setup_verification_questions_desc'), - array('int', 'qa_verification_number', 'subtext' => Lang::$txt['setting_qa_verification_number_desc']), - array('callback', 'question_answer_list'), - ); + ['title', 'setup_verification_questions'], + ['desc', 'setup_verification_questions_desc'], + ['int', 'qa_verification_number', 'subtext' => Lang::$txt['setting_qa_verification_number_desc']], + ['callback', 'question_answer_list'], + ]; - IntegrationHook::call('integrate_spam_settings', array(&$config_vars)); + IntegrationHook::call('integrate_spam_settings', [&$config_vars]); return $config_vars; } @@ -476,8 +472,9 @@ public static function getConfigVars(): array */ public static function modifyAntispamSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::getConfigVars(); + } self::load(); self::$obj->execute(); @@ -492,12 +489,13 @@ public static function modifyAntispamSettings($return_config = false) */ protected function __construct() { - + } } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\AntiSpam::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\AntiSpam::exportStatic')) { AntiSpam::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Attachments.php b/Sources/Actions/Admin/Attachments.php index 3d2eaac53d..5f88ee1723 100644 --- a/Sources/Actions/Admin/Attachments.php +++ b/Sources/Actions/Admin/Attachments.php @@ -17,11 +17,11 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - use SMF\Attachment; +use SMF\BackwardCompatibility; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\IntegrationHook; use SMF\ItemList; use SMF\Lang; @@ -31,7 +31,6 @@ use SMF\Time; use SMF\User; use SMF\Utils; -use SMF\Db\DatabaseApi as Db; /** * Maintains and manages attachments and avatars. @@ -45,8 +44,8 @@ class Attachments implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'ManageAttachments', 'list_getFiles' => 'list_getFiles', 'list_getNumFiles' => 'list_getNumFiles', @@ -64,8 +63,8 @@ class Attachments implements ActionInterface 'repairAttachments' => 'RepairAttachments', 'manageAttachmentPaths' => 'ManageAttachmentPaths', 'transferAttachments' => 'TransferAttachments', - ), - ); + ], + ]; /******************* * Public properties @@ -88,7 +87,7 @@ class Attachments implements ActionInterface * * Available sub-actions. */ - public static array $subactions = array( + public static array $subactions = [ 'attachments' => 'attachmentSettings', 'avatars' => 'avatarSettings', 'browse' => 'browse', @@ -100,7 +99,7 @@ class Attachments implements ActionInterface 'repair' => 'repair', 'attachpaths' => 'paths', 'transfer' => 'transfer', - ); + ]; /**************************** * Internal static properties @@ -123,10 +122,11 @@ class Attachments implements ActionInterface */ public function execute(): void { - $call = method_exists($this, self::$subactions[$this->subaction]) ? array($this, self::$subactions[$this->subaction]) : Utils::getCallable(self::$subactions[$this->subaction]); + $call = method_exists($this, self::$subactions[$this->subaction]) ? [$this, self::$subactions[$this->subaction]] : Utils::getCallable(self::$subactions[$this->subaction]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } /** @@ -153,68 +153,58 @@ public function attachmentSettings(): void toggleSubDir();'; // Saving settings? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); - if (isset($_POST['attachmentUploadDir'])) + if (isset($_POST['attachmentUploadDir'])) { unset($_POST['attachmentUploadDir']); + } - if (!empty($_POST['use_subdirectories_for_attachments'])) - { + if (!empty($_POST['use_subdirectories_for_attachments'])) { if ( isset($_POST['use_subdirectories_for_attachments']) && empty($_POST['basedirectory_for_attachments']) - ) - { + ) { $_POST['basedirectory_for_attachments'] = (!empty(Config::$modSettings['basedirectory_for_attachments']) ? (Config::$modSettings['basedirectory_for_attachments']) : Config::$boarddir); } if ( !empty($_POST['use_subdirectories_for_attachments']) && !empty(Config::$modSettings['attachment_basedirectories']) - ) - { - if (!is_array(Config::$modSettings['attachment_basedirectories'])) - { + ) { + if (!is_array(Config::$modSettings['attachment_basedirectories'])) { Config::$modSettings['attachment_basedirectories'] = Utils::jsonDecode(Config::$modSettings['attachment_basedirectories'], true); } - } - else - { - Config::$modSettings['attachment_basedirectories'] = array(); + } else { + Config::$modSettings['attachment_basedirectories'] = []; } if ( !empty($_POST['use_subdirectories_for_attachments']) && !empty($_POST['basedirectory_for_attachments']) && !in_array($_POST['basedirectory_for_attachments'], Config::$modSettings['attachment_basedirectories']) - ) - { + ) { $currentAttachmentUploadDir = Config::$modSettings['currentAttachmentUploadDir']; - if (!in_array($_POST['basedirectory_for_attachments'], Config::$modSettings['attachmentUploadDir'])) - { - if (!Attachment::automanageCreateDirectory($_POST['basedirectory_for_attachments'])) - { + if (!in_array($_POST['basedirectory_for_attachments'], Config::$modSettings['attachmentUploadDir'])) { + if (!Attachment::automanageCreateDirectory($_POST['basedirectory_for_attachments'])) { $_POST['basedirectory_for_attachments'] = Config::$modSettings['basedirectory_for_attachments']; } } - if (!in_array($_POST['basedirectory_for_attachments'], Config::$modSettings['attachment_basedirectories'])) - { + if (!in_array($_POST['basedirectory_for_attachments'], Config::$modSettings['attachment_basedirectories'])) { Config::$modSettings['attachment_basedirectories'][Config::$modSettings['currentAttachmentUploadDir']] = $_POST['basedirectory_for_attachments']; - Config::updateModSettings(array( + Config::updateModSettings([ 'attachment_basedirectories' => Utils::jsonEncode( - Config::$modSettings['attachment_basedirectories'] + Config::$modSettings['attachment_basedirectories'], ), 'currentAttachmentUploadDir' => $currentAttachmentUploadDir, - )); + ]); $_POST['use_subdirectories_for_attachments'] = 1; $_POST['attachmentUploadDir'] = Utils::jsonEncode( - Config::$modSettings['attachmentUploadDir'] + Config::$modSettings['attachmentUploadDir'], ); } } @@ -245,22 +235,25 @@ public function avatarSettings(): void $config_vars = self::avatarConfigVars(); // Saving avatar settings? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); // These settings cannot be left empty! - if (empty($_POST['custom_avatar_dir'])) + if (empty($_POST['custom_avatar_dir'])) { $_POST['custom_avatar_dir'] = Config::$boarddir . '/custom_avatar'; + } - if (empty($_POST['custom_avatar_url'])) + if (empty($_POST['custom_avatar_url'])) { $_POST['custom_avatar_url'] = Config::$boardurl . '/custom_avatar'; + } - if (empty($_POST['avatar_directory'])) + if (empty($_POST['avatar_directory'])) { $_POST['avatar_directory'] = Config::$boarddir . '/avatars'; + } - if (empty($_POST['avatar_url'])) + if (empty($_POST['avatar_url'])) { $_POST['avatar_url'] = Config::$boardurl . '/avatars'; + } IntegrationHook::call('integrate_save_avatar_settings'); @@ -297,204 +290,190 @@ public function browse(): void Utils::$context['browse_type'] = isset($_REQUEST['avatars']) ? 'avatars' : (isset($_REQUEST['thumbs']) ? 'thumbs' : 'attachments'); // Set the options for the list component. - $listOptions = array( + $listOptions = [ 'id' => 'file_list', 'items_per_page' => Config::$modSettings['defaultMaxListItems'], 'base_href' => Config::$scripturl . '?action=admin;area=manageattachments;sa=browse' . (Utils::$context['browse_type'] === 'avatars' ? ';avatars' : (Utils::$context['browse_type'] === 'thumbs' ? ';thumbs' : '')), 'default_sort_col' => 'name', 'no_items_label' => Lang::$txt['attachment_manager_' . (Utils::$context['browse_type'] === 'avatars' ? 'avatars' : (Utils::$context['browse_type'] === 'thumbs' ? 'thumbs' : 'attachments')) . '_no_entries'], - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getFiles', - 'params' => array( + 'params' => [ Utils::$context['browse_type'], - ), - ), - 'get_count' => array( + ], + ], + 'get_count' => [ 'function' => __CLASS__ . '::list_getNumFiles', - 'params' => array( + 'params' => [ Utils::$context['browse_type'], - ), - ), - 'columns' => array( - 'name' => array( - 'header' => array( + ], + ], + 'columns' => [ + 'name' => [ + 'header' => [ 'value' => Lang::$txt['attachment_name'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { $link = '%1$s', preg_replace('~&#(\\\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\\\1;', Utils::htmlspecialchars($rowData['filename']))); // Show the dimensions. - if (!empty($rowData['width']) && !empty($rowData['height'])) - { + if (!empty($rowData['width']) && !empty($rowData['height'])) { $link .= sprintf(' %1$dx%2$d', $rowData['width'], $rowData['height']); } return $link; }, - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'a.filename', 'reverse' => 'a.filename DESC', - ), - ), - 'filesize' => array( - 'header' => array( + ], + ], + 'filesize' => [ + 'header' => [ 'value' => Lang::$txt['attachment_file_size'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return sprintf('%1$s%2$s', round($rowData['size'] / 1024, 2), Lang::$txt['kilobyte']); }, - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'a.size', 'reverse' => 'a.size DESC', - ), - ), - 'member' => array( - 'header' => array( + ], + ], + 'member' => [ + 'header' => [ 'value' => Utils::$context['browse_type'] == 'avatars' ? Lang::$txt['attachment_manager_member'] : Lang::$txt['posted_by'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { // In case of an attachment, return the poster of the attachment. - if (empty($rowData['id_member'])) - { + if (empty($rowData['id_member'])) { return Utils::htmlspecialchars($rowData['poster_name']); } // Otherwise it must be an avatar, return the link to the owner of it. return sprintf('%3$s', Config::$scripturl, $rowData['id_member'], $rowData['poster_name']); }, - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'mem.real_name', 'reverse' => 'mem.real_name DESC', - ), - ), - 'date' => array( - 'header' => array( + ], + ], + 'date' => [ + 'header' => [ 'value' => Utils::$context['browse_type'] == 'avatars' ? Lang::$txt['attachment_manager_last_active'] : Lang::$txt['date'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { // The date the message containing the attachment was posted or the owner of the avatar was active. $date = empty($rowData['poster_time']) ? Lang::$txt['never'] : Time::create('@' . $rowData['poster_time'])->format(null, true); // Add a link to the topic in case of an attachment. - if (Utils::$context['browse_type'] !== 'avatars') - { + if (Utils::$context['browse_type'] !== 'avatars') { $date .= sprintf('
%1$s %5$s', Lang::$txt['in'], Config::$scripturl, $rowData['id_topic'], $rowData['id_msg'], $rowData['subject']); } return $date; }, - ), - 'sort' => array( + ], + 'sort' => [ 'default' => Utils::$context['browse_type'] === 'avatars' ? 'mem.last_login' : 'm.id_msg', 'reverse' => Utils::$context['browse_type'] === 'avatars' ? 'mem.last_login DESC' : 'm.id_msg DESC', - ), - ), - 'downloads' => array( - 'header' => array( + ], + ], + 'downloads' => [ + 'header' => [ 'value' => Lang::$txt['downloads'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'downloads', 'comma_format' => true, - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'a.downloads', 'reverse' => 'a.downloads DESC', - ), - ), - 'check' => array( - 'header' => array( + ], + ], + 'check' => [ + 'header' => [ 'value' => '', 'class' => 'centercol', - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '', - 'params' => array( + 'params' => [ 'id_attach' => false, - ), - ), + ], + ], 'class' => 'centercol', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=manageattachments;sa=remove' . (Utils::$context['browse_type'] === 'avatars' ? ';avatars' : (Utils::$context['browse_type'] === 'thumbs' ? ';thumbs' : '')), 'include_sort' => true, 'include_start' => true, - 'hidden_fields' => array( + 'hidden_fields' => [ 'type' => Utils::$context['browse_type'], - ), - ), - 'additional_rows' => array( - array( + ], + ], + 'additional_rows' => [ + [ 'position' => 'above_column_headers', 'value' => '', - ), - array( + ], + [ 'position' => 'below_table_data', 'value' => '', - ), - ), - ); + ], + ], + ]; - $titles = array( - 'attachments' => array('?action=admin;area=manageattachments;sa=browse', Lang::$txt['attachment_manager_attachments']), - 'avatars' => array('?action=admin;area=manageattachments;sa=browse;avatars', Lang::$txt['attachment_manager_avatars']), - 'thumbs' => array('?action=admin;area=manageattachments;sa=browse;thumbs', Lang::$txt['attachment_manager_thumbs']), - ); + $titles = [ + 'attachments' => ['?action=admin;area=manageattachments;sa=browse', Lang::$txt['attachment_manager_attachments']], + 'avatars' => ['?action=admin;area=manageattachments;sa=browse;avatars', Lang::$txt['attachment_manager_avatars']], + 'thumbs' => ['?action=admin;area=manageattachments;sa=browse;thumbs', Lang::$txt['attachment_manager_thumbs']], + ]; $list_title = Lang::$txt['attachment_manager_browse_files'] . ': '; // Does a hook want to display their attachments better? - IntegrationHook::call('integrate_attachments_browse', array(&$listOptions, &$titles)); + IntegrationHook::call('integrate_attachments_browse', [&$listOptions, &$titles]); - foreach ($titles as $browse_type => $details) - { - if ($browse_type != 'attachments') - { + foreach ($titles as $browse_type => $details) { + if ($browse_type != 'attachments') { $list_title .= ' | '; } - if (Utils::$context['browse_type'] == $browse_type) - { + if (Utils::$context['browse_type'] == $browse_type) { $list_title .= '> '; } @@ -525,73 +504,79 @@ public function maintain(): void $attach_dirs = Config::$modSettings['attachmentUploadDir']; // Get the number of attachments.... - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}attachments WHERE attachment_type = {int:attachment_type} AND id_member = {int:guest_id_member}', - array( + [ 'attachment_type' => 0, 'guest_id_member' => 0, - ) + ], ); - list (Utils::$context['num_attachments']) = Db::$db->fetch_row($request); + list(Utils::$context['num_attachments']) = Db::$db->fetch_row($request); Db::$db->free_result($request); Utils::$context['num_attachments'] = Lang::numberFormat(Utils::$context['num_attachments'], 0); // Also get the avatar amount.... - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}attachments WHERE id_member != {int:guest_id_member}', - array( + [ 'guest_id_member' => 0, - ) + ], ); - list (Utils::$context['num_avatars']) = Db::$db->fetch_row($request); + list(Utils::$context['num_avatars']) = Db::$db->fetch_row($request); Db::$db->free_result($request); Utils::$context['num_avatars'] = Lang::numberFormat(Utils::$context['num_avatars'], 0); // Check the size of all the directories. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT SUM(size) FROM {db_prefix}attachments WHERE attachment_type != {int:type}', - array( + [ 'type' => 1, - ) + ], ); - list ($attachmentDirSize) = Db::$db->fetch_row($request); + list($attachmentDirSize) = Db::$db->fetch_row($request); Db::$db->free_result($request); // Divide it into kilobytes. $attachmentDirSize /= 1024; Utils::$context['attachment_total_size'] = Lang::numberFormat($attachmentDirSize, 2); - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*), SUM(size) FROM {db_prefix}attachments WHERE id_folder = {int:folder_id} AND attachment_type != {int:type}', - array( + [ 'folder_id' => Config::$modSettings['currentAttachmentUploadDir'], 'type' => 1, - ) + ], ); - list ($current_dir_files, $current_dir_size) = Db::$db->fetch_row($request); + list($current_dir_files, $current_dir_size) = Db::$db->fetch_row($request); Db::$db->free_result($request); $current_dir_size /= 1024; // If they specified a limit only.... - if (!empty(Config::$modSettings['attachmentDirSizeLimit'])) - { + if (!empty(Config::$modSettings['attachmentDirSizeLimit'])) { Utils::$context['attachment_space'] = Lang::numberFormat(max(Config::$modSettings['attachmentDirSizeLimit'] - $current_dir_size, 0), 2); } Utils::$context['attachment_current_size'] = Lang::numberFormat($current_dir_size, 2); - if (!empty(Config::$modSettings['attachmentDirFileLimit'])) - { + if (!empty(Config::$modSettings['attachmentDirFileLimit'])) { Utils::$context['attachment_files'] = Lang::numberFormat(max(Config::$modSettings['attachmentDirFileLimit'] - $current_dir_files, 0), 0); } @@ -601,12 +586,11 @@ public function maintain(): void Utils::$context['attach_dirs'] = $attach_dirs; - Utils::$context['base_dirs'] = !empty(Config::$modSettings['attachment_basedirectories']) ? Utils::jsonDecode(Config::$modSettings['attachment_basedirectories'], true) : array(); + Utils::$context['base_dirs'] = !empty(Config::$modSettings['attachment_basedirectories']) ? Utils::jsonDecode(Config::$modSettings['attachment_basedirectories'], true) : []; - Utils::$context['checked'] = isset($_SESSION['checked']) ? $_SESSION['checked'] : true; + Utils::$context['checked'] = $_SESSION['checked'] ?? true; - if (!empty($_SESSION['results'])) - { + if (!empty($_SESSION['results'])) { Utils::$context['results'] = implode('
', $_SESSION['results']); unset($_SESSION['results']); } @@ -621,40 +605,38 @@ public function remove(): void { User::$me->checkSession(); - if (!empty($_POST['remove'])) - { - $attachments = array(); + if (!empty($_POST['remove'])) { + $attachments = []; // There must be a quicker way to pass this safety test?? - foreach ($_POST['remove'] as $removeID => $dummy) + foreach ($_POST['remove'] as $removeID => $dummy) { $attachments[] = (int) $removeID; + } // If the attachments are from a 3rd party, let them remove it. Hooks should remove their ids from the array. $filesRemoved = false; - IntegrationHook::call('integrate_attachment_remove', array(&$filesRemoved, $attachments)); + IntegrationHook::call('integrate_attachment_remove', [&$filesRemoved, $attachments]); - if ($_REQUEST['type'] == 'avatars' && !empty($attachments)) - { - Attachment::remove(array('id_attach' => $attachments)); - } - elseif (!empty($attachments)) - { - $messages = Attachment::remove(array('id_attach' => $attachments), 'messages', true); + if ($_REQUEST['type'] == 'avatars' && !empty($attachments)) { + Attachment::remove(['id_attach' => $attachments]); + } elseif (!empty($attachments)) { + $messages = Attachment::remove(['id_attach' => $attachments], 'messages', true); // And change the message to reflect this. - if (!empty($messages)) - { + if (!empty($messages)) { Lang::load('index', Lang::$default, true); - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}messages SET body = CONCAT(body, {string:deleted_message}) WHERE id_msg IN ({array_int:messages_affected})', - array( + [ 'messages_affected' => $messages, 'deleted_message' => '

' . Lang::$txt['attachment_delete_admin'], - ) + ], ); Lang::load('index', User::$me->language, true); @@ -662,7 +644,7 @@ public function remove(): void } } - $_GET['sort'] = isset($_GET['sort']) ? $_GET['sort'] : 'date'; + $_GET['sort'] = $_GET['sort'] ?? 'date'; Utils::redirectexit('action=admin;area=manageattachments;sa=browse;' . $_REQUEST['type'] . ';sort=' . $_GET['sort'] . (isset($_GET['desc']) ? ';desc' : '') . ';start=' . $_REQUEST['start']); } @@ -681,29 +663,27 @@ public function removeByAge(): void // @todo Ignore messages in topics that are stickied? // Deleting an attachment? - if ($_REQUEST['type'] != 'avatars') - { + if ($_REQUEST['type'] != 'avatars') { // Get rid of all the old attachments. - $messages = Attachment::remove(array('attachment_type' => 0, 'poster_time' => (time() - 24 * 60 * 60 * $_POST['age'])), 'messages', true); + $messages = Attachment::remove(['attachment_type' => 0, 'poster_time' => (time() - 24 * 60 * 60 * $_POST['age'])], 'messages', true); // Update the messages to reflect the change. - if (!empty($messages) && !empty($_POST['notice'])) - { - Db::$db->query('', ' + if (!empty($messages) && !empty($_POST['notice'])) { + Db::$db->query( + '', + ' UPDATE {db_prefix}messages SET body = CONCAT(body, {string:notice}) WHERE id_msg IN ({array_int:messages})', - array( + [ 'messages' => $messages, 'notice' => '

' . $_POST['notice'], - ) + ], ); } - } - else - { + } else { // Remove all the old avatars. - Attachment::remove(array('not_id_member' => 0, 'last_login' => (time() - 24 * 60 * 60 * $_POST['age'])), 'members'); + Attachment::remove(['not_id_member' => 0, 'last_login' => (time() - 24 * 60 * 60 * $_POST['age'])], 'members'); } Utils::redirectexit('action=admin;area=manageattachments' . (empty($_REQUEST['avatars']) ? ';sa=maintenance' : ';avatars')); @@ -721,19 +701,20 @@ public function removeBySize(): void User::$me->checkSession('post', 'admin'); // Find humungous attachments. - $messages = Attachment::remove(array('attachment_type' => 0, 'size' => 1024 * $_POST['size']), 'messages', true); + $messages = Attachment::remove(['attachment_type' => 0, 'size' => 1024 * $_POST['size']], 'messages', true); // And make a note on the post. - if (!empty($messages) && !empty($_POST['notice'])) - { - Db::$db->query('', ' + if (!empty($messages) && !empty($_POST['notice'])) { + Db::$db->query( + '', + ' UPDATE {db_prefix}messages SET body = CONCAT(body, {string:notice}) WHERE id_msg IN ({array_int:messages})', - array( + [ 'messages' => $messages, 'notice' => '

' . $_POST['notice'], - ) + ], ); } @@ -749,22 +730,24 @@ public function removeAll(): void { User::$me->checkSession('get', 'admin'); - $messages = Attachment::remove(array('attachment_type' => 0), '', true); + $messages = Attachment::remove(['attachment_type' => 0], '', true); - if (!isset($_POST['notice'])) + if (!isset($_POST['notice'])) { $_POST['notice'] = Lang::$txt['attachment_delete_admin']; + } // Add the notice on the end of the changed messages. - if (!empty($messages)) - { - Db::$db->query('', ' + if (!empty($messages)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}messages SET body = CONCAT(body, {string:deleted_message}) WHERE id_msg IN ({array_int:messages})', - array( + [ 'messages' => $messages, 'deleted_message' => '

' . $_POST['notice'], - ) + ], ); } @@ -779,8 +762,9 @@ public function repair(): void User::$me->checkSession('get'); // If we choose cancel, redirect right back. - if (isset($_POST['cancel'])) + if (isset($_POST['cancel'])) { Utils::redirectexit('action=admin;area=manageattachments;sa=maintenance'); + } // Try give us a while to sort this out... @set_time_limit(600); @@ -790,27 +774,27 @@ public function repair(): void Utils::$context['starting_substep'] = $_GET['substep'] = empty($_GET['substep']) ? 0 : (int) $_GET['substep']; // Don't recall the session just in case. - if ($_GET['step'] == 0 && $_GET['substep'] == 0) - { + if ($_GET['step'] == 0 && $_GET['substep'] == 0) { unset($_SESSION['attachments_to_fix'], $_SESSION['attachments_to_fix2']); // If we're actually fixing stuff - work out what. - if (isset($_GET['fixErrors'])) - { + if (isset($_GET['fixErrors'])) { // Nothing? - if (empty($_POST['to_fix'])) + if (empty($_POST['to_fix'])) { Utils::redirectexit('action=admin;area=manageattachments;sa=maintenance'); + } - $_SESSION['attachments_to_fix'] = array(); + $_SESSION['attachments_to_fix'] = []; // @todo No need to do this I think. - foreach ($_POST['to_fix'] as $value) + foreach ($_POST['to_fix'] as $value) { $_SESSION['attachments_to_fix'][] = $value; + } } } // All the valid problems are here: - Utils::$context['repair_errors'] = array( + Utils::$context['repair_errors'] = [ 'missing_thumbnail_parent' => 0, 'parent_missing_thumbnail' => 0, 'file_missing_on_disk' => 0, @@ -820,77 +804,78 @@ public function repair(): void 'avatar_no_member' => 0, 'wrong_folder' => 0, 'files_without_attachment' => 0, - ); + ]; - $to_fix = !empty($_SESSION['attachments_to_fix']) ? $_SESSION['attachments_to_fix'] : array(); + $to_fix = !empty($_SESSION['attachments_to_fix']) ? $_SESSION['attachments_to_fix'] : []; - Utils::$context['repair_errors'] = isset($_SESSION['attachments_to_fix2']) ? $_SESSION['attachments_to_fix2'] : Utils::$context['repair_errors']; + Utils::$context['repair_errors'] = $_SESSION['attachments_to_fix2'] ?? Utils::$context['repair_errors']; $fix_errors = isset($_GET['fixErrors']) ? true : false; // Get stranded thumbnails. - if ($_GET['step'] <= 0) - { - $result = Db::$db->query('', ' + if ($_GET['step'] <= 0) { + $result = Db::$db->query( + '', + ' SELECT MAX(id_attach) FROM {db_prefix}attachments WHERE attachment_type = {int:thumbnail}', - array( + [ 'thumbnail' => 3, - ) + ], ); - list ($thumbnails) = Db::$db->fetch_row($result); + list($thumbnails) = Db::$db->fetch_row($result); Db::$db->free_result($result); - for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500) - { - $to_remove = array(); + for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500) { + $to_remove = []; - $result = Db::$db->query('', ' + $result = Db::$db->query( + '', + ' SELECT thumb.id_attach, thumb.id_folder, thumb.filename, thumb.file_hash FROM {db_prefix}attachments AS thumb LEFT JOIN {db_prefix}attachments AS tparent ON (tparent.id_thumb = thumb.id_attach) WHERE thumb.id_attach BETWEEN {int:substep} AND {int:substep} + 499 AND thumb.attachment_type = {int:thumbnail} AND tparent.id_attach IS NULL', - array( + [ 'thumbnail' => 3, 'substep' => $_GET['substep'], - ) + ], ); - while ($row = Db::$db->fetch_assoc($result)) - { + + while ($row = Db::$db->fetch_assoc($result)) { // Only do anything once... just in case - if (!isset($to_remove[$row['id_attach']])) - { + if (!isset($to_remove[$row['id_attach']])) { $to_remove[$row['id_attach']] = $row['id_attach']; Utils::$context['repair_errors']['missing_thumbnail_parent']++; // If we are repairing remove the file from disk now. - if ($fix_errors && in_array('missing_thumbnail_parent', $to_fix)) - { + if ($fix_errors && in_array('missing_thumbnail_parent', $to_fix)) { $filename = Attachment::getFilePath($row['id_attach']); @unlink($filename); } } } - if (Db::$db->num_rows($result) != 0) - { + + if (Db::$db->num_rows($result) != 0) { $to_fix[] = 'missing_thumbnail_parent'; } Db::$db->free_result($result); // Do we need to delete what we have? - if ($fix_errors && !empty($to_remove) && in_array('missing_thumbnail_parent', $to_fix)) - { - Db::$db->query('', ' + if ($fix_errors && !empty($to_remove) && in_array('missing_thumbnail_parent', $to_fix)) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}attachments WHERE id_attach IN ({array_int:to_remove}) AND attachment_type = {int:attachment_type}', - array( + [ 'to_remove' => $to_remove, 'attachment_type' => 3, - ) + ], ); } @@ -903,57 +888,60 @@ public function repair(): void } // Find parents which think they have thumbnails, but actually, don't. - if ($_GET['step'] <= 1) - { - $result = Db::$db->query('', ' + if ($_GET['step'] <= 1) { + $result = Db::$db->query( + '', + ' SELECT MAX(id_attach) FROM {db_prefix}attachments WHERE id_thumb != {int:no_thumb}', - array( + [ 'no_thumb' => 0, - ) + ], ); - list ($thumbnails) = Db::$db->fetch_row($result); + list($thumbnails) = Db::$db->fetch_row($result); Db::$db->free_result($result); - for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500) - { - $to_update = array(); + for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500) { + $to_update = []; - $result = Db::$db->query('', ' + $result = Db::$db->query( + '', + ' SELECT a.id_attach FROM {db_prefix}attachments AS a LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb) WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499 AND a.id_thumb != {int:no_thumb} AND thumb.id_attach IS NULL', - array( + [ 'no_thumb' => 0, 'substep' => $_GET['substep'], - ) + ], ); - while ($row = Db::$db->fetch_assoc($result)) - { + + while ($row = Db::$db->fetch_assoc($result)) { $to_update[] = $row['id_attach']; Utils::$context['repair_errors']['parent_missing_thumbnail']++; } - if (Db::$db->num_rows($result) != 0) - { + + if (Db::$db->num_rows($result) != 0) { $to_fix[] = 'parent_missing_thumbnail'; } Db::$db->free_result($result); // Do we need to delete what we have? - if ($fix_errors && !empty($to_update) && in_array('parent_missing_thumbnail', $to_fix)) - { - Db::$db->query('', ' + if ($fix_errors && !empty($to_update) && in_array('parent_missing_thumbnail', $to_fix)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}attachments SET id_thumb = {int:no_thumb} WHERE id_attach IN ({array_int:to_update})', - array( + [ 'to_update' => $to_update, 'no_thumb' => 0, - ) + ], ); } @@ -966,70 +954,66 @@ public function repair(): void } // This may take forever I'm afraid, but life sucks... recount EVERY attachments! - if ($_GET['step'] <= 2) - { - $result = Db::$db->query('', ' + if ($_GET['step'] <= 2) { + $result = Db::$db->query( + '', + ' SELECT MAX(id_attach) FROM {db_prefix}attachments', - array( - ) + [ + ], ); - list ($thumbnails) = Db::$db->fetch_row($result); + list($thumbnails) = Db::$db->fetch_row($result); Db::$db->free_result($result); - for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 250) - { - $to_remove = array(); - $errors_found = array(); + for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 250) { + $to_remove = []; + $errors_found = []; - $result = Db::$db->query('', ' + $result = Db::$db->query( + '', + ' SELECT id_attach, id_folder, filename, file_hash, size, attachment_type FROM {db_prefix}attachments WHERE id_attach BETWEEN {int:substep} AND {int:substep} + 249', - array( + [ 'substep' => $_GET['substep'], - ) + ], ); - while ($row = Db::$db->fetch_assoc($result)) - { + + while ($row = Db::$db->fetch_assoc($result)) { // Get the filename. - if ($row['attachment_type'] == 1) - { + if ($row['attachment_type'] == 1) { $filename = Config::$modSettings['custom_avatar_dir'] . '/' . $row['filename']; - } - else - { + } else { $filename = Attachment::getFilePath($row['id_attach']); } // File doesn't exist? - if (!file_exists($filename)) - { + if (!file_exists($filename)) { // If we're lucky it might just be in a different folder. - if (!empty(Config::$modSettings['currentAttachmentUploadDir'])) - { + if (!empty(Config::$modSettings['currentAttachmentUploadDir'])) { // Get the attachment name with out the folder. $attachment_name = $row['id_attach'] . '_' . $row['file_hash'] . '.dat'; // Loop through the other folders. - foreach (Config::$modSettings['attachmentUploadDir'] as $id => $dir) - { - if (file_exists($dir . '/' . $attachment_name)) - { + foreach (Config::$modSettings['attachmentUploadDir'] as $id => $dir) { + if (file_exists($dir . '/' . $attachment_name)) { Utils::$context['repair_errors']['wrong_folder']++; $errors_found[] = 'wrong_folder'; // Are we going to fix this now? - if ($fix_errors && in_array('wrong_folder', $to_fix)) - { - Db::$db->query('', ' + if ($fix_errors && in_array('wrong_folder', $to_fix)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}attachments SET id_folder = {int:new_folder} WHERE id_attach = {int:id_attach}', - array( + [ 'new_folder' => $id, 'id_attach' => $row['id_attach'], - ) + ], ); } @@ -1041,73 +1025,76 @@ public function repair(): void $to_remove[] = $row['id_attach']; Utils::$context['repair_errors']['file_missing_on_disk']++; $errors_found[] = 'file_missing_on_disk'; - } - elseif (filesize($filename) == 0) - { + } elseif (filesize($filename) == 0) { Utils::$context['repair_errors']['file_size_of_zero']++; $errors_found[] = 'file_size_of_zero'; // Fixing? - if ($fix_errors && in_array('file_size_of_zero', $to_fix)) - { + if ($fix_errors && in_array('file_size_of_zero', $to_fix)) { $to_remove[] = $row['id_attach']; @unlink($filename); } - } - elseif (filesize($filename) != $row['size']) - { + } elseif (filesize($filename) != $row['size']) { Utils::$context['repair_errors']['file_wrong_size']++; $errors_found[] = 'file_wrong_size'; // Fix it here? - if ($fix_errors && in_array('file_wrong_size', $to_fix)) - { - Db::$db->query('', ' + if ($fix_errors && in_array('file_wrong_size', $to_fix)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}attachments SET size = {int:filesize} WHERE id_attach = {int:id_attach}', - array( + [ 'filesize' => filesize($filename), 'id_attach' => $row['id_attach'], - ) + ], ); } } } - if (in_array('file_missing_on_disk', $errors_found)) + if (in_array('file_missing_on_disk', $errors_found)) { $to_fix[] = 'file_missing_on_disk'; + } - if (in_array('file_size_of_zero', $errors_found)) + if (in_array('file_size_of_zero', $errors_found)) { $to_fix[] = 'file_size_of_zero'; + } - if (in_array('file_wrong_size', $errors_found)) + if (in_array('file_wrong_size', $errors_found)) { $to_fix[] = 'file_wrong_size'; + } - if (in_array('wrong_folder', $errors_found)) + if (in_array('wrong_folder', $errors_found)) { $to_fix[] = 'wrong_folder'; + } Db::$db->free_result($result); // Do we need to delete what we have? - if ($fix_errors && !empty($to_remove)) - { - Db::$db->query('', ' + if ($fix_errors && !empty($to_remove)) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}attachments WHERE id_attach IN ({array_int:to_remove})', - array( + [ 'to_remove' => $to_remove, - ) + ], ); - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}attachments SET id_thumb = {int:no_thumb} WHERE id_thumb IN ({array_int:to_remove})', - array( + [ 'to_remove' => $to_remove, 'no_thumb' => 0, - ) + ], ); } @@ -1120,22 +1107,24 @@ public function repair(): void } // Get avatars with no members associated with them. - if ($_GET['step'] <= 3) - { - $result = Db::$db->query('', ' + if ($_GET['step'] <= 3) { + $result = Db::$db->query( + '', + ' SELECT MAX(id_attach) FROM {db_prefix}attachments', - array( - ) + [ + ], ); - list ($thumbnails) = Db::$db->fetch_row($result); + list($thumbnails) = Db::$db->fetch_row($result); Db::$db->free_result($result); - for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500) - { - $to_remove = array(); + for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500) { + $to_remove = []; - $result = Db::$db->query('', ' + $result = Db::$db->query( + '', + ' SELECT a.id_attach, a.id_folder, a.filename, a.file_hash, a.attachment_type FROM {db_prefix}attachments AS a LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member) @@ -1143,51 +1132,48 @@ public function repair(): void AND a.id_member != {int:no_member} AND a.id_msg = {int:no_msg} AND mem.id_member IS NULL', - array( + [ 'no_member' => 0, 'no_msg' => 0, 'substep' => $_GET['substep'], - ) + ], ); - while ($row = Db::$db->fetch_assoc($result)) - { + + while ($row = Db::$db->fetch_assoc($result)) { $to_remove[] = $row['id_attach']; Utils::$context['repair_errors']['avatar_no_member']++; // If we are repairing remove the file from disk now. - if ($fix_errors && in_array('avatar_no_member', $to_fix)) - { - if ($row['attachment_type'] == 1) - { + if ($fix_errors && in_array('avatar_no_member', $to_fix)) { + if ($row['attachment_type'] == 1) { $filename = Config::$modSettings['custom_avatar_dir'] . '/' . $row['filename']; - } - else - { + } else { $filename = Attachment::getFilePath($row['id_attach']); } @unlink($filename); } } - if (Db::$db->num_rows($result) != 0) - { + + if (Db::$db->num_rows($result) != 0) { $to_fix[] = 'avatar_no_member'; } Db::$db->free_result($result); // Do we need to delete what we have? - if ($fix_errors && !empty($to_remove) && in_array('avatar_no_member', $to_fix)) - { - Db::$db->query('', ' + if ($fix_errors && !empty($to_remove) && in_array('avatar_no_member', $to_fix)) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}attachments WHERE id_attach IN ({array_int:to_remove}) AND id_member != {int:no_member} AND id_msg = {int:no_msg}', - array( + [ 'to_remove' => $to_remove, 'no_member' => 0, 'no_msg' => 0, - ) + ], ); } @@ -1200,26 +1186,28 @@ public function repair(): void } // What about attachments, who are missing a message :'( - if ($_GET['step'] <= 4) - { - $result = Db::$db->query('', ' + if ($_GET['step'] <= 4) { + $result = Db::$db->query( + '', + ' SELECT MAX(id_attach) FROM {db_prefix}attachments', - array( - ) + [ + ], ); - list ($thumbnails) = Db::$db->fetch_row($result); + list($thumbnails) = Db::$db->fetch_row($result); Db::$db->free_result($result); - for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500) - { - $to_remove = array(); - $ignore_ids = array(0); + for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500) { + $to_remove = []; + $ignore_ids = [0]; // returns an array of ints of id_attach's that should not be deleted - IntegrationHook::call('integrate_repair_attachments_nomsg', array(&$ignore_ids, $_GET['substep'], $_GET['substep'] + 500)); + IntegrationHook::call('integrate_repair_attachments_nomsg', [&$ignore_ids, $_GET['substep'], $_GET['substep'] + 500]); - $result = Db::$db->query('', ' + $result = Db::$db->query( + '', + ' SELECT a.id_attach, a.id_folder, a.filename, a.file_hash FROM {db_prefix}attachments AS a LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg) @@ -1228,45 +1216,45 @@ public function repair(): void AND (a.id_msg = {int:no_msg} OR m.id_msg IS NULL) AND a.id_attach NOT IN ({array_int:ignore_ids}) AND a.attachment_type IN ({array_int:attach_thumb})', - array( + [ 'no_member' => 0, 'no_msg' => 0, 'substep' => $_GET['substep'], 'ignore_ids' => $ignore_ids, - 'attach_thumb' => array(0, 3), - ) + 'attach_thumb' => [0, 3], + ], ); - while ($row = Db::$db->fetch_assoc($result)) - { + + while ($row = Db::$db->fetch_assoc($result)) { $to_remove[] = $row['id_attach']; Utils::$context['repair_errors']['attachment_no_msg']++; // If we are repairing remove the file from disk now. - if ($fix_errors && in_array('attachment_no_msg', $to_fix)) - { + if ($fix_errors && in_array('attachment_no_msg', $to_fix)) { $filename = Attachment::getFilePath($row['id_attach']); @unlink($filename); } } - if (Db::$db->num_rows($result) != 0) - { + + if (Db::$db->num_rows($result) != 0) { $to_fix[] = 'attachment_no_msg'; } Db::$db->free_result($result); // Do we need to delete what we have? - if ($fix_errors && !empty($to_remove) && in_array('attachment_no_msg', $to_fix)) - { - Db::$db->query('', ' + if ($fix_errors && !empty($to_remove) && in_array('attachment_no_msg', $to_fix)) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}attachments WHERE id_attach IN ({array_int:to_remove}) AND id_member = {int:no_member} AND attachment_type IN ({array_int:attach_thumb})', - array( + [ 'to_remove' => $to_remove, 'no_member' => 0, - 'attach_thumb' => array(0, 3), - ) + 'attach_thumb' => [0, 3], + ], ); } @@ -1279,70 +1267,59 @@ public function repair(): void } // What about files who are not recorded in the database? - if ($_GET['step'] <= 5) - { + if ($_GET['step'] <= 5) { $attach_dirs = Config::$modSettings['attachmentUploadDir']; $current_check = 0; $max_checks = 500; $files_checked = empty($_GET['substep']) ? 0 : $_GET['substep']; - foreach ($attach_dirs as $attach_dir) - { - if ($dir = @opendir($attach_dir)) - { - while ($file = readdir($dir)) - { - if (in_array($file, array('.', '..', '.htaccess', 'index.php'))) + + foreach ($attach_dirs as $attach_dir) { + if ($dir = @opendir($attach_dir)) { + while ($file = readdir($dir)) { + if (in_array($file, ['.', '..', '.htaccess', 'index.php'])) { continue; + } - if ($files_checked <= $current_check) - { + if ($files_checked <= $current_check) { // Temporary file, get rid of it! - if (strpos($file, 'post_tmp_') !== false) - { + if (strpos($file, 'post_tmp_') !== false) { // Temp file is more than 5 hours old! - if (filemtime($attach_dir . '/' . $file) < time() - 18000) + if (filemtime($attach_dir . '/' . $file) < time() - 18000) { @unlink($attach_dir . '/' . $file); + } } // That should be an attachment, let's check if we have it in the database - elseif (strpos($file, '_') !== false) - { + elseif (strpos($file, '_') !== false) { $attachID = (int) substr($file, 0, strpos($file, '_')); - if (!empty($attachID)) - { - $request = Db::$db->query('', ' + if (!empty($attachID)) { + $request = Db::$db->query( + '', + ' SELECT id_attach FROM {db_prefix}attachments WHERE id_attach = {int:attachment_id} LIMIT 1', - array( + [ 'attachment_id' => $attachID, - ) + ], ); - if (Db::$db->num_rows($request) == 0) - { - if ($fix_errors && in_array('files_without_attachment', $to_fix)) - { + + if (Db::$db->num_rows($request) == 0) { + if ($fix_errors && in_array('files_without_attachment', $to_fix)) { @unlink($attach_dir . '/' . $file); - } - else - { + } else { Utils::$context['repair_errors']['files_without_attachment']++; $to_fix[] = 'files_without_attachment'; } } Db::$db->free_result($request); } - } - else - { - if ($fix_errors && in_array('files_without_attachment', $to_fix)) - { + } else { + if ($fix_errors && in_array('files_without_attachment', $to_fix)) { @unlink($attach_dir . '/' . $file); - } - else - { + } else { Utils::$context['repair_errors']['files_without_attachment']++; $to_fix[] = 'files_without_attachment'; } @@ -1351,8 +1328,9 @@ public function repair(): void $current_check++; $_GET['substep'] = $current_check; - if ($current_check - $files_checked >= $max_checks) + if ($current_check - $files_checked >= $max_checks) { $this->pauseAttachmentMaintenance($to_fix); + } } closedir($dir); @@ -1381,183 +1359,157 @@ public function repair(): void public function paths(): void { // Since this needs to be done eventually. - if (!isset(Config::$modSettings['attachment_basedirectories'])) - { - Config::$modSettings['attachment_basedirectories'] = array(); - } - elseif (!is_array(Config::$modSettings['attachment_basedirectories'])) - { + if (!isset(Config::$modSettings['attachment_basedirectories'])) { + Config::$modSettings['attachment_basedirectories'] = []; + } elseif (!is_array(Config::$modSettings['attachment_basedirectories'])) { Config::$modSettings['attachment_basedirectories'] = Utils::jsonDecode(Config::$modSettings['attachment_basedirectories'], true); } - $errors = array(); + $errors = []; // Saving? - if (isset($_REQUEST['save'])) - { + if (isset($_REQUEST['save'])) { User::$me->checkSession(); $_POST['current_dir'] = (int) $_POST['current_dir']; - $new_dirs = array(); + $new_dirs = []; - foreach ($_POST['dirs'] as $id => $path) - { + foreach ($_POST['dirs'] as $id => $path) { $error = ''; $id = (int) $id; - if ($id < 1) + if ($id < 1) { continue; + } // Sorry, these dirs are NOT valid - $invalid_dirs = array(Config::$boarddir, Theme::$current->settings['default_theme_dir'], Config::$sourcedir); + $invalid_dirs = [Config::$boarddir, Theme::$current->settings['default_theme_dir'], Config::$sourcedir]; - if (in_array($path, $invalid_dirs)) - { + if (in_array($path, $invalid_dirs)) { $errors[] = $path . ': ' . Lang::$txt['attach_dir_invalid']; + continue; } // Hmm, a new path maybe? // Don't allow empty paths - if (!array_key_exists($id, Config::$modSettings['attachmentUploadDir']) && !empty($path)) - { + if (!array_key_exists($id, Config::$modSettings['attachmentUploadDir']) && !empty($path)) { // or is it? - if (in_array($path, Config::$modSettings['attachmentUploadDir']) || in_array(Config::$boarddir . DIRECTORY_SEPARATOR . $path, Config::$modSettings['attachmentUploadDir'])) - { + if (in_array($path, Config::$modSettings['attachmentUploadDir']) || in_array(Config::$boarddir . DIRECTORY_SEPARATOR . $path, Config::$modSettings['attachmentUploadDir'])) { $errors[] = $path . ': ' . Lang::$txt['attach_dir_duplicate_msg']; + continue; } - elseif (empty($path)) - { + + if (empty($path)) { // Ignore this and set $id to one less continue; } // OK, so let's try to create it then. - if (Attachment::automanageCreateDirectory($path)) - { + if (Attachment::automanageCreateDirectory($path)) { $_POST['current_dir'] = Config::$modSettings['currentAttachmentUploadDir']; - } - else - { + } else { $errors[] = $path . ': ' . Lang::$txt[Utils::$context['dir_creation_error']]; } } // Changing a directory name? - if (!empty(Config::$modSettings['attachmentUploadDir'][$id]) && !empty($path) && $path != Config::$modSettings['attachmentUploadDir'][$id]) - { - if ($path != Config::$modSettings['attachmentUploadDir'][$id] && !is_dir($path)) - { - if (!@rename(Config::$modSettings['attachmentUploadDir'][$id], $path)) - { + if (!empty(Config::$modSettings['attachmentUploadDir'][$id]) && !empty($path) && $path != Config::$modSettings['attachmentUploadDir'][$id]) { + if ($path != Config::$modSettings['attachmentUploadDir'][$id] && !is_dir($path)) { + if (!@rename(Config::$modSettings['attachmentUploadDir'][$id], $path)) { $errors[] = $path . ': ' . Lang::$txt['attach_dir_no_rename']; $path = Config::$modSettings['attachmentUploadDir'][$id]; } - } - else - { + } else { $errors[] = $path . ': ' . Lang::$txt['attach_dir_exists_msg']; $path = Config::$modSettings['attachmentUploadDir'][$id]; } // Update the base directory path - if (!empty(Config::$modSettings['attachment_basedirectories']) && array_key_exists($id, Config::$modSettings['attachment_basedirectories'])) - { + if (!empty(Config::$modSettings['attachment_basedirectories']) && array_key_exists($id, Config::$modSettings['attachment_basedirectories'])) { $base = Config::$modSettings['basedirectory_for_attachments'] == Config::$modSettings['attachmentUploadDir'][$id] ? $path : Config::$modSettings['basedirectory_for_attachments']; Config::$modSettings['attachment_basedirectories'][$id] = $path; - Config::updateModSettings(array( + Config::updateModSettings([ 'attachment_basedirectories' => Utils::jsonEncode(Config::$modSettings['attachment_basedirectories']), 'basedirectory_for_attachments' => $base, - )); + ]); Config::$modSettings['attachment_basedirectories'] = Utils::jsonDecode(Config::$modSettings['attachment_basedirectories'], true); } } - if (empty($path)) - { + if (empty($path)) { $path = Config::$modSettings['attachmentUploadDir'][$id]; // It's not a good idea to delete the current directory. - if ($id == (!empty($_POST['current_dir']) ? $_POST['current_dir'] : Config::$modSettings['currentAttachmentUploadDir'])) - { + if ($id == (!empty($_POST['current_dir']) ? $_POST['current_dir'] : Config::$modSettings['currentAttachmentUploadDir'])) { $errors[] = $path . ': ' . Lang::$txt['attach_dir_is_current']; } // Or the current base directory - elseif (!empty(Config::$modSettings['basedirectory_for_attachments']) && Config::$modSettings['basedirectory_for_attachments'] == Config::$modSettings['attachmentUploadDir'][$id]) - { + elseif (!empty(Config::$modSettings['basedirectory_for_attachments']) && Config::$modSettings['basedirectory_for_attachments'] == Config::$modSettings['attachmentUploadDir'][$id]) { $errors[] = $path . ': ' . Lang::$txt['attach_dir_is_current_bd']; - } - else - { + } else { // Let's not try to delete a path with files in it. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(id_attach) AS num_attach FROM {db_prefix}attachments WHERE id_folder = {int:id_folder}', - array( + [ 'id_folder' => (int) $id, - ) + ], ); - list ($num_attach) = Db::$db->fetch_row($request); + list($num_attach) = Db::$db->fetch_row($request); Db::$db->free_result($request); // A check to see if it's a used base dir. - if (!empty(Config::$modSettings['attachment_basedirectories'])) - { + if (!empty(Config::$modSettings['attachment_basedirectories'])) { // Count any sub-folders. - foreach (Config::$modSettings['attachmentUploadDir'] as $sub) - { - if (strpos($sub, $path . DIRECTORY_SEPARATOR) !== false) + foreach (Config::$modSettings['attachmentUploadDir'] as $sub) { + if (strpos($sub, $path . DIRECTORY_SEPARATOR) !== false) { $num_attach++; + } } } // It's safe to delete. So try to delete the folder also - if ($num_attach == 0) - { - if (is_dir($path)) - { + if ($num_attach == 0) { + if (is_dir($path)) { $doit = true; - } - elseif (is_dir(Config::$boarddir . DIRECTORY_SEPARATOR . $path)) - { + } elseif (is_dir(Config::$boarddir . DIRECTORY_SEPARATOR . $path)) { $doit = true; $path = Config::$boarddir . DIRECTORY_SEPARATOR . $path; } - if (isset($doit) && realpath($path) != realpath(Config::$boarddir)) - { + if (isset($doit) && realpath($path) != realpath(Config::$boarddir)) { unlink($path . '/.htaccess'); unlink($path . '/index.php'); - if (!@rmdir($path)) - { + if (!@rmdir($path)) { $error = $path . ': ' . Lang::$txt['attach_dir_no_delete']; } } // Remove it from the base directory list. - if (empty($error) && !empty(Config::$modSettings['attachment_basedirectories'])) - { + if (empty($error) && !empty(Config::$modSettings['attachment_basedirectories'])) { unset(Config::$modSettings['attachment_basedirectories'][$id]); - Config::updateModSettings(array('attachment_basedirectories' => Utils::jsonEncode(Config::$modSettings['attachment_basedirectories']))); + Config::updateModSettings(['attachment_basedirectories' => Utils::jsonEncode(Config::$modSettings['attachment_basedirectories'])]); Config::$modSettings['attachment_basedirectories'] = Utils::jsonDecode(Config::$modSettings['attachment_basedirectories'], true); } - } - else - { + } else { $error = $path . ': ' . Lang::$txt['attach_dir_no_remove']; } - if (empty($error)) + if (empty($error)) { continue; + } $errors[] = $error; } @@ -1567,20 +1519,15 @@ public function paths(): void } // We need to make sure the current directory is right. - if (empty($_POST['current_dir']) && !empty(Config::$modSettings['currentAttachmentUploadDir'])) - { + if (empty($_POST['current_dir']) && !empty(Config::$modSettings['currentAttachmentUploadDir'])) { $_POST['current_dir'] = Config::$modSettings['currentAttachmentUploadDir']; } // Find the current directory if there's no value carried, - if (empty($_POST['current_dir']) || empty($new_dirs[$_POST['current_dir']])) - { - if (array_key_exists(Config::$modSettings['currentAttachmentUploadDir'], Config::$modSettings['attachmentUploadDir'])) - { + if (empty($_POST['current_dir']) || empty($new_dirs[$_POST['current_dir']])) { + if (array_key_exists(Config::$modSettings['currentAttachmentUploadDir'], Config::$modSettings['attachmentUploadDir'])) { $_POST['current_dir'] = Config::$modSettings['currentAttachmentUploadDir']; - } - else - { + } else { $_POST['current_dir'] = max(array_keys(Config::$modSettings['attachmentUploadDir'])); } } @@ -1593,35 +1540,29 @@ public function paths(): void isset(Config::$modSettings['last_attachments_directory'][$_POST['current_dir']]) || isset(Config::$modSettings['last_attachments_directory'][0]) ) - ) - { - if (!is_array(Config::$modSettings['last_attachments_directory'])) - { + ) { + if (!is_array(Config::$modSettings['last_attachments_directory'])) { Config::$modSettings['last_attachments_directory'] = Utils::jsonDecode(Config::$modSettings['last_attachments_directory'], true); } $num = substr(strrchr(Config::$modSettings['attachmentUploadDir'][$_POST['current_dir']], '_'), 1); - if (is_numeric($num)) - { + if (is_numeric($num)) { // Need to find the base folder. $bid = -1; $use_subdirectories_for_attachments = 0; - if (!empty(Config::$modSettings['attachment_basedirectories'])) - { - foreach (Config::$modSettings['attachment_basedirectories'] as $bid => $base) - { - if (strpos(Config::$modSettings['attachmentUploadDir'][$_POST['current_dir']], $base . DIRECTORY_SEPARATOR) !== false) - { + if (!empty(Config::$modSettings['attachment_basedirectories'])) { + foreach (Config::$modSettings['attachment_basedirectories'] as $bid => $base) { + if (strpos(Config::$modSettings['attachmentUploadDir'][$_POST['current_dir']], $base . DIRECTORY_SEPARATOR) !== false) { $use_subdirectories_for_attachments = 1; + break; } } } - if ($use_subdirectories_for_attachments == 0 && strpos(Config::$modSettings['attachmentUploadDir'][$_POST['current_dir']], Config::$boarddir . DIRECTORY_SEPARATOR) !== false) - { + if ($use_subdirectories_for_attachments == 0 && strpos(Config::$modSettings['attachmentUploadDir'][$_POST['current_dir']], Config::$boarddir . DIRECTORY_SEPARATOR) !== false) { $bid = 0; } @@ -1631,98 +1572,88 @@ public function paths(): void Config::$modSettings['use_subdirectories_for_attachments'] = !empty(Config::$modSettings['use_subdirectories_for_attachments']) ? Config::$modSettings['use_subdirectories_for_attachments'] : 0; - Config::updateModSettings(array( + Config::updateModSettings([ 'last_attachments_directory' => Utils::jsonEncode(Config::$modSettings['last_attachments_directory']), 'basedirectory_for_attachments' => $bid == 0 ? Config::$modSettings['basedirectory_for_attachments'] : Config::$modSettings['attachment_basedirectories'][$bid], 'use_subdirectories_for_attachments' => $use_subdirectories_for_attachments, - )); + ]); } } // Going back to just one path? - if (count($new_dirs) == 1) - { + if (count($new_dirs) == 1) { // We might need to reset the paths. This loop will just loop through once. - foreach ($new_dirs as $id => $dir) - { - if ($id != 1) - { - Db::$db->query('', ' + foreach ($new_dirs as $id => $dir) { + if ($id != 1) { + Db::$db->query( + '', + ' UPDATE {db_prefix}attachments SET id_folder = {int:default_folder} WHERE id_folder = {int:current_folder}', - array( + [ 'default_folder' => 1, 'current_folder' => $id, - ) + ], ); } - $update = array( + $update = [ 'currentAttachmentUploadDir' => 1, - 'attachmentUploadDir' => Utils::jsonEncode(array(1 => $dir)), - ); + 'attachmentUploadDir' => Utils::jsonEncode([1 => $dir]), + ]; } - } - else - { + } else { // Save it to the database. - $update = array( + $update = [ 'currentAttachmentUploadDir' => $_POST['current_dir'], 'attachmentUploadDir' => Utils::jsonEncode($new_dirs), - ); + ]; } - if (!empty($update)) + if (!empty($update)) { Config::updateModSettings($update); + } - if (!empty($errors)) + if (!empty($errors)) { $_SESSION['errors']['dir'] = $errors; + } Utils::redirectexit('action=admin;area=manageattachments;sa=attachpaths;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']); } // Saving a base directory? - if (isset($_REQUEST['save2'])) - { + if (isset($_REQUEST['save2'])) { User::$me->checkSession(); // Changing the current base directory? $_POST['current_base_dir'] = isset($_POST['current_base_dir']) ? (int) $_POST['current_base_dir'] : 1; - if (empty($_POST['new_base_dir']) && !empty($_POST['current_base_dir'])) - { - if (Config::$modSettings['basedirectory_for_attachments'] != Config::$modSettings['attachmentUploadDir'][$_POST['current_base_dir']]) - { - $update = array( + if (empty($_POST['new_base_dir']) && !empty($_POST['current_base_dir'])) { + if (Config::$modSettings['basedirectory_for_attachments'] != Config::$modSettings['attachmentUploadDir'][$_POST['current_base_dir']]) { + $update = [ 'basedirectory_for_attachments' => Config::$modSettings['attachmentUploadDir'][$_POST['current_base_dir']], - ); + ]; } } - if (isset($_POST['base_dir'])) - { - foreach ($_POST['base_dir'] as $id => $dir) - { - if (!empty($dir) && $dir != Config::$modSettings['attachmentUploadDir'][$id]) - { - if (@rename(Config::$modSettings['attachmentUploadDir'][$id], $dir)) - { + if (isset($_POST['base_dir'])) { + foreach ($_POST['base_dir'] as $id => $dir) { + if (!empty($dir) && $dir != Config::$modSettings['attachmentUploadDir'][$id]) { + if (@rename(Config::$modSettings['attachmentUploadDir'][$id], $dir)) { Config::$modSettings['attachmentUploadDir'][$id] = $dir; Config::$modSettings['attachment_basedirectories'][$id] = $dir; - $update = array( + $update = [ 'attachmentUploadDir' => Utils::jsonEncode(Config::$modSettings['attachmentUploadDir']), 'attachment_basedirectories' => Utils::jsonEncode(Config::$modSettings['attachment_basedirectories']), 'basedirectory_for_attachments' => Config::$modSettings['attachmentUploadDir'][$_POST['current_base_dir']], - ); + ]; } } - if (empty($dir)) - { - if ($id == $_POST['current_base_dir']) - { + if (empty($dir)) { + if ($id == $_POST['current_base_dir']) { $errors[] = Config::$modSettings['attachmentUploadDir'][$id] . ': ' . Lang::$txt['attach_dir_is_current']; continue; @@ -1730,241 +1661,233 @@ public function paths(): void unset(Config::$modSettings['attachment_basedirectories'][$id]); - $update = array( + $update = [ 'attachment_basedirectories' => Utils::jsonEncode(Config::$modSettings['attachment_basedirectories']), 'basedirectory_for_attachments' => Config::$modSettings['attachmentUploadDir'][$_POST['current_base_dir']], - ); + ]; } } } // Or adding a new one? - if (!empty($_POST['new_base_dir'])) - { + if (!empty($_POST['new_base_dir'])) { $_POST['new_base_dir'] = Utils::htmlspecialchars($_POST['new_base_dir'], ENT_QUOTES); $current_dir = Config::$modSettings['currentAttachmentUploadDir']; - if (!in_array($_POST['new_base_dir'], Config::$modSettings['attachmentUploadDir'])) - { - if (!Attachment::automanageCreateDirectory($_POST['new_base_dir'])) - { + if (!in_array($_POST['new_base_dir'], Config::$modSettings['attachmentUploadDir'])) { + if (!Attachment::automanageCreateDirectory($_POST['new_base_dir'])) { $errors[] = $_POST['new_base_dir'] . ': ' . Lang::$txt['attach_dir_base_no_create']; } } Config::$modSettings['currentAttachmentUploadDir'] = array_search($_POST['new_base_dir'], Config::$modSettings['attachmentUploadDir']); - if (!in_array($_POST['new_base_dir'], Config::$modSettings['attachment_basedirectories'])) - { + if (!in_array($_POST['new_base_dir'], Config::$modSettings['attachment_basedirectories'])) { Config::$modSettings['attachment_basedirectories'][Config::$modSettings['currentAttachmentUploadDir']] = $_POST['new_base_dir']; } ksort(Config::$modSettings['attachment_basedirectories']); - $update = array( + $update = [ 'attachment_basedirectories' => Utils::jsonEncode(Config::$modSettings['attachment_basedirectories']), 'basedirectory_for_attachments' => $_POST['new_base_dir'], 'currentAttachmentUploadDir' => $current_dir, - ); + ]; } - if (!empty($errors)) + if (!empty($errors)) { $_SESSION['errors']['base'] = $errors; + } - if (!empty($update)) + if (!empty($update)) { Config::updateModSettings($update); + } Utils::redirectexit('action=admin;area=manageattachments;sa=attachpaths;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']); } - if (isset($_SESSION['errors'])) - { - if (is_array($_SESSION['errors'])) - { - $errors = array(); + if (isset($_SESSION['errors'])) { + if (is_array($_SESSION['errors'])) { + $errors = []; - if (!empty($_SESSION['errors']['dir'])) - { - foreach ($_SESSION['errors']['dir'] as $error) + if (!empty($_SESSION['errors']['dir'])) { + foreach ($_SESSION['errors']['dir'] as $error) { $errors['dir'][] = Utils::htmlspecialchars($error, ENT_QUOTES); + } } - if (!empty($_SESSION['errors']['base'])) - { - foreach ($_SESSION['errors']['base'] as $error) + if (!empty($_SESSION['errors']['base'])) { + foreach ($_SESSION['errors']['base'] as $error) { $errors['base'][] = Utils::htmlspecialchars($error, ENT_QUOTES); + } } } unset($_SESSION['errors']); } - $listOptions = array( + $listOptions = [ 'id' => 'attach_paths', 'base_href' => Config::$scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'], 'title' => Lang::$txt['attach_paths'], - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getAttachDirs', - ), - 'columns' => array( - 'current_dir' => array( - 'header' => array( + ], + 'columns' => [ + 'current_dir' => [ + 'header' => [ 'value' => Lang::$txt['attach_current'], 'class' => 'centercol', - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return ''; }, 'style' => 'width: 10%;', 'class' => 'centercol', - ), - ), - 'path' => array( - 'header' => array( + ], + ], + 'path' => [ + 'header' => [ 'value' => Lang::$txt['attach_path'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return ''; }, 'style' => 'width: 40%;', - ), - ), - 'current_size' => array( - 'header' => array( + ], + ], + 'current_size' => [ + 'header' => [ 'value' => Lang::$txt['attach_current_size'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'current_size', 'style' => 'width: 15%;', - ), - ), - 'num_files' => array( - 'header' => array( + ], + ], + 'num_files' => [ + 'header' => [ 'value' => Lang::$txt['attach_num_files'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'num_files', 'style' => 'width: 15%;', - ), - ), - 'status' => array( - 'header' => array( + ], + ], + 'status' => [ + 'header' => [ 'value' => Lang::$txt['attach_dir_status'], 'class' => 'centercol', - ), - 'data' => array( + ], + 'data' => [ 'db' => 'status', 'style' => 'width: 25%;', 'class' => 'centercol', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'], - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'below_table_data', 'value' => ' ', - ), - empty($errors['dir']) ? array( + ], + empty($errors['dir']) ? [ 'position' => 'top_of_list', 'value' => Lang::$txt['attach_dir_desc'], - 'class' => 'information' - ) : array( + 'class' => 'information', + ] : [ 'position' => 'top_of_list', 'value' => Lang::$txt['attach_dir_save_problem'] . '
' . implode('
', $errors['dir']), 'style' => 'padding-left: 35px;', 'class' => 'noticebox', - ), - ), - ); + ], + ], + ]; new ItemList($listOptions); - if (!empty(Config::$modSettings['attachment_basedirectories'])) - { - $listOptions2 = array( + if (!empty(Config::$modSettings['attachment_basedirectories'])) { + $listOptions2 = [ 'id' => 'base_paths', 'base_href' => Config::$scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'], 'title' => Lang::$txt['attach_base_paths'], - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getBaseDirs', - ), - 'columns' => array( - 'current_dir' => array( - 'header' => array( + ], + 'columns' => [ + 'current_dir' => [ + 'header' => [ 'value' => Lang::$txt['attach_current'], 'class' => 'centercol', - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return ''; }, 'style' => 'width: 10%;', 'class' => 'centercol', - ), - ), - 'path' => array( - 'header' => array( + ], + ], + 'path' => [ + 'header' => [ 'value' => Lang::$txt['attach_path'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'path', 'style' => 'width: 45%;', 'class' => 'word_break', - ), - ), - 'num_dirs' => array( - 'header' => array( + ], + ], + 'num_dirs' => [ + 'header' => [ 'value' => Lang::$txt['attach_num_dirs'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'num_dirs', 'style' => 'width: 15%;', - ), - ), - 'status' => array( - 'header' => array( + ], + ], + 'status' => [ + 'header' => [ 'value' => Lang::$txt['attach_dir_status'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'status', 'style' => 'width: 15%;', 'class' => 'centercol', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'], - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'below_table_data', 'value' => ' ', - ), - empty($errors['base']) ? array( + ], + empty($errors['base']) ? [ 'position' => 'top_of_list', 'value' => Lang::$txt['attach_dir_base_desc'], 'style' => 'padding: 5px 10px;', - 'class' => 'windowbg smalltext' - ) : array( + 'class' => 'windowbg smalltext', + ] : [ 'position' => 'top_of_list', 'value' => Lang::$txt['attach_dir_save_problem'] . '
' . implode('
', $errors['base']), 'style' => 'padding-left: 35px', 'class' => 'noticebox', - ), - ), - ); + ], + ], + ]; new ItemList($listOptions2); } @@ -1981,13 +1904,10 @@ public function transfer(): void { User::$me->checkSession(); - if (!empty(Config::$modSettings['attachment_basedirectories'])) - { + if (!empty(Config::$modSettings['attachment_basedirectories'])) { Config::$modSettings['attachment_basedirectories'] = Utils::jsonDecode(Config::$modSettings['attachment_basedirectories'], true); - } - else - { - Config::$modSettings['basedirectory_for_attachments'] = array(); + } else { + Config::$modSettings['basedirectory_for_attachments'] = []; } $_POST['from'] = (int) $_POST['from']; @@ -1996,65 +1916,66 @@ public function transfer(): void $start = !empty($_POST['empty_it']) ? 0 : Config::$modSettings['attachmentDirFileLimit']; $_SESSION['checked'] = !empty($_POST['empty_it']) ? true : false; $limit = 501; - $results = array(); + $results = []; $dir_files = 0; $current_progress = 0; $total_moved = 0; $total_not_moved = 0; - if (empty($_POST['from']) || (empty($_POST['auto']) && empty($_POST['to']))) + if (empty($_POST['from']) || (empty($_POST['auto']) && empty($_POST['to']))) { $results[] = Lang::$txt['attachment_transfer_no_dir']; + } - if ($_POST['from'] == $_POST['to']) + if ($_POST['from'] == $_POST['to']) { $results[] = Lang::$txt['attachment_transfer_same_dir']; + } - if (empty($results)) - { + if (empty($results)) { // Get the total file count for the progess bar. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}attachments WHERE id_folder = {int:folder_id} AND attachment_type != {int:attachment_type}', - array( + [ 'folder_id' => $_POST['from'], 'attachment_type' => 1, - ) + ], ); - list ($total_progress) = Db::$db->fetch_row($request); + list($total_progress) = Db::$db->fetch_row($request); Db::$db->free_result($request); $total_progress -= $start; - if ($total_progress < 1) + if ($total_progress < 1) { $results[] = Lang::$txt['attachment_transfer_no_find']; + } } - if (empty($results)) - { + if (empty($results)) { // Where are they going? - if (!empty($_POST['auto'])) - { + if (!empty($_POST['auto'])) { Config::$modSettings['automanage_attachments'] = 1; Config::$modSettings['use_subdirectories_for_attachments'] = $_POST['auto'] == -1 ? 0 : 1; Config::$modSettings['basedirectory_for_attachments'] = $_POST['auto'] > 0 ? Config::$modSettings['attachmentUploadDir'][$_POST['auto']] : Config::$modSettings['basedirectory_for_attachments']; Attachment::automanageCheckDirectory(); $new_dir = Config::$modSettings['currentAttachmentUploadDir']; - } - else - { + } else { $new_dir = $_POST['to']; } Config::$modSettings['currentAttachmentUploadDir'] = $new_dir; $break = false; - while ($break == false) - { + + while ($break == false) { @set_time_limit(300); - if (function_exists('apache_reset_timeout')) + if (function_exists('apache_reset_timeout')) { @apache_reset_timeout(); + } // If limits are set, get the file count and size for the destination folder if ( @@ -2063,58 +1984,61 @@ public function transfer(): void !empty(Config::$modSettings['attachmentDirSizeLimit']) || !empty(Config::$modSettings['attachmentDirFileLimit']) ) - ) - { - $request = Db::$db->query('', ' + ) { + $request = Db::$db->query( + '', + ' SELECT COUNT(*), SUM(size) FROM {db_prefix}attachments WHERE id_folder = {int:folder_id} AND attachment_type != {int:attachment_type}', - array( + [ 'folder_id' => $new_dir, 'attachment_type' => 1, - ) + ], ); - list ($dir_files, $dir_size) = Db::$db->fetch_row($request); + list($dir_files, $dir_size) = Db::$db->fetch_row($request); Db::$db->free_result($request); } // Find some attachments to move - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_attach, filename, id_folder, file_hash, size FROM {db_prefix}attachments WHERE id_folder = {int:folder} AND attachment_type != {int:attachment_type} LIMIT {int:start}, {int:limit}', - array( + [ 'folder' => $_POST['from'], 'attachment_type' => 1, 'start' => $start, 'limit' => $limit, - ) + ], ); - if (Db::$db->num_rows($request) === 0) - { - if (empty($current_progress)) + if (Db::$db->num_rows($request) === 0) { + if (empty($current_progress)) { $results[] = Lang::$txt['attachment_transfer_no_find']; + } break; } - if (Db::$db->num_rows($request) < $limit) + if (Db::$db->num_rows($request) < $limit) { $break = true; + } // Move them - $moved = array(); - while ($row = Db::$db->fetch_assoc($request)) - { + $moved = []; + + while ($row = Db::$db->fetch_assoc($request)) { $source = Attachment::getFilePath($row['id_attach']); $dest = Config::$modSettings['attachmentUploadDir'][$new_dir] . '/' . basename($source); // Size and file count check - if (!empty(Config::$modSettings['attachmentDirSizeLimit']) || !empty(Config::$modSettings['attachmentDirFileLimit'])) - { + if (!empty(Config::$modSettings['attachmentDirSizeLimit']) || !empty(Config::$modSettings['attachmentDirFileLimit'])) { $dir_files++; $dir_size += !empty($row['size']) ? $row['size'] : filesize($source); @@ -2126,17 +2050,14 @@ public function transfer(): void !empty(Config::$modSettings['attachmentDirFileLimit']) && $dir_files > Config::$modSettings['attachmentDirFileLimit'] ) - ) - { - if (!empty($_POST['auto'])) - { + ) { + if (!empty($_POST['auto'])) { // Since we're in auto mode. Create a new folder and reset the counters. Attachment::automanageBySpace(); $results[] = sprintf(Lang::$txt['attachments_transferred'], $total_moved, Config::$modSettings['attachmentUploadDir'][$new_dir]); - if (!empty($total_not_moved)) - { + if (!empty($total_not_moved)) { $results[] = sprintf(Lang::$txt['attachments_not_transferred'], $total_not_moved); } @@ -2145,50 +2066,49 @@ public function transfer(): void $total_not_moved = 0; $break = false; + break; } - else - { - // Hmm, not in auto. Time to bail out then... - $results[] = Lang::$txt['attachment_transfer_no_room']; - $break = true; - break; - } + + + // Hmm, not in auto. Time to bail out then... + $results[] = Lang::$txt['attachment_transfer_no_room']; + $break = true; + + break; + } } - if (@rename($source, $dest)) - { + if (@rename($source, $dest)) { $total_moved++; $current_progress++; $moved[] = $row['id_attach']; - } - else - { + } else { $total_not_moved++; } } Db::$db->free_result($request); - if (!empty($moved)) - { + if (!empty($moved)) { // Update the database - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}attachments SET id_folder = {int:new} WHERE id_attach IN ({array_int:attachments})', - array( + [ 'attachments' => $moved, 'new' => $new_dir, - ) + ], ); } $new_dir = Config::$modSettings['currentAttachmentUploadDir']; // Create the progress bar. - if (!$break) - { + if (!$break) { $percent_done = min(round($current_progress / $total_progress * 100, 0), 100); $prog_bar = ' @@ -2198,7 +2118,7 @@ public function transfer(): void '; // Write it to a file so it can be displayed - $fp = fopen(Config::$boarddir . '/progress.php', "w"); + $fp = fopen(Config::$boarddir . '/progress.php', 'w'); fwrite($fp, $prog_bar); fclose($fp); usleep(500000); @@ -2207,14 +2127,16 @@ public function transfer(): void $results[] = sprintf(Lang::$txt['attachments_transferred'], $total_moved, Config::$modSettings['attachmentUploadDir'][$new_dir]); - if (!empty($total_not_moved)) + if (!empty($total_not_moved)) { $results[] = sprintf(Lang::$txt['attachments_not_transferred'], $total_not_moved); + } } $_SESSION['results'] = $results; - if (file_exists(Config::$boarddir . '/progress.php')) + if (file_exists(Config::$boarddir . '/progress.php')) { unlink(Config::$boarddir . '/progress.php'); + } Utils::redirectexit('action=admin;area=manageattachments;sa=maintenance#transfer'); } @@ -2230,8 +2152,9 @@ public function transfer(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -2254,27 +2177,19 @@ public static function attachConfigVars(): array Utils::$context['attachmentUploadDir'] = Config::$modSettings['attachmentUploadDir'][Config::$modSettings['currentAttachmentUploadDir']]; // If not set, show a default path for the base directory - if (!isset($_GET['save']) && empty(Config::$modSettings['basedirectory_for_attachments'])) - { - if (is_dir(Config::$modSettings['attachmentUploadDir'][1])) - { + if (!isset($_GET['save']) && empty(Config::$modSettings['basedirectory_for_attachments'])) { + if (is_dir(Config::$modSettings['attachmentUploadDir'][1])) { Config::$modSettings['basedirectory_for_attachments'] = Config::$modSettings['attachmentUploadDir'][1]; - } - else - { + } else { Config::$modSettings['basedirectory_for_attachments'] = Utils::$context['attachmentUploadDir']; } } Utils::$context['valid_upload_dir'] = is_dir(Utils::$context['attachmentUploadDir']) && is_writable(Utils::$context['attachmentUploadDir']); - if (!empty(Config::$modSettings['automanage_attachments'])) - { + if (!empty(Config::$modSettings['automanage_attachments'])) { Utils::$context['valid_basedirectory'] = !empty(Config::$modSettings['basedirectory_for_attachments']) && is_writable(Config::$modSettings['basedirectory_for_attachments']); - } - - else - { + } else { Utils::$context['valid_basedirectory'] = true; } @@ -2285,12 +2200,11 @@ public static function attachConfigVars(): array empty(Config::$modSettings['attachment_basedirectories']) && Config::$modSettings['currentAttachmentUploadDir'] == 1 && count(Config::$modSettings['attachmentUploadDir']) == 1 - ) - { + ) { Lang::$txt['attachmentUploadDir_path'] = Config::$modSettings['attachmentUploadDir'][1]; } - Lang::$txt['basedirectory_for_attachments_path'] = isset(Config::$modSettings['basedirectory_for_attachments']) ? Config::$modSettings['basedirectory_for_attachments'] : ''; + Lang::$txt['basedirectory_for_attachments_path'] = Config::$modSettings['basedirectory_for_attachments'] ?? ''; Lang::$txt['use_subdirectories_for_attachments_note'] = empty(Config::$modSettings['attachment_basedirectories']) || empty(Config::$modSettings['use_subdirectories_for_attachments']) ? Lang::$txt['use_subdirectories_for_attachments_note'] : ''; @@ -2309,56 +2223,56 @@ public static function attachConfigVars(): array $post_max_kb = floor(Config::memoryReturnBytes(ini_get('post_max_size')) / 1024); $file_max_kb = floor(Config::memoryReturnBytes(ini_get('upload_max_filesize')) / 1024); - $config_vars = array( - array('title', 'attachment_manager_settings'), + $config_vars = [ + ['title', 'attachment_manager_settings'], // Are attachments enabled? - array('select', 'attachmentEnable', array(Lang::$txt['attachmentEnable_deactivate'], Lang::$txt['attachmentEnable_enable_all'], Lang::$txt['attachmentEnable_disable_new'])), + ['select', 'attachmentEnable', [Lang::$txt['attachmentEnable_deactivate'], Lang::$txt['attachmentEnable_enable_all'], Lang::$txt['attachmentEnable_disable_new']]], '', // Directory and size limits. - array('select', 'automanage_attachments', array(0 => Lang::$txt['attachments_normal'], 1 => Lang::$txt['attachments_auto_space'], 2 => Lang::$txt['attachments_auto_years'], 3 => Lang::$txt['attachments_auto_months'], 4 => Lang::$txt['attachments_auto_16'])), - array('check', 'use_subdirectories_for_attachments', 'subtext' => Lang::$txt['use_subdirectories_for_attachments_note']), - (empty(Config::$modSettings['attachment_basedirectories']) ? array('text', 'basedirectory_for_attachments', 40,) : array('var_message', 'basedirectory_for_attachments', 'message' => 'basedirectory_for_attachments_path', 'invalid' => empty(Utils::$context['valid_basedirectory']), 'text_label' => (!empty(Utils::$context['valid_basedirectory']) ? Lang::$txt['basedirectory_for_attachments_current'] : sprintf(Lang::$txt['basedirectory_for_attachments_warning'], Config::$scripturl)))), - empty(Config::$modSettings['attachment_basedirectories']) && Config::$modSettings['currentAttachmentUploadDir'] == 1 && count(Config::$modSettings['attachmentUploadDir']) == 1 ? array('var_message', 'attachmentUploadDir_path', 'subtext' => Lang::$txt['attachmentUploadDir_multiple_configure'], 40, 'invalid' => !Utils::$context['valid_upload_dir'], 'text_label' => Lang::$txt['attachmentUploadDir'], 'message' => 'attachmentUploadDir_path') : array('var_message', 'attach_current_directory', 'subtext' => Lang::$txt['attachmentUploadDir_multiple_configure'], 'message' => 'attachment_path', 'invalid' => empty(Utils::$context['valid_upload_dir']), 'text_label' => (!empty(Utils::$context['valid_upload_dir']) ? Lang::$txt['attach_current_dir'] : sprintf(Lang::$txt['attach_current_dir_warning'], Config::$scripturl))), - array('int', 'attachmentDirFileLimit', 'subtext' => Lang::$txt['zero_for_no_limit'], 6), - array('int', 'attachmentDirSizeLimit', 'subtext' => Lang::$txt['zero_for_no_limit'], 6, 'postinput' => Lang::$txt['kilobyte']), - array('check', 'dont_show_attach_under_post', 'subtext' => Lang::$txt['dont_show_attach_under_post_sub']), + ['select', 'automanage_attachments', [0 => Lang::$txt['attachments_normal'], 1 => Lang::$txt['attachments_auto_space'], 2 => Lang::$txt['attachments_auto_years'], 3 => Lang::$txt['attachments_auto_months'], 4 => Lang::$txt['attachments_auto_16']]], + ['check', 'use_subdirectories_for_attachments', 'subtext' => Lang::$txt['use_subdirectories_for_attachments_note']], + (empty(Config::$modSettings['attachment_basedirectories']) ? ['text', 'basedirectory_for_attachments', 40] : ['var_message', 'basedirectory_for_attachments', 'message' => 'basedirectory_for_attachments_path', 'invalid' => empty(Utils::$context['valid_basedirectory']), 'text_label' => (!empty(Utils::$context['valid_basedirectory']) ? Lang::$txt['basedirectory_for_attachments_current'] : sprintf(Lang::$txt['basedirectory_for_attachments_warning'], Config::$scripturl))]), + empty(Config::$modSettings['attachment_basedirectories']) && Config::$modSettings['currentAttachmentUploadDir'] == 1 && count(Config::$modSettings['attachmentUploadDir']) == 1 ? ['var_message', 'attachmentUploadDir_path', 'subtext' => Lang::$txt['attachmentUploadDir_multiple_configure'], 40, 'invalid' => !Utils::$context['valid_upload_dir'], 'text_label' => Lang::$txt['attachmentUploadDir'], 'message' => 'attachmentUploadDir_path'] : ['var_message', 'attach_current_directory', 'subtext' => Lang::$txt['attachmentUploadDir_multiple_configure'], 'message' => 'attachment_path', 'invalid' => empty(Utils::$context['valid_upload_dir']), 'text_label' => (!empty(Utils::$context['valid_upload_dir']) ? Lang::$txt['attach_current_dir'] : sprintf(Lang::$txt['attach_current_dir_warning'], Config::$scripturl))], + ['int', 'attachmentDirFileLimit', 'subtext' => Lang::$txt['zero_for_no_limit'], 6], + ['int', 'attachmentDirSizeLimit', 'subtext' => Lang::$txt['zero_for_no_limit'], 6, 'postinput' => Lang::$txt['kilobyte']], + ['check', 'dont_show_attach_under_post', 'subtext' => Lang::$txt['dont_show_attach_under_post_sub']], '', // Posting limits - array('int', 'attachmentPostLimit', 'subtext' => sprintf(Lang::$txt['attachment_ini_max'], $post_max_kb . ' ' . Lang::$txt['kilobyte']), 6, 'postinput' => Lang::$txt['kilobyte'], 'min' => 1, 'max' => $post_max_kb, 'disabled' => empty($post_max_kb)), - array('int', 'attachmentSizeLimit', 'subtext' => sprintf(Lang::$txt['attachment_ini_max'], $file_max_kb . ' ' . Lang::$txt['kilobyte']), 6, 'postinput' => Lang::$txt['kilobyte'], 'min' => 1, 'max' => $file_max_kb, 'disabled' => empty($file_max_kb)), - array('int', 'attachmentNumPerPostLimit', 'subtext' => Lang::$txt['zero_for_no_limit'], 6, 'min' => 0), + ['int', 'attachmentPostLimit', 'subtext' => sprintf(Lang::$txt['attachment_ini_max'], $post_max_kb . ' ' . Lang::$txt['kilobyte']), 6, 'postinput' => Lang::$txt['kilobyte'], 'min' => 1, 'max' => $post_max_kb, 'disabled' => empty($post_max_kb)], + ['int', 'attachmentSizeLimit', 'subtext' => sprintf(Lang::$txt['attachment_ini_max'], $file_max_kb . ' ' . Lang::$txt['kilobyte']), 6, 'postinput' => Lang::$txt['kilobyte'], 'min' => 1, 'max' => $file_max_kb, 'disabled' => empty($file_max_kb)], + ['int', 'attachmentNumPerPostLimit', 'subtext' => Lang::$txt['zero_for_no_limit'], 6, 'min' => 0], // Security Items - array('title', 'attachment_security_settings'), + ['title', 'attachment_security_settings'], // Extension checks etc. - array('check', 'attachmentCheckExtensions'), - array('text', 'attachmentExtensions', 40), + ['check', 'attachmentCheckExtensions'], + ['text', 'attachmentExtensions', 40], '', // Image checks. - array('warning', empty($testImg) ? 'attachment_img_enc_warning' : ''), - array('check', 'attachment_image_reencode'), + ['warning', empty($testImg) ? 'attachment_img_enc_warning' : ''], + ['check', 'attachment_image_reencode'], '', - array('warning', 'attachment_image_paranoid_warning'), - array('check', 'attachment_image_paranoid'), + ['warning', 'attachment_image_paranoid_warning'], + ['check', 'attachment_image_paranoid'], // Thumbnail settings. - array('title', 'attachment_thumbnail_settings'), - array('check', 'attachmentShowImages'), - array('check', 'attachmentThumbnails'), - array('check', 'attachment_thumb_png'), - array('check', 'attachment_thumb_memory'), - array('warning', 'attachment_thumb_memory_note'), - array('text', 'attachmentThumbWidth', 6), - array('text', 'attachmentThumbHeight', 6), + ['title', 'attachment_thumbnail_settings'], + ['check', 'attachmentShowImages'], + ['check', 'attachmentThumbnails'], + ['check', 'attachment_thumb_png'], + ['check', 'attachment_thumb_memory'], + ['warning', 'attachment_thumb_memory_note'], + ['text', 'attachmentThumbWidth', 6], + ['text', 'attachmentThumbHeight', 6], '', - array('int', 'max_image_width', 'subtext' => Lang::$txt['zero_for_no_limit']), - array('int', 'max_image_height', 'subtext' => Lang::$txt['zero_for_no_limit']), - ); + ['int', 'max_image_width', 'subtext' => Lang::$txt['zero_for_no_limit']], + ['int', 'max_image_height', 'subtext' => Lang::$txt['zero_for_no_limit']], + ]; - IntegrationHook::call('integrate_modify_attachment_settings', array(&$config_vars)); + IntegrationHook::call('integrate_modify_attachment_settings', [&$config_vars]); return $config_vars; } @@ -2376,72 +2290,72 @@ public static function avatarConfigVars(): array Utils::$context['valid_avatar_dir'] = is_dir(Config::$modSettings['avatar_directory']); Utils::$context['valid_custom_avatar_dir'] = !empty(Config::$modSettings['custom_avatar_dir']) && is_dir(Config::$modSettings['custom_avatar_dir']) && is_writable(Config::$modSettings['custom_avatar_dir']); - $config_vars = array( + $config_vars = [ // Server stored avatars! - array('title', 'avatar_server_stored'), - array('warning', empty($testImg) ? 'avatar_img_enc_warning' : ''), - array('permissions', 'profile_server_avatar', 0, Lang::$txt['avatar_server_stored_groups']), - array('warning', !Utils::$context['valid_avatar_dir'] ? 'avatar_directory_wrong' : ''), - array('text', 'avatar_directory', 40, 'invalid' => !Utils::$context['valid_avatar_dir']), - array('text', 'avatar_url', 40), + ['title', 'avatar_server_stored'], + ['warning', empty($testImg) ? 'avatar_img_enc_warning' : ''], + ['permissions', 'profile_server_avatar', 0, Lang::$txt['avatar_server_stored_groups']], + ['warning', !Utils::$context['valid_avatar_dir'] ? 'avatar_directory_wrong' : ''], + ['text', 'avatar_directory', 40, 'invalid' => !Utils::$context['valid_avatar_dir']], + ['text', 'avatar_url', 40], // External avatars? - array('title', 'avatar_external'), - array('permissions', 'profile_remote_avatar', 0, Lang::$txt['avatar_external_url_groups']), - array('check', 'avatar_download_external', 0, 'onchange' => 'fUpdateStatus();'), - array('text', 'avatar_max_width_external', 'subtext' => Lang::$txt['zero_for_no_limit'], 6), - array('text', 'avatar_max_height_external', 'subtext' => Lang::$txt['zero_for_no_limit'], 6), - array('select', 'avatar_action_too_large', - array( + ['title', 'avatar_external'], + ['permissions', 'profile_remote_avatar', 0, Lang::$txt['avatar_external_url_groups']], + ['check', 'avatar_download_external', 0, 'onchange' => 'fUpdateStatus();'], + ['text', 'avatar_max_width_external', 'subtext' => Lang::$txt['zero_for_no_limit'], 6], + ['text', 'avatar_max_height_external', 'subtext' => Lang::$txt['zero_for_no_limit'], 6], + ['select', 'avatar_action_too_large', + [ 'option_refuse' => Lang::$txt['option_refuse'], 'option_css_resize' => Lang::$txt['option_css_resize'], 'option_download_and_resize' => Lang::$txt['option_download_and_resize'], - ), - ), + ], + ], // Uploadable avatars? - array('title', 'avatar_upload'), - array('permissions', 'profile_upload_avatar', 0, Lang::$txt['avatar_upload_groups']), - array('text', 'avatar_max_width_upload', 'subtext' => Lang::$txt['zero_for_no_limit'], 6), - array('text', 'avatar_max_height_upload', 'subtext' => Lang::$txt['zero_for_no_limit'], 6), - array('check', 'avatar_resize_upload', 'subtext' => Lang::$txt['avatar_resize_upload_note']), - array('check', 'avatar_download_png'), - array('check', 'avatar_reencode'), + ['title', 'avatar_upload'], + ['permissions', 'profile_upload_avatar', 0, Lang::$txt['avatar_upload_groups']], + ['text', 'avatar_max_width_upload', 'subtext' => Lang::$txt['zero_for_no_limit'], 6], + ['text', 'avatar_max_height_upload', 'subtext' => Lang::$txt['zero_for_no_limit'], 6], + ['check', 'avatar_resize_upload', 'subtext' => Lang::$txt['avatar_resize_upload_note']], + ['check', 'avatar_download_png'], + ['check', 'avatar_reencode'], '', - array('warning', 'avatar_paranoid_warning'), - array('check', 'avatar_paranoid'), + ['warning', 'avatar_paranoid_warning'], + ['check', 'avatar_paranoid'], '', - array('warning', !Utils::$context['valid_custom_avatar_dir'] ? 'custom_avatar_dir_wrong' : ''), - array('text', 'custom_avatar_dir', 40, 'subtext' => Lang::$txt['custom_avatar_dir_desc'], 'invalid' => !Utils::$context['valid_custom_avatar_dir']), - array('text', 'custom_avatar_url', 40), + ['warning', !Utils::$context['valid_custom_avatar_dir'] ? 'custom_avatar_dir_wrong' : ''], + ['text', 'custom_avatar_dir', 40, 'subtext' => Lang::$txt['custom_avatar_dir_desc'], 'invalid' => !Utils::$context['valid_custom_avatar_dir']], + ['text', 'custom_avatar_url', 40], // Grvatars? - array('title', 'gravatar_settings'), - array('check', 'gravatarEnabled'), - array('check', 'gravatarOverride'), - array('check', 'gravatarAllowExtraEmail'), + ['title', 'gravatar_settings'], + ['check', 'gravatarEnabled'], + ['check', 'gravatarOverride'], + ['check', 'gravatarAllowExtraEmail'], '', - array('select', 'gravatarMaxRating', - array( + ['select', 'gravatarMaxRating', + [ 'G' => Lang::$txt['gravatar_maxG'], 'PG' => Lang::$txt['gravatar_maxPG'], 'R' => Lang::$txt['gravatar_maxR'], 'X' => Lang::$txt['gravatar_maxX'], - ), - ), - array('select', 'gravatarDefault', - array( + ], + ], + ['select', 'gravatarDefault', + [ 'mm' => Lang::$txt['gravatar_mm'], 'identicon' => Lang::$txt['gravatar_identicon'], 'monsterid' => Lang::$txt['gravatar_monsterid'], 'wavatar' => Lang::$txt['gravatar_wavatar'], 'retro' => Lang::$txt['gravatar_retro'], 'blank' => Lang::$txt['gravatar_blank'], - ), - ), - ); + ], + ], + ]; - IntegrationHook::call('integrate_modify_avatar_settings', array(&$config_vars)); + IntegrationHook::call('integrate_modify_avatar_settings', [&$config_vars]); return $config_vars; } @@ -2458,12 +2372,13 @@ public static function avatarConfigVars(): array */ public static function list_getFiles($start, $items_per_page, $sort, $browse_type): array { - $files = array(); + $files = []; // Choose a query depending on what we are viewing. - if ($browse_type === 'avatars') - { - $request = Db::$db->query('', ' + if ($browse_type === 'avatars') { + $request = Db::$db->query( + '', + ' SELECT {string:blank_text} AS id_msg, COALESCE(mem.real_name, {string:not_applicable_text}) AS poster_name, mem.last_login AS poster_time, 0 AS id_topic, a.id_member, a.id_attach, a.filename, a.file_hash, a.attachment_type, @@ -2473,19 +2388,19 @@ public static function list_getFiles($start, $items_per_page, $sort, $browse_typ WHERE a.id_member != {int:guest_id} ORDER BY {raw:sort} LIMIT {int:start}, {int:per_page}', - array( + [ 'guest_id' => 0, 'blank_text' => '', 'not_applicable_text' => Lang::$txt['not_applicable'], 'sort' => $sort, 'start' => $start, 'per_page' => $items_per_page, - ) + ], ); - } - else - { - $request = Db::$db->query('', ' + } else { + $request = Db::$db->query( + '', + ' SELECT m.id_msg, COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.id_topic, m.id_member, a.id_attach, a.filename, a.file_hash, a.attachment_type, a.size, a.width, a.height, a.downloads, mf.subject, t.id_board @@ -2498,17 +2413,17 @@ public static function list_getFiles($start, $items_per_page, $sort, $browse_typ AND a.id_member = {int:guest_id_member} ORDER BY {raw:sort} LIMIT {int:start}, {int:per_page}', - array( + [ 'attachment_type' => $browse_type == 'thumbs' ? '3' : '0', 'guest_id_member' => 0, 'sort' => $sort, 'start' => $start, 'per_page' => $items_per_page, - ) + ], ); } - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $files[] = $row; } Db::$db->free_result($request); @@ -2526,20 +2441,21 @@ public static function list_getFiles($start, $items_per_page, $sort, $browse_typ public static function list_getNumFiles($browse_type): int { // Depending on the type of file, different queries are used. - if ($browse_type === 'avatars') - { - $request = Db::$db->query('', ' + if ($browse_type === 'avatars') { + $request = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}attachments WHERE id_member != {int:guest_id_member}', - array( + [ 'guest_id_member' => 0, - ) + ], ); - } - else - { - $request = Db::$db->query('', ' + } else { + $request = Db::$db->query( + '', + ' SELECT COUNT(*) AS num_attach FROM {db_prefix}attachments AS a INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg) @@ -2547,13 +2463,13 @@ public static function list_getNumFiles($browse_type): int INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg) WHERE a.attachment_type = {int:attachment_type} AND a.id_member = {int:guest_id_member}', - array( + [ 'attachment_type' => $browse_type === 'thumbs' ? '3' : '0', 'guest_id_member' => 0, - ) + ], ); } - list ($num_files) = Db::$db->fetch_row($request); + list($num_files) = Db::$db->fetch_row($request); Db::$db->free_result($request); return $num_files; @@ -2566,31 +2482,34 @@ public static function list_getNumFiles($browse_type): int */ public static function list_getAttachDirs(): array { - $expected_files = array(); - $expected_size = array(); + $expected_files = []; + $expected_size = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_folder, COUNT(id_attach) AS num_attach, SUM(size) AS size_attach FROM {db_prefix}attachments WHERE attachment_type != {int:type} GROUP BY id_folder', - array( + [ 'type' => 1, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $expected_files[$row['id_folder']] = $row['num_attach']; $expected_size[$row['id_folder']] = $row['size_attach']; } Db::$db->free_result($request); - $attachdirs = array(); - foreach (Config::$modSettings['attachmentUploadDir'] as $id => $dir) - { + $attachdirs = []; + + foreach (Config::$modSettings['attachmentUploadDir'] as $id => $dir) { // If there aren't any attachments in this directory this won't exist. - if (!isset($expected_files[$id])) + if (!isset($expected_files[$id])) { $expected_files[$id] = 0; + } // Check if the directory is doing okay. list($status, $error, $files) = attachDirStatus($dir, $expected_files[$id]); @@ -2598,22 +2517,20 @@ public static function list_getAttachDirs(): array // If it is one, let's show that it's a base directory. $sub_dirs = 0; $is_base_dir = false; - if (!empty(Config::$modSettings['attachment_basedirectories'])) - { + + if (!empty(Config::$modSettings['attachment_basedirectories'])) { $is_base_dir = in_array($dir, Config::$modSettings['attachment_basedirectories']); // Count any sub-folders. - foreach (Config::$modSettings['attachmentUploadDir'] as $sid => $sub) - { - if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false) - { + foreach (Config::$modSettings['attachmentUploadDir'] as $sid => $sub) { + if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false) { $expected_files[$id]++; $sub_dirs++; } } } - $attachdirs[] = array( + $attachdirs[] = [ 'id' => $id, 'current' => $id == Config::$modSettings['currentAttachmentUploadDir'], 'disable_current' => isset(Config::$modSettings['automanage_attachments']) && Config::$modSettings['automanage_attachments'] > 1, @@ -2622,20 +2539,19 @@ public static function list_getAttachDirs(): array 'current_size' => !empty($expected_size[$id]) ? Lang::numberFormat($expected_size[$id] / 1024, 0) : 0, 'num_files' => Lang::numberFormat($expected_files[$id] - $sub_dirs, 0) . ($sub_dirs > 0 ? ' (' . $sub_dirs . ')' : ''), 'status' => ($is_base_dir ? Lang::$txt['attach_dir_basedir'] . '
' : '') . ($error ? '
' : '') . sprintf(Lang::$txt['attach_dir_' . $status], Utils::$context['session_id'], Utils::$context['session_var'], Config::$scripturl) . ($error ? '
' : ''), - ); + ]; } // Just stick a new directory on at the bottom. - if (isset($_REQUEST['new_path'])) - { - $attachdirs[] = array( + if (isset($_REQUEST['new_path'])) { + $attachdirs[] = [ 'id' => max(array_merge(array_keys($expected_files), array_keys(Config::$modSettings['attachmentUploadDir']))) + 1, 'current' => false, 'path' => '', 'current_size' => '', 'num_files' => '', 'status' => '', - ); + ]; } return $attachdirs; @@ -2648,54 +2564,48 @@ public static function list_getAttachDirs(): array */ public static function list_getBaseDirs(): array { - if (empty(Config::$modSettings['attachment_basedirectories'])) - return array(); + if (empty(Config::$modSettings['attachment_basedirectories'])) { + return []; + } - $basedirs = array(); + $basedirs = []; // Get a list of the base directories. - foreach (Config::$modSettings['attachment_basedirectories'] as $id => $dir) - { + foreach (Config::$modSettings['attachment_basedirectories'] as $id => $dir) { // Loop through the attach directory array to count any sub-directories $expected_dirs = 0; - foreach (Config::$modSettings['attachmentUploadDir'] as $sid => $sub) - { - if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false) + foreach (Config::$modSettings['attachmentUploadDir'] as $sid => $sub) { + if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false) { $expected_dirs++; + } } - if (!is_dir($dir)) - { + if (!is_dir($dir)) { $status = 'does_not_exist'; - } - elseif (!is_writeable($dir)) - { + } elseif (!is_writeable($dir)) { $status = 'not_writable'; - } - else - { + } else { $status = 'ok'; } - $basedirs[] = array( + $basedirs[] = [ 'id' => $id, 'current' => $dir == Config::$modSettings['basedirectory_for_attachments'], 'path' => $expected_dirs > 0 ? $dir : (''), 'num_dirs' => $expected_dirs, 'status' => $status == 'ok' ? Lang::$txt['attach_dir_ok'] : ('' . Lang::$txt['attach_dir_' . $status] . ''), - ); + ]; } - if (isset($_REQUEST['new_base_path'])) - { - $basedirs[] = array( + if (isset($_REQUEST['new_base_path'])) { + $basedirs[] = [ 'id' => '', 'current' => false, 'path' => '', 'num_dirs' => '', 'status' => '', - ); + ]; } return $basedirs; @@ -2712,36 +2622,40 @@ public static function list_getBaseDirs(): array */ public static function attachDirStatus($dir, $expected_files): array { - if (!is_dir($dir)) - return array('does_not_exist', true, ''); + if (!is_dir($dir)) { + return ['does_not_exist', true, '']; + } - if (!is_writable($dir)) - return array('not_writable', true, ''); + if (!is_writable($dir)) { + return ['not_writable', true, '']; + } // Everything is okay so far, start to scan through the directory. $num_files = 0; $dir_handle = dir($dir); - while ($file = $dir_handle->read()) - { + while ($file = $dir_handle->read()) { // Now do we have a real file here? - if (in_array($file, array('.', '..', '.htaccess', 'index.php'))) + if (in_array($file, ['.', '..', '.htaccess', 'index.php'])) { continue; + } $num_files++; } $dir_handle->close(); - if ($num_files < $expected_files) - return array('files_missing', true, $num_files); + if ($num_files < $expected_files) { + return ['files_missing', true, $num_files]; + } // Empty? - if ($expected_files == 0) - return array('unused', false, $num_files); + if ($expected_files == 0) { + return ['unused', false, $num_files]; + } // All good! - return array('ok', false, $num_files); + return ['ok', false, $num_files]; } /** @@ -2752,8 +2666,9 @@ public static function attachDirStatus($dir, $expected_files): array */ public static function manageAttachmentSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::attachConfigVars(); + } self::load(); self::$obj->subaction = 'attachments'; @@ -2768,8 +2683,9 @@ public static function manageAttachmentSettings($return_config = false) */ public static function manageAvatarSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::avatarConfigVars(); + } self::load(); self::$obj->subaction = 'avatars'; @@ -2882,16 +2798,17 @@ protected function __construct() Theme::loadTemplate('ManageAttachments'); // This uses admin tabs - as it should! - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['attachments_avatars'], 'help' => 'manage_files', 'description' => Lang::$txt['attachments_desc'], - ); + ]; - IntegrationHook::call('integrate_manage_attachments', array(&self::$subactions)); + IntegrationHook::call('integrate_manage_attachments', [&self::$subactions]); - if (!empty($_REQUEST['sa']) && isset(self::$subactions[strtolower($_REQUEST['sa'])])) + if (!empty($_REQUEST['sa']) && isset(self::$subactions[strtolower($_REQUEST['sa'])])) { $this->subaction = strtolower($_REQUEST['sa']); + } Utils::$context['sub_action'] = &$this->subaction; @@ -2915,12 +2832,14 @@ protected function pauseAttachmentMaintenance($to_fix, $max_substep = 0): void // Try get more time... @set_time_limit(600); - if (function_exists('apache_reset_timeout')) + if (function_exists('apache_reset_timeout')) { @apache_reset_timeout(); + } // Have we already used our maximum time? - if ((time() - TIME_START) < 3 || Utils::$context['starting_substep'] == $_GET['substep']) + if ((time() - TIME_START) < 3 || Utils::$context['starting_substep'] == $_GET['substep']) { return; + } Utils::$context['continue_get_data'] = '?action=admin;area=manageattachments;sa=repair' . (isset($_GET['fixErrors']) ? ';fixErrors' : '') . ';step=' . $_GET['step'] . ';substep=' . $_GET['substep'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['page_title'] = Lang::$txt['not_done_title']; @@ -2932,12 +2851,9 @@ protected function pauseAttachmentMaintenance($to_fix, $max_substep = 0): void Menu::$loaded['admin']['current_subsection'] = 'maintenance'; // Change these two if more steps are added! - if (empty($max_substep)) - { + if (empty($max_substep)) { Utils::$context['continue_percent'] = round(($_GET['step'] * 100) / 25); - } - else - { + } else { Utils::$context['continue_percent'] = round(($_GET['step'] * 100 + ($_GET['substep'] * 100) / $max_substep) / 25); } @@ -2955,7 +2871,8 @@ protected function pauseAttachmentMaintenance($to_fix, $max_substep = 0): void class_exists('SMF\\Attachment'); // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Attachments::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Attachments::exportStatic')) { Attachments::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Bans.php b/Sources/Actions/Admin/Bans.php index 05c78273cc..0c4b4b487b 100644 --- a/Sources/Actions/Admin/Bans.php +++ b/Sources/Actions/Admin/Bans.php @@ -17,13 +17,13 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\BackwardCompatibility; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\ErrorHandler; -use SMF\IP; use SMF\IntegrationHook; +use SMF\IP; use SMF\ItemList; use SMF\Lang; use SMF\Logging; @@ -33,7 +33,6 @@ use SMF\Time; use SMF\User; use SMF\Utils; -use SMF\Db\DatabaseApi as Db; /** * This class contains all the methods used for the ban center. @@ -47,8 +46,8 @@ class Bans implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'Ban', 'updateBanMembers' => 'updateBanMembers', 'list_getBans' => 'list_getBans', @@ -64,8 +63,8 @@ class Bans implements ActionInterface 'banBrowseTriggers' => 'BanBrowseTriggers', 'banEditTrigger' => 'BanEditTrigger', 'banLog' => 'BanLog', - ), - ); + ], + ]; /******************* * Public properties @@ -88,14 +87,14 @@ class Bans implements ActionInterface * * Available sub-actions. */ - public static array $subactions = array( + public static array $subactions = [ 'list' => 'list', 'edit' => 'edit', 'add' => 'edit', 'browse' => 'browseTriggers', 'edittrigger' => 'editTrigger', 'log' => 'log', - ); + ]; /**************************** * Internal static properties @@ -120,10 +119,11 @@ public function execute(): void { User::$me->isAllowedTo('manage_bans'); - $call = method_exists($this, self::$subactions[$this->subaction]) ? array($this, self::$subactions[$this->subaction]) : Utils::getCallable(self::$subactions[$this->subaction]); + $call = method_exists($this, self::$subactions[$this->subaction]) ? [$this, self::$subactions[$this->subaction]] : Utils::getCallable(self::$subactions[$this->subaction]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } /** @@ -137,8 +137,7 @@ public function execute(): void public function list(): void { // User pressed the 'remove selection button'. - if (!empty($_POST['removeBans']) && !empty($_POST['remove']) && is_array($_POST['remove'])) - { + if (!empty($_POST['removeBans']) && !empty($_POST['remove']) && is_array($_POST['remove'])) { User::$me->checkSession(); // Make sure every entry is a proper integer. @@ -148,179 +147,173 @@ public function list(): void $this->removeBanGroups($_POST['remove']); // No more caching this ban! - Config::updateModSettings(array('banLastUpdated' => time())); + Config::updateModSettings(['banLastUpdated' => time()]); // Some members might be unbanned now. Update the members table. self::updateBanMembers(); } // Create a date string so we don't overload them with date info. - if (preg_match('~%[AaBbCcDdeGghjmuYy](?:[^%]*%[AaBbCcDdeGghjmuYy])*~', User::$me->time_format, $matches) == 0 || empty($matches[0])) - { + if (preg_match('~%[AaBbCcDdeGghjmuYy](?:[^%]*%[AaBbCcDdeGghjmuYy])*~', User::$me->time_format, $matches) == 0 || empty($matches[0])) { Utils::$context['ban_time_format'] = User::$me->time_format; - } - else - { + } else { Utils::$context['ban_time_format'] = $matches[0]; } - $listOptions = array( + $listOptions = [ 'id' => 'ban_list', 'title' => Lang::$txt['ban_title'], 'items_per_page' => Config::$modSettings['defaultMaxListItems'], 'base_href' => Config::$scripturl . '?action=admin;area=ban;sa=list', 'default_sort_col' => 'added', 'default_sort_dir' => 'desc', - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getBans', - ), - 'get_count' => array( + ], + 'get_count' => [ 'function' => __CLASS__ . '::list_getNumBans', - ), + ], 'no_items_label' => Lang::$txt['ban_no_entries'], - 'columns' => array( - 'name' => array( - 'header' => array( + 'columns' => [ + 'name' => [ + 'header' => [ 'value' => Lang::$txt['ban_name'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'name', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'bg.name', 'reverse' => 'bg.name DESC', - ), - ), - 'notes' => array( - 'header' => array( + ], + ], + 'notes' => [ + 'header' => [ 'value' => Lang::$txt['ban_notes'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'notes', 'class' => 'smalltext word_break', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'LENGTH(bg.notes) > 0 DESC, bg.notes', 'reverse' => 'LENGTH(bg.notes) > 0, bg.notes DESC', - ), - ), - 'reason' => array( - 'header' => array( + ], + ], + 'reason' => [ + 'header' => [ 'value' => Lang::$txt['ban_reason'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'reason', 'class' => 'smalltext word_break', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'LENGTH(bg.reason) > 0 DESC, bg.reason', 'reverse' => 'LENGTH(bg.reason) > 0, bg.reason DESC', - ), - ), - 'added' => array( - 'header' => array( + ], + ], + 'added' => [ + 'header' => [ 'value' => Lang::$txt['ban_added'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { $time = new Time('@' . $rowData['ban_time']); - if (empty(Utils::$context['ban_time_format'])) + if (empty(Utils::$context['ban_time_format'])) { return $time->format(); + } return $time->format(Utils::$context['ban_time_format'], true); }, - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'bg.ban_time', 'reverse' => 'bg.ban_time DESC', - ), - ), - 'expires' => array( - 'header' => array( + ], + ], + 'expires' => [ + 'header' => [ 'value' => Lang::$txt['ban_expires'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { // This ban never expires...whahaha. - if ($rowData['expire_time'] === null) - { + if ($rowData['expire_time'] === null) { return Lang::$txt['never']; } // This ban has already expired. - if ($rowData['expire_time'] < time()) - { + if ($rowData['expire_time'] < time()) { return sprintf('%1$s', Lang::$txt['ban_expired']); } // Still need to wait a few days for this ban to expire. return sprintf('%1$d %2$s', ceil(($rowData['expire_time'] - time()) / (60 * 60 * 24)), Lang::$txt['ban_days']); }, - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'COALESCE(bg.expire_time, 1=1) DESC, bg.expire_time DESC', 'reverse' => 'COALESCE(bg.expire_time, 1=1), bg.expire_time', - ), - ), - 'num_triggers' => array( - 'header' => array( + ], + ], + 'num_triggers' => [ + 'header' => [ 'value' => Lang::$txt['ban_triggers'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'num_triggers', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'num_triggers DESC', 'reverse' => 'num_triggers', - ), - ), - 'actions' => array( - 'header' => array( + ], + ], + 'actions' => [ + 'header' => [ 'value' => Lang::$txt['ban_actions'], 'class' => 'centercol', - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '' . Lang::$txt['modify'] . '', - 'params' => array( + 'params' => [ 'id_ban_group' => false, - ), - ), + ], + ], 'class' => 'centercol', - ), - ), - 'check' => array( - 'header' => array( + ], + ], + 'check' => [ + 'header' => [ 'value' => '', 'class' => 'centercol', - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '', - 'params' => array( + 'params' => [ 'id_ban_group' => false, - ), - ), + ], + ], 'class' => 'centercol', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=ban;sa=list', - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'top_of_list', 'value' => '', - ), - array( + ], + [ 'position' => 'bottom_of_list', 'value' => '', - ), - ), + ], + ], 'javascript' => ' var removeBans = $("input[name=\'removeBans\']"); @@ -336,7 +329,7 @@ public function list(): void return confirm("' . Lang::$txt['ban_remove_selected_confirm'] . '"); });', - ); + ]; new ItemList($listOptions); @@ -356,12 +349,11 @@ public function list(): void */ public function edit(): void { - if ((isset($_POST['add_ban']) || isset($_POST['modify_ban']) || isset($_POST['remove_selection'])) && empty(Utils::$context['ban_errors'])) - { + if ((isset($_POST['add_ban']) || isset($_POST['modify_ban']) || isset($_POST['remove_selection'])) && empty(Utils::$context['ban_errors'])) { $this->edit2(); } - $ban_group_id = isset(Utils::$context['ban']['id']) ? Utils::$context['ban']['id'] : (isset($_REQUEST['bg']) ? (int) $_REQUEST['bg'] : 0); + $ban_group_id = Utils::$context['ban']['id'] ?? (isset($_REQUEST['bg']) ? (int) $_REQUEST['bg'] : 0); // Template needs this to show errors using javascript Lang::load('Errors'); @@ -370,129 +362,122 @@ public function edit(): void Utils::$context['form_url'] = Config::$scripturl . '?action=admin;area=ban;sa=edit'; - if (!empty(Utils::$context['ban_errors'])) - { - foreach (Utils::$context['ban_errors'] as $error) + if (!empty(Utils::$context['ban_errors'])) { + foreach (Utils::$context['ban_errors'] as $error) { Utils::$context['error_messages'][$error] = Lang::$txt[$error]; - } - else - { + } + } else { // If we're editing an existing ban, get it from the database. - if (!empty($ban_group_id)) - { + if (!empty($ban_group_id)) { Utils::$context['ban_group_id'] = $ban_group_id; - $listOptions = array( + $listOptions = [ 'id' => 'ban_items', 'base_href' => Config::$scripturl . '?action=admin;area=ban;sa=edit;bg=' . $ban_group_id, 'no_items_label' => Lang::$txt['ban_no_triggers'], 'items_per_page' => Config::$modSettings['defaultMaxListItems'], - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getBanItems', - 'params' => array( + 'params' => [ 'ban_group_id' => $ban_group_id, - ), - ), - 'get_count' => array( + ], + ], + 'get_count' => [ 'function' => __CLASS__ . '::list_getNumBanItems', - 'params' => array( + 'params' => [ 'ban_group_id' => $ban_group_id, - ), - ), - 'columns' => array( - 'type' => array( - 'header' => array( + ], + ], + 'columns' => [ + 'type' => [ + 'header' => [ 'value' => Lang::$txt['ban_banned_entity'], 'style' => 'width: 60%;text-align: left;', - ), - 'data' => array( - 'function' => function($ban_item) - { - if (in_array($ban_item['type'], array('ip', 'hostname', 'email'))) - { + ], + 'data' => [ + 'function' => function ($ban_item) { + if (in_array($ban_item['type'], ['ip', 'hostname', 'email'])) { return '' . Lang::$txt[$ban_item['type']] . ': ' . $ban_item[$ban_item['type']]; } - if ($ban_item['type'] == 'user') - { + if ($ban_item['type'] == 'user') { return '' . Lang::$txt['username'] . ': ' . $ban_item['user']['link']; } return '' . Lang::$txt['unknown'] . ': ' . $ban_item['no_bantype_selected']; }, 'style' => 'text-align: left;', - ), - ), - 'hits' => array( - 'header' => array( + ], + ], + 'hits' => [ + 'header' => [ 'value' => Lang::$txt['ban_hits'], 'style' => 'width: 15%; text-align: center;', - ), - 'data' => array( + ], + 'data' => [ 'db' => 'hits', 'style' => 'text-align: center;', - ), - ), - 'id' => array( - 'header' => array( + ], + ], + 'id' => [ + 'header' => [ 'value' => Lang::$txt['ban_actions'], 'style' => 'width: 15%; text-align: center;', - ), - 'data' => array( - 'function' => function($ban_item) - { + ], + 'data' => [ + 'function' => function ($ban_item) { return '' . Lang::$txt['ban_edit_trigger'] . ''; }, 'style' => 'text-align: center;', - ), - ), - 'checkboxes' => array( - 'header' => array( + ], + ], + 'checkboxes' => [ + 'header' => [ 'value' => '', 'style' => 'width: 5%; text-align: center;', - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '', - 'params' => array( + 'params' => [ 'id' => false, - ), - ), + ], + ], 'style' => 'text-align: center;', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=ban;sa=edit;bg=' . $ban_group_id, - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'above_column_headers', 'value' => ' ' . Lang::$txt['ban_add_trigger'] . '', 'style' => 'text-align: right;', - ), - array( + ], + [ 'position' => 'above_column_headers', 'value' => ' ', - ), - array( + ], + [ 'position' => 'below_table_data', 'value' => ' ' . Lang::$txt['ban_add_trigger'] . '', 'style' => 'text-align: right;', - ), - array( + ], + [ 'position' => 'below_table_data', 'value' => ' ', - ), - ), + ], + ], 'javascript' => ' var removeBans = $("input[name=\'remove_selection\']"); @@ -508,64 +493,63 @@ public function edit(): void return confirm("' . Lang::$txt['ban_remove_selected_confirm'] . '"); });', - ); + ]; - IntegrationHook::call('integrate_ban_edit_list', array(&$listOptions)); + IntegrationHook::call('integrate_ban_edit_list', [&$listOptions]); new ItemList($listOptions); } // Not an existing one, then it's probably a new one. - else - { - Utils::$context['ban'] = array( + else { + Utils::$context['ban'] = [ 'id' => 0, 'name' => '', - 'expiration' => array( + 'expiration' => [ 'status' => 'never', - 'days' => 0 - ), + 'days' => 0, + ], 'reason' => '', 'notes' => '', 'ban_days' => 0, - 'cannot' => array( + 'cannot' => [ 'access' => true, 'post' => false, 'register' => false, 'login' => false, - ), + ], 'is_new' => true, - ); - Utils::$context['ban_suggestions'] = array( + ]; + Utils::$context['ban_suggestions'] = [ 'main_ip' => '', 'hostname' => '', 'email' => '', - 'member' => array( + 'member' => [ 'id' => 0, - ), - ); + ], + ]; // Overwrite some of the default form values if a user ID was given. - if (!empty($_REQUEST['u'])) - { - $request = Db::$db->query('', ' + if (!empty($_REQUEST['u'])) { + $request = Db::$db->query( + '', + ' SELECT id_member, real_name, member_ip, email_address FROM {db_prefix}members WHERE id_member = {int:current_user} LIMIT 1', - array( + [ 'current_user' => (int) $_REQUEST['u'], - ) + ], ); - if (Db::$db->num_rows($request) > 0) - { + + if (Db::$db->num_rows($request) > 0) { list(Utils::$context['ban_suggestions']['member']['id'], Utils::$context['ban_suggestions']['member']['name'], Utils::$context['ban_suggestions']['main_ip'], Utils::$context['ban_suggestions']['email']) = Db::$db->fetch_row($request); Utils::$context['ban_suggestions']['main_ip'] = new IP(Utils::$context['ban_suggestions']['main_ip']); } Db::$db->free_result($request); - if (!empty(Utils::$context['ban_suggestions']['member']['id'])) - { + if (!empty(Utils::$context['ban_suggestions']['member']['id'])) { Utils::$context['ban_suggestions']['href'] = Config::$scripturl . '?action=profile;u=' . Utils::$context['ban_suggestions']['member']['id']; Utils::$context['ban_suggestions']['member']['link'] = '' . Utils::$context['ban_suggestions']['member']['name'] . ''; @@ -582,8 +566,7 @@ public function edit(): void if ( empty(Config::$modSettings['disableHostnameLookup']) && $main_ip->isValid() - ) - { + ) { Utils::$context['ban_suggestions']['hostname'] = $main_ip->getHost(); } @@ -591,19 +574,20 @@ public function edit(): void } } // We came from the mod center. - elseif (isset($_GET['msg']) && !empty($_GET['msg'])) - { - $request = Db::$db->query('', ' + elseif (isset($_GET['msg']) && !empty($_GET['msg'])) { + $request = Db::$db->query( + '', + ' SELECT poster_name, poster_ip, poster_email FROM {db_prefix}messages WHERE id_msg = {int:message} LIMIT 1', - array( + [ 'message' => (int) $_REQUEST['msg'], - ) + ], ); - if (Db::$db->num_rows($request) > 0) - { + + if (Db::$db->num_rows($request) > 0) { list(Utils::$context['ban_suggestions']['member']['name'], Utils::$context['ban_suggestions']['main_ip'], Utils::$context['ban_suggestions']['email']) = Db::$db->fetch_row($request); Utils::$context['ban_suggestions']['main_ip'] = new IP(Utils::$context['ban_suggestions']['main_ip']); @@ -616,11 +600,11 @@ public function edit(): void Utils::$context['ban']['from_user'] = true; } - IntegrationHook::call('integrate_ban_edit_new', array()); + IntegrationHook::call('integrate_ban_edit_new', []); } } - Theme::loadJavaScriptFile('suggest.js', array('minimize' => true), 'smf_suggest'); + Theme::loadJavaScriptFile('suggest.js', ['minimize' => true], 'smf_suggest'); Utils::$context['sub_template'] = 'ban_edit'; } @@ -634,165 +618,155 @@ public function edit(): void */ public function browseTriggers(): void { - if (!empty($_POST['remove_triggers']) && !empty($_POST['remove']) && is_array($_POST['remove'])) - { + if (!empty($_POST['remove_triggers']) && !empty($_POST['remove']) && is_array($_POST['remove'])) { User::$me->checkSession(); self::removeBanTriggers($_POST['remove']); // Rehabilitate some members. - if ($_REQUEST['entity'] == 'member') + if ($_REQUEST['entity'] == 'member') { self::updateBanMembers(); + } // Make sure the ban cache is refreshed. - Config::updateModSettings(array('banLastUpdated' => time())); + Config::updateModSettings(['banLastUpdated' => time()]); } - Utils::$context['selected_entity'] = isset($_REQUEST['entity']) && in_array($_REQUEST['entity'], array('ip', 'hostname', 'email', 'member')) ? $_REQUEST['entity'] : 'ip'; + Utils::$context['selected_entity'] = isset($_REQUEST['entity']) && in_array($_REQUEST['entity'], ['ip', 'hostname', 'email', 'member']) ? $_REQUEST['entity'] : 'ip'; - $listOptions = array( + $listOptions = [ 'id' => 'ban_trigger_list', 'title' => Lang::$txt['ban_trigger_browse'], 'items_per_page' => Config::$modSettings['defaultMaxListItems'], 'base_href' => Config::$scripturl . '?action=admin;area=ban;sa=browse;entity=' . Utils::$context['selected_entity'], 'default_sort_col' => 'banned_entity', 'no_items_label' => Lang::$txt['ban_no_triggers'], - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getBanTriggers', - 'params' => array( + 'params' => [ Utils::$context['selected_entity'], - ), - ), - 'get_count' => array( + ], + ], + 'get_count' => [ 'function' => __CLASS__ . '::list_getNumBanTriggers', - 'params' => array( + 'params' => [ Utils::$context['selected_entity'], - ), - ), - 'columns' => array( - 'banned_entity' => array( - 'header' => array( + ], + ], + 'columns' => [ + 'banned_entity' => [ + 'header' => [ 'value' => Lang::$txt['ban_banned_entity'], - ), - ), - 'ban_name' => array( - 'header' => array( + ], + ], + 'ban_name' => [ + 'header' => [ 'value' => Lang::$txt['ban_name'], - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '%2$s', - 'params' => array( + 'params' => [ 'id_ban_group' => false, 'name' => false, - ), - ), - ), - 'sort' => array( + ], + ], + ], + 'sort' => [ 'default' => 'bg.name', 'reverse' => 'bg.name DESC', - ), - ), - 'hits' => array( - 'header' => array( + ], + ], + 'hits' => [ + 'header' => [ 'value' => Lang::$txt['ban_hits'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'hits', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'bi.hits DESC', 'reverse' => 'bi.hits', - ), - ), - 'check' => array( - 'header' => array( + ], + ], + 'check' => [ + 'header' => [ 'value' => '', 'class' => 'centercol', - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '', - 'params' => array( + 'params' => [ 'id_ban' => false, - ), - ), + ], + ], 'class' => 'centercol', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=ban;sa=browse;entity=' . Utils::$context['selected_entity'], 'include_start' => true, 'include_sort' => true, - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'above_column_headers', 'value' => '' . (Utils::$context['selected_entity'] == 'ip' ? '> ' : '') . Lang::$txt['ip'] . ' | ' . (Utils::$context['selected_entity'] == 'hostname' ? '> ' : '') . Lang::$txt['hostname'] . ' | ' . (Utils::$context['selected_entity'] == 'email' ? '> ' : '') . Lang::$txt['email'] . ' | ' . (Utils::$context['selected_entity'] == 'member' ? '> ' : '') . Lang::$txt['username'] . '', - ), - array( + ], + [ 'position' => 'bottom_of_list', 'value' => '', - ), - ), - ); + ], + ], + ]; // Specific data for the first column depending on the selected entity. - if (Utils::$context['selected_entity'] === 'ip') - { - $listOptions['columns']['banned_entity']['data'] = array( - 'function' => function($rowData) - { + if (Utils::$context['selected_entity'] === 'ip') { + $listOptions['columns']['banned_entity']['data'] = [ + 'function' => function ($rowData) { return IP::range2ip($rowData['ip_low'], $rowData['ip_high']); }, - ); - $listOptions['columns']['banned_entity']['sort'] = array( + ]; + $listOptions['columns']['banned_entity']['sort'] = [ 'default' => 'bi.ip_low, bi.ip_high, bi.ip_low', 'reverse' => 'bi.ip_low DESC, bi.ip_high DESC', - ); - } - elseif (Utils::$context['selected_entity'] === 'hostname') - { - $listOptions['columns']['banned_entity']['data'] = array( - 'function' => function($rowData) - { - return strtr(Utils::htmlspecialchars($rowData['hostname']), array('%' => '*')); + ]; + } elseif (Utils::$context['selected_entity'] === 'hostname') { + $listOptions['columns']['banned_entity']['data'] = [ + 'function' => function ($rowData) { + return strtr(Utils::htmlspecialchars($rowData['hostname']), ['%' => '*']); }, - ); - $listOptions['columns']['banned_entity']['sort'] = array( + ]; + $listOptions['columns']['banned_entity']['sort'] = [ 'default' => 'bi.hostname', 'reverse' => 'bi.hostname DESC', - ); - } - elseif (Utils::$context['selected_entity'] === 'email') - { - $listOptions['columns']['banned_entity']['data'] = array( - 'function' => function($rowData) - { - return strtr(Utils::htmlspecialchars($rowData['email_address']), array('%' => '*')); + ]; + } elseif (Utils::$context['selected_entity'] === 'email') { + $listOptions['columns']['banned_entity']['data'] = [ + 'function' => function ($rowData) { + return strtr(Utils::htmlspecialchars($rowData['email_address']), ['%' => '*']); }, - ); - $listOptions['columns']['banned_entity']['sort'] = array( + ]; + $listOptions['columns']['banned_entity']['sort'] = [ 'default' => 'bi.email_address', 'reverse' => 'bi.email_address DESC', - ); - } - elseif (Utils::$context['selected_entity'] === 'member') - { - $listOptions['columns']['banned_entity']['data'] = array( - 'sprintf' => array( + ]; + } elseif (Utils::$context['selected_entity'] === 'member') { + $listOptions['columns']['banned_entity']['data'] = [ + 'sprintf' => [ 'format' => '%2$s', - 'params' => array( + 'params' => [ 'id_member' => false, 'real_name' => false, - ), - ), - ); - $listOptions['columns']['banned_entity']['sort'] = array( + ], + ], + ]; + $listOptions['columns']['banned_entity']['sort'] = [ 'default' => 'mem.real_name', 'reverse' => 'mem.real_name DESC', - ); + ]; } // Create the list. @@ -823,57 +797,52 @@ public function editTrigger(): void $ban_group = (int) ($_REQUEST['bg'] ?? 0); $ban_id = (int) ($_REQUEST['bi'] ?? 0); - if (empty($ban_group)) + if (empty($ban_group)) { ErrorHandler::fatalLang('ban_not_found', false); + } - if (isset($_POST['add_new_trigger']) && !empty($_POST['ban_suggestions'])) - { + if (isset($_POST['add_new_trigger']) && !empty($_POST['ban_suggestions'])) { $this->saveTriggers($_POST['ban_suggestions'], $ban_group, 0, $ban_id); Utils::redirectexit('action=admin;area=ban;sa=edit' . (!empty($ban_group) ? ';bg=' . $ban_group : '')); - } - elseif (isset($_POST['edit_trigger']) && !empty($_POST['ban_suggestions'])) - { + } elseif (isset($_POST['edit_trigger']) && !empty($_POST['ban_suggestions'])) { $this->saveTriggers($_POST['ban_suggestions'], $ban_group, 0, $ban_id); Utils::redirectexit('action=admin;area=ban;sa=edit' . (!empty($ban_group) ? ';bg=' . $ban_group : '')); - } - elseif (isset($_POST['edit_trigger'])) - { + } elseif (isset($_POST['edit_trigger'])) { self::removeBanTriggers($ban_id); Utils::redirectexit('action=admin;area=ban;sa=edit' . (!empty($ban_group) ? ';bg=' . $ban_group : '')); } - Theme::loadJavaScriptFile('suggest.js', array('minimize' => true), 'smf_suggest'); + Theme::loadJavaScriptFile('suggest.js', ['minimize' => true], 'smf_suggest'); - if (empty($ban_id)) - { - Utils::$context['ban_trigger'] = array( + if (empty($ban_id)) { + Utils::$context['ban_trigger'] = [ 'id' => 0, 'group' => $ban_group, - 'ip' => array( + 'ip' => [ 'value' => '', 'selected' => true, - ), - 'hostname' => array( + ], + 'hostname' => [ 'selected' => false, 'value' => '', - ), - 'email' => array( + ], + 'email' => [ 'value' => '', 'selected' => false, - ), - 'banneduser' => array( + ], + 'banneduser' => [ 'value' => '', 'selected' => false, - ), + ], 'is_new' => true, - ); - } - else - { - $request = Db::$db->query('', ' + ]; + } else { + $request = Db::$db->query( + '', + ' SELECT bi.id_ban, bi.id_ban_group, bi.hostname, bi.email_address, bi.id_member, bi.ip_low, bi.ip_high, @@ -883,39 +852,39 @@ public function editTrigger(): void WHERE bi.id_ban = {int:ban_item} AND bi.id_ban_group = {int:ban_group} LIMIT 1', - array( + [ 'ban_item' => $ban_id, 'ban_group' => $ban_group, - ) + ], ); - if (Db::$db->num_rows($request) == 0) - { + + if (Db::$db->num_rows($request) == 0) { ErrorHandler::fatalLang('ban_not_found', false); } $row = Db::$db->fetch_assoc($request); Db::$db->free_result($request); - Utils::$context['ban_trigger'] = array( + Utils::$context['ban_trigger'] = [ 'id' => $row['id_ban'], 'group' => $row['id_ban_group'], - 'ip' => array( + 'ip' => [ 'value' => empty($row['ip_low']) ? '' : IP::range2ip($row['ip_low'], $row['ip_high']), 'selected' => !empty($row['ip_low']), - ), - 'hostname' => array( + ], + 'hostname' => [ 'value' => str_replace('%', '*', $row['hostname']), 'selected' => !empty($row['hostname']), - ), - 'email' => array( + ], + 'email' => [ 'value' => str_replace('%', '*', $row['email_address']), - 'selected' => !empty($row['email_address']) - ), - 'banneduser' => array( + 'selected' => !empty($row['email_address']), + ], + 'banneduser' => [ 'value' => $row['member_name'], - 'selected' => !empty($row['member_name']) - ), + 'selected' => !empty($row['member_name']), + ], 'is_new' => false, - ); + ]; } SecurityToken::create('admin-bet'); @@ -932,136 +901,132 @@ public function editTrigger(): void public function log(): void { // Delete one or more entries. - if (!empty($_POST['removeAll']) || (!empty($_POST['removeSelected']) && !empty($_POST['remove']))) - { + if (!empty($_POST['removeAll']) || (!empty($_POST['removeSelected']) && !empty($_POST['remove']))) { User::$me->checkSession(); SecurityToken::validate('admin-bl'); // 'Delete all entries' button was pressed. - if (!empty($_POST['removeAll'])) - { + if (!empty($_POST['removeAll'])) { $this->removeBanLogs(); } // 'Delete selection' button was pressed. - else - { + else { $this->removeBanLogs(array_map('intval', $_POST['remove'])); } } - $listOptions = array( + $listOptions = [ 'id' => 'ban_log', 'title' => Lang::$txt['ban_log'], 'items_per_page' => Config::$modSettings['defaultMaxListItems'], 'base_href' => Utils::$context['admin_area'] == 'ban' ? Config::$scripturl . '?action=admin;area=ban;sa=log' : Config::$scripturl . '?action=admin;area=logs;sa=banlog', 'default_sort_col' => 'date', - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getBanLogEntries', - ), - 'get_count' => array( + ], + 'get_count' => [ 'function' => __CLASS__ . '::list_getNumBanLogEntries', - ), + ], 'no_items_label' => Lang::$txt['ban_log_no_entries'], - 'columns' => array( - 'ip' => array( - 'header' => array( + 'columns' => [ + 'ip' => [ + 'header' => [ 'value' => Lang::$txt['ban_log_ip'], - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '%1$s', - 'params' => array( + 'params' => [ 'ip' => false, - ), - ), - ), - 'sort' => array( + ], + ], + ], + 'sort' => [ 'default' => 'lb.ip', 'reverse' => 'lb.ip DESC', - ), - ), - 'email' => array( - 'header' => array( + ], + ], + 'email' => [ + 'header' => [ 'value' => Lang::$txt['ban_log_email'], - ), - 'data' => array( + ], + 'data' => [ 'db_htmlsafe' => 'email', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'lb.email = \'\', lb.email', 'reverse' => 'lb.email != \'\', lb.email DESC', - ), - ), - 'member' => array( - 'header' => array( + ], + ], + 'member' => [ + 'header' => [ 'value' => Lang::$txt['ban_log_member'], - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '%2$s', - 'params' => array( + 'params' => [ 'id_member' => false, 'real_name' => false, - ), - ), - ), - 'sort' => array( + ], + ], + ], + 'sort' => [ 'default' => 'COALESCE(mem.real_name, 1=1), mem.real_name', 'reverse' => 'COALESCE(mem.real_name, 1=1) DESC, mem.real_name DESC', - ), - ), - 'date' => array( - 'header' => array( + ], + ], + 'date' => [ + 'header' => [ 'value' => Lang::$txt['ban_log_date'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return timeformat($rowData['log_time']); }, - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'lb.log_time DESC', 'reverse' => 'lb.log_time', - ), - ), - 'check' => array( - 'header' => array( + ], + ], + 'check' => [ + 'header' => [ 'value' => '', 'class' => 'centercol', - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '', - 'params' => array( + 'params' => [ 'id_ban_log' => false, - ), - ), + ], + ], 'class' => 'centercol', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Utils::$context['admin_area'] == 'ban' ? Config::$scripturl . '?action=admin;area=ban;sa=log' : Config::$scripturl . '?action=admin;area=logs;sa=banlog', 'include_start' => true, 'include_sort' => true, 'token' => 'admin-bl', - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'after_title', 'value' => ' ', - ), - array( + ], + [ 'position' => 'bottom_of_list', 'value' => ' ', - ), - ), - ); + ], + ], + ]; SecurityToken::create('admin-bl'); @@ -1083,8 +1048,9 @@ public function log(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -1104,43 +1070,42 @@ public static function call(): void */ public static function updateBanMembers(): void { - $updates = array(); - $allMembers = array(); - $newMembers = array(); + $updates = []; + $allMembers = []; + $newMembers = []; // Start by getting all active bans - it's quicker doing this in parts... - $memberIDs = array(); - $memberEmails = array(); - $memberEmailWild = array(); + $memberIDs = []; + $memberEmails = []; + $memberEmailWild = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT bi.id_member, bi.email_address FROM {db_prefix}ban_items AS bi INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group) WHERE (bi.id_member > {int:no_member} OR bi.email_address != {string:blank_string}) AND bg.cannot_access = {int:cannot_access_on} AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})', - array( + [ 'no_member' => 0, 'cannot_access_on' => 1, 'current_time' => time(), 'blank_string' => '', - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { - if ($row['id_member']) + + while ($row = Db::$db->fetch_assoc($request)) { + if ($row['id_member']) { $memberIDs[$row['id_member']] = $row['id_member']; + } - if ($row['email_address']) - { + if ($row['email_address']) { // Does it have a wildcard - if so we can't do a IN on it. - if (strpos($row['email_address'], '%') !== false) - { + if (strpos($row['email_address'], '%') !== false) { $memberEmailWild[$row['email_address']] = $row['email_address']; - } - else - { + } else { $memberEmails[$row['email_address']] = $row['email_address']; } } @@ -1148,46 +1113,43 @@ public static function updateBanMembers(): void Db::$db->free_result($request); // Build up the query. - $queryPart = array(); - $queryValues = array(); + $queryPart = []; + $queryValues = []; - if (!empty($memberIDs)) - { + if (!empty($memberIDs)) { $queryPart[] = 'mem.id_member IN ({array_string:member_ids})'; $queryValues['member_ids'] = $memberIDs; } - if (!empty($memberEmails)) - { + if (!empty($memberEmails)) { $queryPart[] = 'mem.email_address IN ({array_string:member_emails})'; $queryValues['member_emails'] = $memberEmails; } $count = 0; - foreach ($memberEmailWild as $email) - { + + foreach ($memberEmailWild as $email) { $queryPart[] = 'mem.email_address LIKE {string:wild_' . $count . '}'; $queryValues['wild_' . $count++] = $email; } // Find all banned members. - if (!empty($queryPart)) - { - $request = Db::$db->query('', ' + if (!empty($queryPart)) { + $request = Db::$db->query( + '', + ' SELECT mem.id_member, mem.is_activated FROM {db_prefix}members AS mem WHERE ' . implode(' OR ', $queryPart), - $queryValues + $queryValues, ); - while ($row = Db::$db->fetch_assoc($request)) - { - if (!in_array($row['id_member'], $allMembers)) - { + + while ($row = Db::$db->fetch_assoc($request)) { + if (!in_array($row['id_member'], $allMembers)) { $allMembers[] = $row['id_member']; // Do they need an update? - if ($row['is_activated'] < 10) - { + if ($row['is_activated'] < 10) { $updates[($row['is_activated'] + 10)][] = $row['id_member']; $newMembers[] = $row['id_member']; } @@ -1197,46 +1159,48 @@ public static function updateBanMembers(): void } // We welcome our new members in the realm of the banned. - if (!empty($newMembers)) - { - Db::$db->query('', ' + if (!empty($newMembers)) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}log_online WHERE id_member IN ({array_int:new_banned_members})', - array( + [ 'new_banned_members' => $newMembers, - ) + ], ); } // Find members that are wrongfully marked as banned. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT mem.id_member, mem.is_activated - 10 AS new_value FROM {db_prefix}members AS mem LEFT JOIN {db_prefix}ban_items AS bi ON (bi.id_member = mem.id_member OR mem.email_address LIKE bi.email_address) LEFT JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group AND bg.cannot_access = {int:cannot_access_activated} AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})) WHERE (bi.id_ban IS NULL OR bg.id_ban_group IS NULL) AND mem.is_activated >= {int:ban_flag}', - array( + [ 'cannot_access_activated' => 1, 'current_time' => time(), 'ban_flag' => 10, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { // Don't do this twice! - if (!in_array($row['id_member'], $allMembers)) - { + if (!in_array($row['id_member'], $allMembers)) { $updates[$row['new_value']][] = $row['id_member']; $allMembers[] = $row['id_member']; } } Db::$db->free_result($request); - if (!empty($updates)) - { - foreach ($updates as $newStatus => $members) - User::updateMemberData($members, array('is_activated' => $newStatus)); + if (!empty($updates)) { + foreach ($updates as $newStatus => $members) { + User::updateMemberData($members, ['is_activated' => $newStatus]); + } } // Update the latest member and our total members as banning may change them. @@ -1253,23 +1217,25 @@ public static function updateBanMembers(): void */ public static function list_getBans($start, $items_per_page, $sort): array { - $bans = array(); + $bans = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT bg.id_ban_group, bg.name, bg.ban_time, bg.expire_time, bg.reason, bg.notes, COUNT(bi.id_ban) AS num_triggers FROM {db_prefix}ban_groups AS bg LEFT JOIN {db_prefix}ban_items AS bi ON (bi.id_ban_group = bg.id_ban_group) GROUP BY bg.id_ban_group, bg.name, bg.ban_time, bg.expire_time, bg.reason, bg.notes ORDER BY {raw:sort} LIMIT {int:offset}, {int:limit}', - array( + [ 'sort' => $sort, 'offset' => $start, 'limit' => $items_per_page, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $bans[] = $row; } Db::$db->free_result($request); @@ -1284,13 +1250,15 @@ public static function list_getBans($start, $items_per_page, $sort): array */ public static function list_getNumBans(): int { - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) AS num_bans FROM {db_prefix}ban_groups', - array( - ) + [ + ], ); - list ($numBans) = Db::$db->fetch_row($request); + list($numBans) = Db::$db->fetch_row($request); Db::$db->free_result($request); return $numBans; @@ -1307,9 +1275,11 @@ public static function list_getNumBans(): int */ public static function list_getBanItems($start = 0, $items_per_page = 0, $sort = 0, $ban_group_id = 0): array { - $ban_items = array(); + $ban_items = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT bi.id_ban, bi.hostname, bi.email_address, bi.id_member, bi.hits, bi.ip_low, bi.ip_high, @@ -1320,75 +1290,66 @@ public static function list_getBanItems($start = 0, $items_per_page = 0, $sort = LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = bi.id_member) WHERE bg.id_ban_group = {int:current_ban} LIMIT {int:start}, {int:items_per_page}', - array( + [ 'current_ban' => $ban_group_id, 'start' => $start, 'items_per_page' => $items_per_page, - ) + ], ); - if (Db::$db->num_rows($request) == 0) - { + + if (Db::$db->num_rows($request) == 0) { ErrorHandler::fatalLang('ban_not_found', false); } - while ($row = Db::$db->fetch_assoc($request)) - { - if (!isset(Utils::$context['ban'])) - { - Utils::$context['ban'] = array( + + while ($row = Db::$db->fetch_assoc($request)) { + if (!isset(Utils::$context['ban'])) { + Utils::$context['ban'] = [ 'id' => $row['id_ban_group'], 'name' => $row['name'], - 'expiration' => array( + 'expiration' => [ 'status' => $row['expire_time'] === null ? 'never' : ($row['expire_time'] < time() ? 'expired' : 'one_day'), - 'days' => $row['expire_time'] > time() ? ($row['expire_time'] - time() < 86400 ? 1 : ceil(($row['expire_time'] - time()) / 86400)) : 0 - ), + 'days' => $row['expire_time'] > time() ? ($row['expire_time'] - time() < 86400 ? 1 : ceil(($row['expire_time'] - time()) / 86400)) : 0, + ], 'reason' => $row['reason'], 'notes' => $row['notes'], - 'cannot' => array( + 'cannot' => [ 'access' => !empty($row['cannot_access']), 'post' => !empty($row['cannot_post']), 'register' => !empty($row['cannot_register']), 'login' => !empty($row['cannot_login']), - ), + ], 'is_new' => false, 'hostname' => '', 'email' => '', - ); + ]; } - if (!empty($row['id_ban'])) - { - $ban_items[$row['id_ban']] = array( + if (!empty($row['id_ban'])) { + $ban_items[$row['id_ban']] = [ 'id' => $row['id_ban'], 'hits' => $row['hits'], - ); - if (!empty($row['ip_high'])) - { + ]; + + if (!empty($row['ip_high'])) { $ban_items[$row['id_ban']]['type'] = 'ip'; $ban_items[$row['id_ban']]['ip'] = IP::range2ip($row['ip_low'], $row['ip_high']); - } - elseif (!empty($row['hostname'])) - { + } elseif (!empty($row['hostname'])) { $ban_items[$row['id_ban']]['type'] = 'hostname'; $ban_items[$row['id_ban']]['hostname'] = str_replace('%', '*', $row['hostname']); - } - elseif (!empty($row['email_address'])) - { + } elseif (!empty($row['email_address'])) { $ban_items[$row['id_ban']]['type'] = 'email'; $ban_items[$row['id_ban']]['email'] = str_replace('%', '*', $row['email_address']); - } - elseif (!empty($row['id_member'])) - { + } elseif (!empty($row['id_member'])) { $ban_items[$row['id_ban']]['type'] = 'user'; - $ban_items[$row['id_ban']]['user'] = array( + $ban_items[$row['id_ban']]['user'] = [ 'id' => $row['id_member'], 'name' => $row['real_name'], 'href' => Config::$scripturl . '?action=profile;u=' . $row['id_member'], 'link' => '' . $row['real_name'] . '', - ); + ]; } // Invalid ban (member probably doesn't exist anymore). - else - { + else { unset($ban_items[$row['id_ban']]); self::removeBanTriggers($row['id_ban']); } @@ -1396,7 +1357,7 @@ public static function list_getBanItems($start = 0, $items_per_page = 0, $sort = } Db::$db->free_result($request); - IntegrationHook::call('integrate_ban_list', array(&$ban_items)); + IntegrationHook::call('integrate_ban_list', [&$ban_items]); return $ban_items; } @@ -1408,17 +1369,19 @@ public static function list_getBanItems($start = 0, $items_per_page = 0, $sort = */ public static function list_getNumBanItems(): int { - $ban_group_id = isset(Utils::$context['ban_group_id']) ? Utils::$context['ban_group_id'] : 0; + $ban_group_id = Utils::$context['ban_group_id'] ?? 0; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(bi.id_ban) FROM {db_prefix}ban_groups AS bg LEFT JOIN {db_prefix}ban_items AS bi ON (bi.id_ban_group = bg.id_ban_group) LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = bi.id_member) WHERE bg.id_ban_group = {int:current_ban}', - array( + [ 'current_ban' => $ban_group_id, - ) + ], ); list($banNumber) = Db::$db->fetch_row($request); Db::$db->free_result($request); @@ -1439,15 +1402,17 @@ public static function list_getNumBanItems(): int */ public static function list_getBanTriggers($start, $items_per_page, $sort, $trigger_type): array { - $ban_triggers = array(); + $ban_triggers = []; - $where = array( + $where = [ 'ip' => 'bi.ip_low is not null', 'hostname' => 'bi.hostname != {string:blank_string}', 'email' => 'bi.email_address != {string:blank_string}', - ); + ]; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT bi.id_ban, bi.ip_low, bi.ip_high, bi.hostname, bi.email_address, bi.hits, bg.id_ban_group, bg.name' . ($trigger_type === 'member' ? ', @@ -1458,15 +1423,15 @@ public static function list_getBanTriggers($start, $items_per_page, $sort, $trig WHERE ' . $where[$trigger_type]) . ' ORDER BY {raw:sort} LIMIT {int:start}, {int:max}', - array( + [ 'blank_string' => '', 'sort' => $sort, 'start' => $start, 'max' => $items_per_page, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $ban_triggers[] = $row; } Db::$db->free_result($request); @@ -1484,22 +1449,24 @@ public static function list_getBanTriggers($start, $items_per_page, $sort, $trig */ public static function list_getNumBanTriggers($trigger_type): int { - $where = array( + $where = [ 'ip' => 'bi.ip_low is not null', 'hostname' => 'bi.hostname != {string:blank_string}', 'email' => 'bi.email_address != {string:blank_string}', - ); + ]; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}ban_items AS bi' . ($trigger_type === 'member' ? ' INNER JOIN {db_prefix}members AS mem ON (mem.id_member = bi.id_member)' : ' WHERE ' . $where[$trigger_type]), - array( + [ 'blank_string' => '', - ) + ], ); - list ($num_triggers) = Db::$db->fetch_row($request); + list($num_triggers) = Db::$db->fetch_row($request); Db::$db->free_result($request); return $num_triggers; @@ -1516,24 +1483,26 @@ public static function list_getNumBanTriggers($trigger_type): int */ public static function list_getBanLogEntries($start, $items_per_page, $sort): array { - $log_entries = array(); + $log_entries = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT lb.id_ban_log, lb.id_member, lb.ip AS ip, COALESCE(lb.email, {string:dash}) AS email, lb.log_time, COALESCE(mem.real_name, {string:blank_string}) AS real_name FROM {db_prefix}log_banned AS lb LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lb.id_member) ORDER BY {raw:sort} LIMIT {int:start}, {int:items}', - array( + [ 'blank_string' => '', 'dash' => '-', 'sort' => $sort, 'start' => $start, 'items' => $items_per_page, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $row['ip'] = $row['ip'] === null ? '-' : new IP($row['ip']); $log_entries[] = $row; } @@ -1549,13 +1518,15 @@ public static function list_getBanLogEntries($start, $items_per_page, $sort): ar */ public static function list_getNumBanLogEntries(): int { - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}log_banned AS lb', - array( - ) + [ + ], ); - list ($num_entries) = Db::$db->fetch_row($request); + list($num_entries) = Db::$db->fetch_row($request); Db::$db->free_result($request); return $num_entries; @@ -1623,43 +1594,44 @@ protected function __construct() Theme::loadTemplate('ManageBans'); // Tab data might already be set if this was called from Logs::execute(). - if (empty(Menu::$loaded['admin']->tab_data)) - { + if (empty(Menu::$loaded['admin']->tab_data)) { // Tabs for browsing the different ban functions. - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['ban_title'], 'help' => 'ban_members', 'description' => Lang::$txt['ban_description'], - 'tabs' => array( - 'list' => array( + 'tabs' => [ + 'list' => [ 'description' => Lang::$txt['ban_description'], 'href' => Config::$scripturl . '?action=admin;area=ban;sa=list', - ), - 'add' => array( + ], + 'add' => [ 'description' => Lang::$txt['ban_description'], 'href' => Config::$scripturl . '?action=admin;area=ban;sa=add', - ), - 'browse' => array( + ], + 'browse' => [ 'description' => Lang::$txt['ban_trigger_browse_description'], 'href' => Config::$scripturl . '?action=admin;area=ban;sa=browse', - ), - 'log' => array( + ], + 'log' => [ 'description' => Lang::$txt['ban_log_description'], 'href' => Config::$scripturl . '?action=admin;area=ban;sa=log', 'is_last' => true, - ), - ), - ); + ], + ], + ]; } - IntegrationHook::call('integrate_manage_bans', array(&self::$subactions)); + IntegrationHook::call('integrate_manage_bans', [&self::$subactions]); - if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) + if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) { $this->subaction = $_REQUEST['sa']; + } // Mark the appropriate menu entry as selected - if (array_key_exists($this->subaction, Menu::$loaded['admin']->tab_data['tabs'])) + if (array_key_exists($this->subaction, Menu::$loaded['admin']->tab_data['tabs'])) { Menu::$loaded['admin']->tab_data['tabs'][$this->subaction]['is_selected'] = true; + } Utils::$context['page_title'] = Lang::$txt['ban_title']; Utils::$context['sub_action'] = $this->subaction; @@ -1673,48 +1645,44 @@ protected function edit2(): void User::$me->checkSession(); SecurityToken::validate('admin-bet'); - Utils::$context['ban_errors'] = array(); + Utils::$context['ban_errors'] = []; // Adding or editing a ban group - if (isset($_POST['add_ban']) || isset($_POST['modify_ban'])) - { + if (isset($_POST['add_ban']) || isset($_POST['modify_ban'])) { // Let's collect all the information we need $ban_info['id'] = isset($_REQUEST['bg']) ? (int) $_REQUEST['bg'] : 0; $ban_info['is_new'] = empty($ban_info['id']); $ban_info['expire_date'] = !empty($_POST['expire_date']) ? (int) $_POST['expire_date'] : 0; - $ban_info['expiration'] = array( - 'status' => isset($_POST['expiration']) && in_array($_POST['expiration'], array('never', 'one_day', 'expired')) ? $_POST['expiration'] : 'never', + $ban_info['expiration'] = [ + 'status' => isset($_POST['expiration']) && in_array($_POST['expiration'], ['never', 'one_day', 'expired']) ? $_POST['expiration'] : 'never', 'days' => $ban_info['expire_date'], - ); + ]; $ban_info['db_expiration'] = $ban_info['expiration']['status'] == 'never' ? 'NULL' : ($ban_info['expiration']['status'] == 'one_day' ? time() + 24 * 60 * 60 * $ban_info['expire_date'] : 0); $ban_info['full_ban'] = empty($_POST['full_ban']) ? 0 : 1; $ban_info['reason'] = !empty($_POST['reason']) ? Utils::htmlspecialchars($_POST['reason'], ENT_QUOTES) : ''; $ban_info['name'] = !empty($_POST['ban_name']) ? Utils::htmlspecialchars($_POST['ban_name'], ENT_QUOTES) : ''; $ban_info['notes'] = isset($_POST['notes']) ? Utils::htmlspecialchars($_POST['notes'], ENT_QUOTES) : ''; - $ban_info['notes'] = str_replace(array("\r", "\n", ' '), array('', '
', '  '), $ban_info['notes']); + $ban_info['notes'] = str_replace(["\r", "\n", ' '], ['', '
', '  '], $ban_info['notes']); $ban_info['cannot']['access'] = empty($ban_info['full_ban']) ? 0 : 1; $ban_info['cannot']['post'] = !empty($ban_info['full_ban']) || empty($_POST['cannot_post']) ? 0 : 1; $ban_info['cannot']['register'] = !empty($ban_info['full_ban']) || empty($_POST['cannot_register']) ? 0 : 1; $ban_info['cannot']['login'] = !empty($ban_info['full_ban']) || empty($_POST['cannot_login']) ? 0 : 1; - IntegrationHook::call('integrate_edit_bans', array(&$ban_info, empty($_REQUEST['bg']))); + IntegrationHook::call('integrate_edit_bans', [&$ban_info, empty($_REQUEST['bg'])]); // Limit 'reason' characters $ban_info['reason'] = Utils::truncate($ban_info['reason'], 255); // Adding a new ban group - if (empty($_REQUEST['bg'])) - { + if (empty($_REQUEST['bg'])) { $ban_group_id = $this->insertBanGroup($ban_info); } // Editing an existing ban group - else - { + else { $ban_group_id = $this->updateBanGroup($ban_info); } - if (is_numeric($ban_group_id)) - { + if (is_numeric($ban_group_id)) { $ban_info['id'] = $ban_group_id; $ban_info['is_new'] = false; } @@ -1722,47 +1690,43 @@ protected function edit2(): void Utils::$context['ban'] = $ban_info; } - if (isset($_POST['ban_suggestions'])) - { + if (isset($_POST['ban_suggestions'])) { // @TODO: is $_REQUEST['bi'] ever set? $saved_triggers = $this->saveTriggers($_POST['ban_suggestions'], $ban_info['id'], (int) ($_REQUEST['u'] ?? 0), (int) ($_REQUEST['bi'] ?? 0)); } // Something went wrong somewhere... Oh well, let's go back. - if (!empty(Utils::$context['ban_errors'])) - { - Utils::$context['ban_suggestions'] = !empty($saved_triggers) ? $saved_triggers : array(); + if (!empty(Utils::$context['ban_errors'])) { + Utils::$context['ban_suggestions'] = !empty($saved_triggers) ? $saved_triggers : []; - if (isset($_REQUEST['u'])) - { + if (isset($_REQUEST['u'])) { Utils::$context['ban']['from_user'] = true; Utils::$context['ban_suggestions'] = array_merge(Utils::$context['ban_suggestions'], $this->getMemberData((int) $_REQUEST['u'])); } // Not strictly necessary, but it's nice - if (!empty(Utils::$context['ban_suggestions']['member']['id'])) - { + if (!empty(Utils::$context['ban_suggestions']['member']['id'])) { Utils::$context['ban_suggestions']['other_ips'] = $this->banLoadAdditionalIPs(Utils::$context['ban_suggestions']['member']['id']); } $this->edit(); + return; } - Utils::$context['ban_suggestions']['saved_triggers'] = !empty($saved_triggers) ? $saved_triggers : array(); + Utils::$context['ban_suggestions']['saved_triggers'] = !empty($saved_triggers) ? $saved_triggers : []; - if (isset($_POST['ban_items'])) - { + if (isset($_POST['ban_items'])) { $ban_group_id = isset($_REQUEST['bg']) ? (int) $_REQUEST['bg'] : 0; array_map('intval', $_POST['ban_items']); self::removeBanTriggers($_POST['ban_items'], $ban_group_id); } - IntegrationHook::call('integrate_edit_bans_post', array()); + IntegrationHook::call('integrate_edit_bans_post', []); // Register the last modified date. - Config::updateModSettings(array('banLastUpdated' => time())); + Config::updateModSettings(['banLastUpdated' => time()]); // Update the member table to represent the new ban situation. self::updateBanMembers(); @@ -1780,19 +1744,20 @@ protected function banLoadAdditionalIPs($member_id): array // Borrowing a few language strings from profile. Lang::load('Profile'); - $search_list = array(); - IntegrationHook::call('integrate_load_addtional_ip_ban', array(&$search_list)); + $search_list = []; + IntegrationHook::call('integrate_load_addtional_ip_ban', [&$search_list]); - $search_list += array( - 'ips_in_messages' => array($this, 'banLoadAdditionalIPsMember'), - 'ips_in_errors' => array($this, 'banLoadAdditionalIPsError'), - ); + $search_list += [ + 'ips_in_messages' => [$this, 'banLoadAdditionalIPsMember'], + 'ips_in_errors' => [$this, 'banLoadAdditionalIPsError'], + ]; + + $return = []; - $return = array(); - foreach ($search_list as $key => $callable) - { - if (is_callable($callable)) + foreach ($search_list as $key => $callable) { + if (is_callable($callable)) { $return[$key] = call_user_func($callable, $member_id); + } } return $return; @@ -1807,20 +1772,22 @@ protected function banLoadAdditionalIPs($member_id): array protected function banLoadAdditionalIPsMember($member_id): array { // Find some additional IP's used by this member. - $message_ips = array(); + $message_ips = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT DISTINCT poster_ip FROM {db_prefix}messages WHERE id_member = {int:current_user} AND poster_ip IS NOT NULL ORDER BY poster_ip', - array( + [ 'current_user' => $member_id, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $message_ips[] = new IP($row['poster_ip']); } Db::$db->free_result($request); @@ -1836,20 +1803,22 @@ protected function banLoadAdditionalIPsMember($member_id): array */ protected function banLoadAdditionalIPsError($member_id): array { - $error_ips = array(); + $error_ips = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT DISTINCT ip FROM {db_prefix}log_errors WHERE id_member = {int:current_user} AND ip IS NOT NULL ORDER BY ip', - array( + [ 'current_user' => $member_id, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $error_ips[] = new IP($row['ip']); } Db::$db->free_result($request); @@ -1870,48 +1839,41 @@ protected function banLoadAdditionalIPsError($member_id): array */ protected function saveTriggers(array $suggestions, $ban_group, $member = 0, $ban_id = 0) { - $triggers = array( + $triggers = [ 'main_ip' => '', 'hostname' => '', 'email' => '', - 'member' => array( + 'member' => [ 'id' => $member, - ) - ); + ], + ]; - foreach ($suggestions as $key => $value) - { - if (is_array($value)) - { + foreach ($suggestions as $key => $value) { + if (is_array($value)) { $triggers[$key] = $value; - } - else - { + } else { $triggers[$value] = !empty($_POST[$value]) ? $_POST[$value] : ''; } } $ban_triggers = $this->validateTriggers($triggers); - IntegrationHook::call('integrate_save_triggers', array(&$ban_triggers, &$ban_group)); + IntegrationHook::call('integrate_save_triggers', [&$ban_triggers, &$ban_group]); // Time to save! - if (!empty($ban_triggers['ban_triggers']) && empty(Utils::$context['ban_errors'])) - { - if (empty($ban_id)) - { + if (!empty($ban_triggers['ban_triggers']) && empty(Utils::$context['ban_errors'])) { + if (empty($ban_id)) { $this->addTriggers($ban_group, $ban_triggers['ban_triggers'], $ban_triggers['log_info']); - } - else - { + } else { $this->updateTriggers($ban_id, $ban_group, array_shift($ban_triggers['ban_triggers']), $ban_triggers['log_info']); } } - if (!empty(Utils::$context['ban_errors'])) + if (!empty(Utils::$context['ban_errors'])) { return $triggers; + } - return array(); + return []; } /** @@ -1924,35 +1886,41 @@ protected function saveTriggers(array $suggestions, $ban_group, $member = 0, $ba */ protected function removeBanGroups($group_ids): bool { - if (!is_array($group_ids)) - $group_ids = array($group_ids); + if (!is_array($group_ids)) { + $group_ids = [$group_ids]; + } $group_ids = array_unique($group_ids); - if (empty($group_ids)) + if (empty($group_ids)) { return false; + } - Db::$db->query('', ' + Db::$db->query( + '', + ' DELETE FROM {db_prefix}ban_groups WHERE id_ban_group IN ({array_int:ban_list})', - array( + [ 'ban_list' => $group_ids, - ) + ], ); // Remove all ban triggers for these bans groups - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_ban FROM {db_prefix}ban_items WHERE id_ban_group IN ({array_int:ban_list})', - array( + [ 'ban_list' => $group_ids, - ) + ], ); - $id_ban_triggers = array(); - while ($row = Db::$db->fetch_assoc($request)) - { + $id_ban_triggers = []; + + while ($row = Db::$db->fetch_assoc($request)) { $id_ban_triggers[] = $row['id_ban']; } Db::$db->free_result($request); @@ -1970,29 +1938,31 @@ protected function removeBanGroups($group_ids): bool * @param array $ids IDs of the log entries to remove, or empty to remove all. * @return bool Returns true if successful or false if $ids is invalid. */ - protected function removeBanLogs($ids = array()): bool + protected function removeBanLogs($ids = []): bool { - if (empty($ids)) - { - Db::$db->query('truncate_table', ' + if (empty($ids)) { + Db::$db->query( + 'truncate_table', + ' TRUNCATE {db_prefix}log_banned', - array( - ) + [ + ], ); - } - else - { + } else { $ids = array_filter(array_unique(array_map('intval', (array) $ids))); - if (empty($ids)) + if (empty($ids)) { return false; + } - Db::$db->query('', ' + Db::$db->query( + '', + ' DELETE FROM {db_prefix}log_banned WHERE id_ban_log IN ({array_int:ban_list})', - array( + [ 'ban_list' => $ids, - ) + ], ); } @@ -2009,69 +1979,61 @@ protected function removeBanLogs($ids = array()): bool */ protected function validateTriggers(&$triggers): array { - if (empty($triggers)) + if (empty($triggers)) { Utils::$context['ban_errors'][] = 'ban_empty_triggers'; + } - $ban_triggers = array(); - $log_info = array(); + $ban_triggers = []; + $log_info = []; - foreach ($triggers as $key => $value) - { - if (!empty($value)) - { - if ($key == 'member') + foreach ($triggers as $key => $value) { + if (!empty($value)) { + if ($key == 'member') { continue; + } - if ($key == 'main_ip') - { + if ($key == 'main_ip') { $value = trim($value); $ip_range = IP::ip2range($value); - if (!$this->checkExistingTriggerIP($ip_range, $value)) - { + if (!$this->checkExistingTriggerIP($ip_range, $value)) { Utils::$context['ban_errors'][] = 'invalid_ip'; - } - else - { - $ban_triggers['main_ip'] = array( + } else { + $ban_triggers['main_ip'] = [ 'ip_low' => $ip_range['low'], - 'ip_high' => $ip_range['high'] - ); + 'ip_high' => $ip_range['high'], + ]; } - } - elseif ($key == 'hostname') - { - if (preg_match('/[^\w.\-*]/', $value) == 1) - { + } elseif ($key == 'hostname') { + if (preg_match('/[^\\w.\\-*]/', $value) == 1) { Utils::$context['ban_errors'][] = 'invalid_hostname'; - } - else - { + } else { // Replace the * wildcard by a MySQL wildcard %. $value = substr(str_replace('*', '%', $value), 0, 255); $ban_triggers['hostname']['hostname'] = $value; } - } - elseif ($key == 'email') - { - if (preg_match('/[^\w.\-\+*@]/', $value) == 1) + } elseif ($key == 'email') { + if (preg_match('/[^\\w.\\-\\+*@]/', $value) == 1) { Utils::$context['ban_errors'][] = 'invalid_email'; + } // Check the user is not banning an admin. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_member FROM {db_prefix}members WHERE (id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0) AND email_address LIKE {string:email} LIMIT 1', - array( + [ 'admin_group' => 1, 'email' => $value, - ) + ], ); - if (Db::$db->num_rows($request) != 0) - { + + if (Db::$db->num_rows($request) != 0) { Utils::$context['ban_errors'][] = 'no_ban_admin'; } Db::$db->free_result($request); @@ -2079,87 +2041,76 @@ protected function validateTriggers(&$triggers): array $value = substr(strtolower(str_replace('*', '%', $value)), 0, 255); $ban_triggers['email']['email_address'] = $value; - } - elseif ($key == 'user') - { - $user = preg_replace('~&#(\d{4,5}|[2-9]\d{2,4}|1[2-9]\d);~', '&#$1;', Utils::htmlspecialchars($value, ENT_QUOTES)); + } elseif ($key == 'user') { + $user = preg_replace('~&#(\\d{4,5}|[2-9]\\d{2,4}|1[2-9]\\d);~', '&#$1;', Utils::htmlspecialchars($value, ENT_QUOTES)); - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_member, (id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0) AS isAdmin FROM {db_prefix}members WHERE member_name = {string:username} OR real_name = {string:username} LIMIT 1', - array( + [ 'admin_group' => 1, 'username' => $user, - ) + ], ); - if (Db::$db->num_rows($request) == 0) - { + + if (Db::$db->num_rows($request) == 0) { Utils::$context['ban_errors'][] = 'invalid_username'; } - list ($value, $isAdmin) = Db::$db->fetch_row($request); + list($value, $isAdmin) = Db::$db->fetch_row($request); Db::$db->free_result($request); - if ($isAdmin && strtolower($isAdmin) != 'f') - { + if ($isAdmin && strtolower($isAdmin) != 'f') { unset($value); Utils::$context['ban_errors'][] = 'no_ban_admin'; - } - else - { + } else { $ban_triggers['user']['id_member'] = $value; } - } - elseif (in_array($key, array('ips_in_messages', 'ips_in_errors'))) - { + } elseif (in_array($key, ['ips_in_messages', 'ips_in_errors'])) { // Special case, those two are arrays themselves $values = array_unique($value); unset($value); // Don't add the main IP again. - if (isset($triggers['main_ip'])) - $values = array_diff($values, array($triggers['main_ip'])); + if (isset($triggers['main_ip'])) { + $values = array_diff($values, [$triggers['main_ip']]); + } - foreach ($values as $val) - { + foreach ($values as $val) { $val = trim($val); $ip_range = IP::ip2range($val); - if (!$this->checkExistingTriggerIP($ip_range, $val)) - { + if (!$this->checkExistingTriggerIP($ip_range, $val)) { Utils::$context['ban_errors'][] = 'invalid_ip'; - } - else - { - $ban_triggers[$key][] = array( + } else { + $ban_triggers[$key][] = [ 'ip_low' => $ip_range['low'], 'ip_high' => $ip_range['high'], - ); + ]; - $log_info[] = array( + $log_info[] = [ 'value' => $val, 'bantype' => 'ip_range', - ); + ]; } } - } - else - { + } else { Utils::$context['ban_errors'][] = 'no_bantype_selected'; } - if (isset($value) && !is_array($value)) - { - $log_info[] = array( + if (isset($value) && !is_array($value)) { + $log_info[] = [ 'value' => $value, 'bantype' => $key, - ); + ]; } } } - return array('ban_triggers' => $ban_triggers, 'log_info' => $log_info); + return ['ban_triggers' => $ban_triggers, 'log_info' => $log_info]; } /** @@ -2171,33 +2122,35 @@ protected function validateTriggers(&$triggers): array */ protected function checkExistingTriggerIP($ip_array, $fullip = ''): bool { - $values = array( + $values = [ 'ip_low' => $ip_array['low'], - 'ip_high' => $ip_array['high'] - ); + 'ip_high' => $ip_array['high'], + ]; $is_valid = true; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT bg.id_ban_group, bg.name FROM {db_prefix}ban_groups AS bg INNER JOIN {db_prefix}ban_items AS bi ON (bi.id_ban_group = bg.id_ban_group) AND ip_low = {inet:ip_low} AND ip_high = {inet:ip_high} LIMIT 1', - $values + $values, ); - if (Db::$db->num_rows($request) != 0) - { + + if (Db::$db->num_rows($request) != 0) { $is_valid = false; $row = Db::$db->fetch_assoc($request); // @todo Why do we die on this error, but not others? - ErrorHandler::fatalLang('ban_trigger_already_exists', false, array( + ErrorHandler::fatalLang('ban_trigger_already_exists', false, [ $fullip, '' . $row['name'] . '', - )); + ]); } Db::$db->free_result($request); @@ -2215,56 +2168,58 @@ protected function checkExistingTriggerIP($ip_array, $fullip = ''): bool * @param array $logs The log data. * @return bool Whether or not the action was successful. */ - protected function addTriggers($group_id = 0, $triggers = array(), $logs = array()): bool + protected function addTriggers($group_id = 0, $triggers = [], $logs = []): bool { - if (empty($group_id)) + if (empty($group_id)) { Utils::$context['ban_errors'][] = 'ban_id_empty'; + } // Preset all values that are required. - $values = array( + $values = [ 'id_ban_group' => $group_id, 'hostname' => '', 'email_address' => '', 'id_member' => 0, 'ip_low' => 'null', 'ip_high' => 'null', - ); + ]; - $insertKeys = array( + $insertKeys = [ 'id_ban_group' => 'int', 'hostname' => 'string', 'email_address' => 'string', 'id_member' => 'int', 'ip_low' => 'inet', 'ip_high' => 'inet', - ); + ]; + + $insertTriggers = []; - $insertTriggers = array(); - foreach ($triggers as $key => $trigger) - { + foreach ($triggers as $key => $trigger) { // Exceptions, exceptions, exceptions...always exceptions... :P - if (in_array($key, array('ips_in_messages', 'ips_in_errors'))) - { - foreach ($trigger as $real_trigger) + if (in_array($key, ['ips_in_messages', 'ips_in_errors'])) { + foreach ($trigger as $real_trigger) { $insertTriggers[] = array_merge($values, $real_trigger); - } - else - { + } + } else { $insertTriggers[] = array_merge($values, $trigger); } } - if (empty($insertTriggers)) + if (empty($insertTriggers)) { Utils::$context['ban_errors'][] = 'ban_no_triggers'; + } - if (!empty(Utils::$context['ban_errors'])) + if (!empty(Utils::$context['ban_errors'])) { return false; + } - Db::$db->insert('', + Db::$db->insert( + '', '{db_prefix}ban_items', $insertKeys, $insertTriggers, - array('id_ban') + ['id_ban'], ); self::logTriggersUpdates($logs, true); @@ -2282,43 +2237,49 @@ protected function addTriggers($group_id = 0, $triggers = array(), $logs = array * @param array $trigger An array of triggers. * @param array $logs An array of log info. */ - protected function updateTriggers($ban_item = 0, $group_id = 0, $trigger = array(), $logs = array()): void + protected function updateTriggers($ban_item = 0, $group_id = 0, $trigger = [], $logs = []): void { - if (empty($ban_item)) + if (empty($ban_item)) { Utils::$context['ban_errors'][] = 'ban_ban_item_empty'; + } - if (empty($group_id)) + if (empty($group_id)) { Utils::$context['ban_errors'][] = 'ban_id_empty'; + } - if (empty($trigger)) + if (empty($trigger)) { Utils::$context['ban_errors'][] = 'ban_no_triggers'; + } - if (!empty(Utils::$context['ban_errors'])) + if (!empty(Utils::$context['ban_errors'])) { return; + } // Preset all values that are required. - $values = array( + $values = [ 'id_ban_group' => $group_id, 'hostname' => '', 'email_address' => '', 'id_member' => 0, 'ip_low' => 'null', 'ip_high' => 'null', - ); + ]; $trigger = array_merge($values, $trigger); - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}ban_items SET hostname = {string:hostname}, email_address = {string:email_address}, id_member = {int:id_member}, ip_low = {inet:ip_low}, ip_high = {inet:ip_high} WHERE id_ban = {int:ban_item} AND id_ban_group = {int:id_ban_group}', - array_merge($trigger, array( + array_merge($trigger, [ 'id_ban_group' => $group_id, 'ban_item' => $ban_item, - )) + ]), ); self::logTriggersUpdates($logs, false); @@ -2333,67 +2294,71 @@ protected function updateTriggers($ban_item = 0, $group_id = 0, $trigger = array * Should have name and may also have an id. * @return int The ban group's ID. */ - protected function updateBanGroup($ban_info = array()): int + protected function updateBanGroup($ban_info = []): int { - if (empty($ban_info['name'])) + if (empty($ban_info['name'])) { Utils::$context['ban_errors'][] = 'ban_name_empty'; + } - if (empty($ban_info['id'])) + if (empty($ban_info['id'])) { Utils::$context['ban_errors'][] = 'ban_id_empty'; + } if ( empty($ban_info['cannot']['access']) && empty($ban_info['cannot']['register']) && empty($ban_info['cannot']['post']) && empty($ban_info['cannot']['login']) - ) - { + ) { Utils::$context['ban_errors'][] = 'ban_unknown_restriction_type'; } - if (!empty($ban_info['id'])) - { + if (!empty($ban_info['id'])) { // Verify the ban group exists. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_ban_group FROM {db_prefix}ban_groups WHERE id_ban_group = {int:ban_group} LIMIT 1', - array( - 'ban_group' => $ban_info['id'] - ) + [ + 'ban_group' => $ban_info['id'], + ], ); - if (Db::$db->num_rows($request) == 0) - { + + if (Db::$db->num_rows($request) == 0) { Utils::$context['ban_errors'][] = 'ban_not_found'; } Db::$db->free_result($request); } - if (!empty($ban_info['name'])) - { + if (!empty($ban_info['name'])) { // Make sure the name does not already exist (Of course, if it exists in the ban group we are editing, proceed.) - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_ban_group FROM {db_prefix}ban_groups WHERE name = {string:new_ban_name} AND id_ban_group != {int:ban_group} LIMIT 1', - array( + [ 'ban_group' => empty($ban_info['id']) ? 0 : $ban_info['id'], 'new_ban_name' => $ban_info['name'], - ) + ], ); - if (Db::$db->num_rows($request) != 0) - { + + if (Db::$db->num_rows($request) != 0) { Utils::$context['ban_errors'][] = 'ban_name_exists'; } Db::$db->free_result($request); } - if (empty(Utils::$context['ban_errors'])) - { - Db::$db->query('', ' + if (empty(Utils::$context['ban_errors'])) { + Db::$db->query( + '', + ' UPDATE {db_prefix}ban_groups SET name = {string:ban_name}, @@ -2405,7 +2370,7 @@ protected function updateBanGroup($ban_info = array()): int cannot_register = {int:cannot_register}, cannot_login = {int:cannot_login} WHERE id_ban_group = {int:id_ban_group}', - array( + [ 'expiration' => $ban_info['db_expiration'], 'cannot_access' => $ban_info['cannot']['access'], 'cannot_post' => $ban_info['cannot']['post'], @@ -2415,7 +2380,7 @@ protected function updateBanGroup($ban_info = array()): int 'ban_name' => $ban_info['name'], 'reason' => $ban_info['reason'], 'notes' => $ban_info['notes'], - ) + ], ); } @@ -2433,61 +2398,64 @@ protected function updateBanGroup($ban_info = array()): int * @param array $ban_info An array containing 'name', which is the name of the ban group. * @return int|false The ban group's ID, or false on error. */ - protected function insertBanGroup($ban_info = array()): int|false + protected function insertBanGroup($ban_info = []): int|false { - if (empty($ban_info['name'])) + if (empty($ban_info['name'])) { Utils::$context['ban_errors'][] = 'ban_name_empty'; + } if ( empty($ban_info['cannot']['access']) && empty($ban_info['cannot']['register']) && empty($ban_info['cannot']['post']) && empty($ban_info['cannot']['login']) - ) - { + ) { Utils::$context['ban_errors'][] = 'ban_unknown_restriction_type'; } - if (!empty($ban_info['name'])) - { + if (!empty($ban_info['name'])) { // Check whether a ban with this name already exists. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_ban_group FROM {db_prefix}ban_groups WHERE name = {string:new_ban_name}' . ' LIMIT 1', - array( + [ 'new_ban_name' => $ban_info['name'], - ) + ], ); - if (Db::$db->num_rows($request) == 1) - { + + if (Db::$db->num_rows($request) == 1) { Utils::$context['ban_errors'][] = 'ban_name_exists'; } Db::$db->free_result($request); } - if (!empty(Utils::$context['ban_errors'])) + if (!empty(Utils::$context['ban_errors'])) { return false; + } // Yes yes, we're ready to add now. - $ban_info['id'] = Db::$db->insert('', + $ban_info['id'] = Db::$db->insert( + '', '{db_prefix}ban_groups', - array( + [ 'name' => 'string-20', 'ban_time' => 'int', 'expire_time' => 'raw', 'cannot_access' => 'int', 'cannot_register' => 'int', 'cannot_post' => 'int', 'cannot_login' => 'int', 'reason' => 'string-255', 'notes' => 'string-65534', - ), - array( + ], + [ $ban_info['name'], time(), $ban_info['db_expiration'], $ban_info['cannot']['access'], $ban_info['cannot']['register'], $ban_info['cannot']['post'], $ban_info['cannot']['login'], $ban_info['reason'], $ban_info['notes'], - ), - array('id_ban_group'), - 1 + ], + ['id_ban_group'], + 1, ); - if (empty($ban_info['id'])) - { + if (empty($ban_info['id'])) { Utils::$context['ban_errors'][] = 'impossible_insert_new_bangroup'; + return false; } @@ -2502,19 +2470,21 @@ protected function insertBanGroup($ban_info = array()): int|false */ protected function getMemberData($id): array { - $suggestions = array(); + $suggestions = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_member, real_name, member_ip, email_address FROM {db_prefix}members WHERE id_member = {int:current_user} LIMIT 1', - array( + [ 'current_user' => $id, - ) + ], ); - if (Db::$db->num_rows($request) > 0) - { + + if (Db::$db->num_rows($request) > 0) { list($suggestions['member']['id'], $suggestions['member']['name'], $suggestions['main_ip'], $suggestions['email']) = Db::$db->fetch_row($request); $suggestions['main_ip'] = new IP($suggestions['main_ip']); @@ -2538,24 +2508,29 @@ protected function getMemberData($id): array * If null, the triggers will be deleted from all groups. * @return bool Whether the operation was successful. */ - protected static function removeBanTriggers($items_ids = array(), $group_id = null): bool + protected static function removeBanTriggers($items_ids = [], $group_id = null): bool { - if (isset($group_id)) + if (isset($group_id)) { $group_id = (int) $group_id; + } - if (empty($group_id) && empty($items_ids)) + if (empty($group_id) && empty($items_ids)) { return false; + } - if (!is_array($items_ids)) - $items_ids = array($items_ids); + if (!is_array($items_ids)) { + $items_ids = [$items_ids]; + } - $log_info = array(); - $ban_items = array(); + $log_info = []; + $ban_items = []; - IntegrationHook::call('integrate_remove_triggers', array(&$items_ids, $group_id)); + IntegrationHook::call('integrate_remove_triggers', [&$items_ids, $group_id]); // First order of business: Load up the info so we can log this... - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT bi.id_ban, bi.hostname, bi.email_address, bi.id_member, bi.hits, bi.ip_low, bi.ip_high, @@ -2563,65 +2538,57 @@ protected static function removeBanTriggers($items_ids = array(), $group_id = nu FROM {db_prefix}ban_items AS bi LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = bi.id_member) WHERE bi.id_ban IN ({array_int:ban_list})', - array( + [ 'ban_list' => $items_ids, - ) + ], ); + // Get all the info for the log - while ($row = Db::$db->fetch_assoc($request)) - { - if (!empty($row['id_ban'])) - { - $ban_items[$row['id_ban']] = array( + while ($row = Db::$db->fetch_assoc($request)) { + if (!empty($row['id_ban'])) { + $ban_items[$row['id_ban']] = [ 'id' => $row['id_ban'], - ); + ]; - if (!empty($row['ip_high'])) - { + if (!empty($row['ip_high'])) { $ban_items[$row['id_ban']]['type'] = 'ip'; $ban_items[$row['id_ban']]['ip'] = IP::range2ip($row['ip_low'], $row['ip_high']); $is_range = (strpos($ban_items[$row['id_ban']]['ip'], '-') !== false || strpos($ban_items[$row['id_ban']]['ip'], '*') !== false); - $log_info[] = array( + $log_info[] = [ 'bantype' => ($is_range ? 'ip_range' : 'main_ip'), 'value' => $ban_items[$row['id_ban']]['ip'], - ); - } - elseif (!empty($row['hostname'])) - { + ]; + } elseif (!empty($row['hostname'])) { $ban_items[$row['id_ban']]['type'] = 'hostname'; $ban_items[$row['id_ban']]['hostname'] = str_replace('%', '*', $row['hostname']); - $log_info[] = array( + $log_info[] = [ 'bantype' => 'hostname', 'value' => $row['hostname'], - ); - } - elseif (!empty($row['email_address'])) - { + ]; + } elseif (!empty($row['email_address'])) { $ban_items[$row['id_ban']]['type'] = 'email'; $ban_items[$row['id_ban']]['email'] = str_replace('%', '*', $row['email_address']); - $log_info[] = array( + $log_info[] = [ 'bantype' => 'email', 'value' => $ban_items[$row['id_ban']]['email'], - ); - } - elseif (!empty($row['id_member'])) - { + ]; + } elseif (!empty($row['id_member'])) { $ban_items[$row['id_ban']]['type'] = 'user'; - $ban_items[$row['id_ban']]['user'] = array( + $ban_items[$row['id_ban']]['user'] = [ 'id' => $row['id_member'], 'name' => $row['real_name'], 'href' => Config::$scripturl . '?action=profile;u=' . $row['id_member'], 'link' => '' . $row['real_name'] . '', - ); + ]; - $log_info[] = array( + $log_info[] = [ 'bantype' => 'user', 'value' => $row['id_member'], - ); + ]; } } } @@ -2630,26 +2597,27 @@ protected static function removeBanTriggers($items_ids = array(), $group_id = nu // Log this! self::logTriggersUpdates($log_info, false, true); - if (isset($group_id)) - { - Db::$db->query('', ' + if (isset($group_id)) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}ban_items WHERE id_ban IN ({array_int:ban_list}) AND id_ban_group = {int:ban_group}', - array( + [ 'ban_list' => $items_ids, 'ban_group' => $group_id, - ) + ], ); - } - elseif (!empty($items_ids)) - { - Db::$db->query('', ' + } elseif (!empty($items_ids)) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}ban_items WHERE id_ban IN ({array_int:ban_list})', - array( + [ 'ban_list' => $items_ids, - ) + ], ); } @@ -2667,32 +2635,33 @@ protected static function removeBanTriggers($items_ids = array(), $group_id = nu */ protected static function logTriggersUpdates($logs, $new = true, $removal = false): void { - if (empty($logs)) + if (empty($logs)) { return; + } - $log_name_map = array( + $log_name_map = [ 'main_ip' => 'ip_range', 'hostname' => 'hostname', 'email' => 'email', 'user' => 'member', 'ip_range' => 'ip_range', - ); + ]; // Log the addion of the ban entries into the moderation log. - foreach ($logs as $log) - { - Logging::logAction('ban' . ($removal == true ? 'remove' : ''), array( + foreach ($logs as $log) { + Logging::logAction('ban' . ($removal == true ? 'remove' : ''), [ $log_name_map[$log['bantype']] => $log['value'], 'new' => empty($new) ? 0 : 1, 'remove' => empty($removal) ? 0 : 1, 'type' => $log['bantype'], - )); + ]); } } } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Bans::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Bans::exportStatic')) { Bans::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Boards.php b/Sources/Actions/Admin/Boards.php index d42fbd2b05..3769f08913 100644 --- a/Sources/Actions/Admin/Boards.php +++ b/Sources/Actions/Admin/Boards.php @@ -13,13 +13,13 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\BackwardCompatibility; use SMF\BBCodeParser; use SMF\Board; use SMF\Category; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\ErrorHandler; use SMF\Group; use SMF\IntegrationHook; @@ -30,7 +30,6 @@ use SMF\Url; use SMF\User; use SMF\Utils; -use SMF\Db\DatabaseApi as Db; /** * Manages and maintains the boards and categories of the forum. @@ -44,12 +43,12 @@ class Boards implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'ManageBoards', 'editBoardSettings' => 'EditBoardSettings', - ), - ); + ], + ]; /***************** * Class constants @@ -80,17 +79,17 @@ class Boards implements ActionInterface * * Format: 'sub-action' => array('function', 'permission') */ - public static array $subactions = array( - 'main' => array('main', 'manage_boards'), - 'board' => array('editBoard', 'manage_boards'), - 'board2' => array('editBoard2', 'manage_boards'), - 'cat' => array('editCategory', 'manage_boards'), - 'cat2' => array('editCategory2', 'manage_boards'), - 'move' => array('main', 'manage_boards'), - 'newcat' => array('editCategory', 'manage_boards'), - 'newboard' => array('editBoard', 'manage_boards'), - 'settings' => array('settings', 'admin_forum'), - ); + public static array $subactions = [ + 'main' => ['main', 'manage_boards'], + 'board' => ['editBoard', 'manage_boards'], + 'board2' => ['editBoard2', 'manage_boards'], + 'cat' => ['editCategory', 'manage_boards'], + 'cat2' => ['editCategory2', 'manage_boards'], + 'move' => ['main', 'manage_boards'], + 'newcat' => ['editCategory', 'manage_boards'], + 'newboard' => ['editBoard', 'manage_boards'], + 'settings' => ['settings', 'admin_forum'], + ]; /********************* * Internal properties @@ -122,10 +121,11 @@ public function execute(): void // Have you got the proper permissions? User::$me->isAllowedTo(self::$subactions[$this->subaction][1]); - $call = method_exists($this, self::$subactions[$this->subaction][0]) ? array($this, self::$subactions[$this->subaction][0]) : Utils::getCallable(self::$subactions[$this->subaction][0]); + $call = method_exists($this, self::$subactions[$this->subaction][0]) ? [$this, self::$subactions[$this->subaction][0]] : Utils::getCallable(self::$subactions[$this->subaction][0]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } /** @@ -140,26 +140,22 @@ public function main(): void { Theme::loadTemplate('ManageBoards'); - if (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'move' && in_array($_REQUEST['move_to'], array('child', 'before', 'after', 'top'))) - { + if (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'move' && in_array($_REQUEST['move_to'], ['child', 'before', 'after', 'top'])) { User::$me->checkSession('get'); SecurityToken::validate('admin-bm-' . (int) $_REQUEST['src_board'], 'request'); - if ($_REQUEST['move_to'] === 'top') - { - $boardOptions = array( + if ($_REQUEST['move_to'] === 'top') { + $boardOptions = [ 'move_to' => $_REQUEST['move_to'], 'target_category' => (int) $_REQUEST['target_cat'], 'move_first_child' => true, - ); - } - else - { - $boardOptions = array( + ]; + } else { + $boardOptions = [ 'move_to' => $_REQUEST['move_to'], 'target_board' => (int) $_REQUEST['target_board'], 'move_first_child' => true, - ); + ]; } Board::modify((int) $_REQUEST['src_board'], $boardOptions); @@ -169,21 +165,19 @@ public function main(): void Utils::$context['move_board'] = !empty($_REQUEST['move']) && isset(Board::$loaded[(int) $_REQUEST['move']]) ? (int) $_REQUEST['move'] : 0; - Utils::$context['categories'] = array(); + Utils::$context['categories'] = []; - foreach (Category::$loaded as $catid => $tree) - { - Utils::$context['categories'][$catid] = array( + foreach (Category::$loaded as $catid => $tree) { + Utils::$context['categories'][$catid] = [ 'name' => &$tree->name, 'id' => &$tree->id, - 'boards' => array() - ); + 'boards' => [], + ]; $move_cat = !empty(Utils::$context['move_board']) && Board::$loaded[Utils::$context['move_board']]->category == $catid; - foreach (Category::$boardList[$catid] as $boardid) - { - Utils::$context['categories'][$catid]['boards'][$boardid] = array( + foreach (Category::$boardList[$catid] as $boardid) { + Utils::$context['categories'][$catid]['boards'][$boardid] = [ 'id' => &Board::$loaded[$boardid]->id, 'name' => &Board::$loaded[$boardid]->name, 'description' => &Board::$loaded[$boardid]->description, @@ -191,71 +185,60 @@ public function main(): void 'move' => $move_cat && ($boardid == Utils::$context['move_board'] || Board::isChildOf($boardid, Utils::$context['move_board'])), 'permission_profile' => &Board::$loaded[$boardid]->profile, 'is_redirect' => !empty(Board::$loaded[$boardid]->redirect), - ); + ]; } } - if (!empty(Utils::$context['move_board'])) - { + if (!empty(Utils::$context['move_board'])) { SecurityToken::create('admin-bm-' . Utils::$context['move_board'], 'request'); Utils::$context['move_title'] = sprintf(Lang::$txt['mboards_select_destination'], Utils::htmlspecialchars(Board::$loaded[Utils::$context['move_board']]->name)); - foreach (Category::$loaded as $catid => $tree) - { + foreach (Category::$loaded as $catid => $tree) { $prev_child_level = 0; $prev_board = 0; - $stack = array(); + $stack = []; // Just a shortcut, this is the same for all the urls $security = Utils::$context['session_var'] . '=' . Utils::$context['session_id'] . ';' . Utils::$context['admin-bm-' . Utils::$context['move_board'] . '_token_var'] . '=' . Utils::$context['admin-bm-' . Utils::$context['move_board'] . '_token']; - foreach (Category::$boardList[$catid] as $boardid) - { - if (!isset(Utils::$context['categories'][$catid]['move_link'])) - { - Utils::$context['categories'][$catid]['move_link'] = array( + foreach (Category::$boardList[$catid] as $boardid) { + if (!isset(Utils::$context['categories'][$catid]['move_link'])) { + Utils::$context['categories'][$catid]['move_link'] = [ 'child_level' => 0, 'label' => Lang::$txt['mboards_order_before'] . ' \'' . Utils::htmlspecialchars(Board::$loaded[$boardid]->name) . '\'', 'href' => Config::$scripturl . '?action=admin;area=manageboards;sa=move;src_board=' . Utils::$context['move_board'] . ';target_board=' . $boardid . ';move_to=before;' . $security, - ); + ]; } - if (!Utils::$context['categories'][$catid]['boards'][$boardid]['move']) - { - Utils::$context['categories'][$catid]['boards'][$boardid]['move_links'] = array( - array( + if (!Utils::$context['categories'][$catid]['boards'][$boardid]['move']) { + Utils::$context['categories'][$catid]['boards'][$boardid]['move_links'] = [ + [ 'child_level' => Board::$loaded[$boardid]->child_level, 'label' => Lang::$txt['mboards_order_after'] . '\'' . Utils::htmlspecialchars(Board::$loaded[$boardid]->name) . '\'', 'href' => Config::$scripturl . '?action=admin;area=manageboards;sa=move;src_board=' . Utils::$context['move_board'] . ';target_board=' . $boardid . ';move_to=after;' . $security, 'class' => Board::$loaded[$boardid]->child_level > 0 ? 'above' : 'below', - ), - array( + ], + [ 'child_level' => Board::$loaded[$boardid]->child_level + 1, 'label' => Lang::$txt['mboards_order_child_of'] . ' \'' . Utils::htmlspecialchars(Board::$loaded[$boardid]->name) . '\'', 'href' => Config::$scripturl . '?action=admin;area=manageboards;sa=move;src_board=' . Utils::$context['move_board'] . ';target_board=' . $boardid . ';move_to=child;' . $security, 'class' => 'here', - ), - ); + ], + ]; } $difference = Board::$loaded[$boardid]->child_level - $prev_child_level; - if ($difference == 1) - { + if ($difference == 1) { array_push($stack, !empty(Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links']) ? array_shift(Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links']) : null); - } - elseif ($difference < 0) - { - if (empty(Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links'])) - { - Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links'] = array(); + } elseif ($difference < 0) { + if (empty(Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links'])) { + Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links'] = []; } - for ($i = 0; $i < -$difference; $i++) - { - if (($temp = array_pop($stack)) != null) - { + for ($i = 0; $i < -$difference; $i++) { + if (($temp = array_pop($stack)) != null) { array_unshift(Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links'], $temp); } } @@ -265,22 +248,18 @@ public function main(): void $prev_child_level = Board::$loaded[$boardid]->child_level; } - if (!empty($stack) && !empty(Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links'])) - { + if (!empty($stack) && !empty(Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links'])) { Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links'] = array_merge($stack, Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links']); - } - elseif (!empty($stack)) - { + } elseif (!empty($stack)) { Utils::$context['categories'][$catid]['boards'][$prev_board]['move_links'] = $stack; } - if (empty(Category::$boardList[$catid])) - { - Utils::$context['categories'][$catid]['move_link'] = array( + if (empty(Category::$boardList[$catid])) { + Utils::$context['categories'][$catid]['move_link'] = [ 'child_level' => 0, 'label' => Lang::$txt['mboards_order_before'] . ' \'' . Utils::htmlspecialchars($tree->name) . '\'', 'href' => Config::$scripturl . '?action=admin;area=manageboards;sa=move;src_board=' . Utils::$context['move_board'] . ';target_cat=' . $catid . ';move_to=top;' . $security, - ); + ]; } } } @@ -313,78 +292,67 @@ public function editCategory(): void $_REQUEST['cat'] = isset($_REQUEST['cat']) ? (int) $_REQUEST['cat'] : 0; // Start with one - "In first place". - Utils::$context['category_order'] = array( - array( + Utils::$context['category_order'] = [ + [ 'id' => 0, 'name' => Lang::$txt['mboards_order_first'], 'selected' => !empty($_REQUEST['cat']) ? Category::$loaded[$_REQUEST['cat']]->is_first : false, - 'true_name' => '' - ) - ); + 'true_name' => '', + ], + ]; // If this is a new category set up some defaults. - if ($_REQUEST['sa'] == 'newcat') - { - Utils::$context['category'] = array( + if ($_REQUEST['sa'] == 'newcat') { + Utils::$context['category'] = [ 'id' => 0, 'name' => Lang::$txt['mboards_new_cat_name'], 'editable_name' => Utils::htmlspecialchars(Lang::$txt['mboards_new_cat_name']), 'description' => '', 'can_collapse' => true, 'is_new' => true, - 'is_empty' => true - ); + 'is_empty' => true, + ]; } // Category doesn't exist, man... sorry. - elseif (!isset(Category::$loaded[$_REQUEST['cat']])) - { + elseif (!isset(Category::$loaded[$_REQUEST['cat']])) { Utils::redirectexit('action=admin;area=manageboards'); - } - else - { - Utils::$context['category'] = array( + } else { + Utils::$context['category'] = [ 'id' => $_REQUEST['cat'], 'name' => Category::$loaded[$_REQUEST['cat']]->name, 'editable_name' => Category::$loaded[$_REQUEST['cat']]->name, 'description' => Category::$loaded[$_REQUEST['cat']]->description, 'can_collapse' => !empty(Category::$loaded[$_REQUEST['cat']]->can_collapse), - 'children' => array(), - 'is_empty' => empty(Category::$loaded[$_REQUEST['cat']]->children) - ); + 'children' => [], + 'is_empty' => empty(Category::$loaded[$_REQUEST['cat']]->children), + ]; - foreach (Category::$boardList[$_REQUEST['cat']] as $child_board) - { + foreach (Category::$boardList[$_REQUEST['cat']] as $child_board) { Utils::$context['category']['children'][] = str_repeat('-', Board::$loaded[$child_board]->child_level) . ' ' . Board::$loaded[$child_board]->name; } } $prevCat = 0; - foreach (Category::$loaded as $catid => $tree) - { - if ($catid == $_REQUEST['cat'] && $prevCat > 0) - { + + foreach (Category::$loaded as $catid => $tree) { + if ($catid == $_REQUEST['cat'] && $prevCat > 0) { Utils::$context['category_order'][$prevCat]['selected'] = true; - } - elseif ($catid != $_REQUEST['cat']) - { - Utils::$context['category_order'][$catid] = array( + } elseif ($catid != $_REQUEST['cat']) { + Utils::$context['category_order'][$catid] = [ 'id' => $catid, 'name' => Lang::$txt['mboards_order_after'] . $tree->name, 'selected' => false, - 'true_name' => $tree->name - ); + 'true_name' => $tree->name, + ]; } $prevCat = $catid; } - if (!isset($_REQUEST['delete'])) - { + if (!isset($_REQUEST['delete'])) { Utils::$context['sub_template'] = 'modify_category'; Utils::$context['page_title'] = $_REQUEST['sa'] == 'newcat' ? Lang::$txt['mboards_new_cat_name'] : Lang::$txt['cat_edit']; - } - else - { + } else { Utils::$context['sub_template'] = 'confirm_category_delete'; Utils::$context['page_title'] = Lang::$txt['mboards_delete_cat']; } @@ -414,47 +382,41 @@ public function editCategory2(): void $_POST['cat'] = (int) $_POST['cat']; // Add a new category or modify an existing one.. - if (isset($_POST['edit']) || isset($_POST['add'])) - { - $catOptions = array(); + if (isset($_POST['edit']) || isset($_POST['add'])) { + $catOptions = []; - if (isset($_POST['cat_order'])) + if (isset($_POST['cat_order'])) { $catOptions['move_after'] = (int) $_POST['cat_order']; + } // Try and get any valid HTML to BBC first, add a naive attempt to strip it off, htmlspecialchars for the rest $catOptions['cat_name'] = Utils::htmlspecialchars(strip_tags($_POST['cat_name'])); $catOptions['cat_desc'] = Utils::htmlspecialchars(strip_tags(BBCodeParser::load()->unparse($_POST['cat_desc']))); $catOptions['is_collapsible'] = isset($_POST['collapse']); - if (isset($_POST['add'])) - { + if (isset($_POST['add'])) { Category::create($catOptions); - } - else - { + } else { Category::modify($_POST['cat'], $catOptions); } } // If they want to delete - first give them confirmation. - elseif (isset($_POST['delete']) && !isset($_POST['confirmation']) && !isset($_POST['empty'])) - { + elseif (isset($_POST['delete']) && !isset($_POST['confirmation']) && !isset($_POST['empty'])) { $this->editCategory(); + return; } // Delete the category! - elseif (isset($_POST['delete'])) - { + elseif (isset($_POST['delete'])) { // First off - check if we are moving all the current boards first - before we start deleting! - if (isset($_POST['delete_action']) && $_POST['delete_action'] == 1) - { - if (empty($_POST['cat_to'])) + if (isset($_POST['delete_action']) && $_POST['delete_action'] == 1) { + if (empty($_POST['cat_to'])) { ErrorHandler::fatalLang('mboards_delete_error'); + } - Category::delete(array($_POST['cat']), (int) $_POST['cat_to']); - } - else - { - Category::delete(array($_POST['cat'])); + Category::delete([$_POST['cat']], (int) $_POST['cat_to']); + } else { + Category::delete([$_POST['cat']]); } } @@ -486,28 +448,27 @@ public function editBoard(): void // id_board must be a number.... $_REQUEST['boardid'] = isset($_REQUEST['boardid']) ? (int) $_REQUEST['boardid'] : 0; - if (!isset(Board::$loaded[$_REQUEST['boardid']])) - { + if (!isset(Board::$loaded[$_REQUEST['boardid']])) { $_REQUEST['boardid'] = 0; $_REQUEST['sa'] = 'newboard'; } - if ('newboard' === $_REQUEST['sa']) - { + if ('newboard' === $_REQUEST['sa']) { // Category doesn't exist, man... sorry. - if (empty($_REQUEST['cat'])) + if (empty($_REQUEST['cat'])) { Utils::redirectexit('action=admin;area=manageboards'); + } // Some things that need to be setup for a new board. - $curBoard = array( - 'member_groups' => array(0, -1), - 'deny_groups' => array(), - 'category' => (int) $_REQUEST['cat'] - ); + $curBoard = [ + 'member_groups' => [0, -1], + 'deny_groups' => [], + 'category' => (int) $_REQUEST['cat'], + ]; - Utils::$context['board_order'] = array(); + Utils::$context['board_order'] = []; - Utils::$context['board'] = Board::init(0, array( + Utils::$context['board'] = Board::init(0, [ 'is_new' => true, 'name' => Lang::$txt['mboards_new_board_name'], 'description' => '', @@ -520,10 +481,8 @@ public function editBoard(): void 'redirect' => '', 'category' => (int) $_REQUEST['cat'], 'no_children' => true, - )); - } - else - { + ]); + } else { // Just some easy shortcuts. $curBoard = &Board::$loaded[$_REQUEST['boardid']]; @@ -544,8 +503,7 @@ public function editBoard(): void Utils::$context['can_manage_permissions'] = User::$me->allowedTo('manage_permissions'); // Load all membergroups except admin and moderator. - foreach (Group::loadSimple(Group::LOAD_BOTH, array(Group::ADMIN, Group::MOD)) as $group) - { + foreach (Group::loadSimple(Group::LOAD_BOTH, [Group::ADMIN, Group::MOD]) as $group) { $group->allow = in_array($group->id, $curBoard['member_groups']); $group->deny = in_array($group->id, $curBoard['deny_groups']); @@ -555,133 +513,129 @@ public function editBoard(): void } // Category doesn't exist, man... sorry. - if (!isset(Category::$boardList[$curBoard['category']])) + if (!isset(Category::$boardList[$curBoard['category']])) { Utils::redirectexit('action=admin;area=manageboards'); + } - foreach (Category::$boardList[$curBoard['category']] as $boardid) - { - if ($boardid == $_REQUEST['boardid']) - { - Utils::$context['board_order'][] = array( + foreach (Category::$boardList[$curBoard['category']] as $boardid) { + if ($boardid == $_REQUEST['boardid']) { + Utils::$context['board_order'][] = [ 'id' => $boardid, 'name' => str_repeat('-', Board::$loaded[$boardid]->child_level) . ' (' . Lang::$txt['mboards_current_position'] . ')', 'children' => Board::$loaded[$boardid]->children, 'no_children' => empty(Board::$loaded[$boardid]->children), 'is_child' => false, - 'selected' => true - ); - } - else - { - Utils::$context['board_order'][] = array( + 'selected' => true, + ]; + } else { + Utils::$context['board_order'][] = [ 'id' => $boardid, 'name' => str_repeat('-', Board::$loaded[$boardid]->child_level) . ' ' . Board::$loaded[$boardid]->name, 'is_child' => empty($_REQUEST['boardid']) ? false : Board::isChildOf($boardid, $_REQUEST['boardid']), - 'selected' => false - ); + 'selected' => false, + ]; } } // Are there any places to move child boards to in the case where we are confirming a delete? - if (!empty($_REQUEST['boardid'])) - { + if (!empty($_REQUEST['boardid'])) { Utils::$context['can_move_children'] = false; Utils::$context['children'] = Board::$loaded[$_REQUEST['boardid']]->children; - foreach (Utils::$context['board_order'] as $lBoard) - { - if ($lBoard['is_child'] == false && $lBoard['selected'] == false) + foreach (Utils::$context['board_order'] as $lBoard) { + if ($lBoard['is_child'] == false && $lBoard['selected'] == false) { Utils::$context['can_move_children'] = true; + } } } // Get other available categories. - Utils::$context['categories'] = array(); + Utils::$context['categories'] = []; - foreach (Category::$loaded as $catID => $tree) - { - Utils::$context['categories'][] = array( + foreach (Category::$loaded as $catID => $tree) { + Utils::$context['categories'][] = [ 'id' => $catID == $curBoard['category'] ? 0 : $catID, 'name' => $tree->name, - 'selected' => $catID == $curBoard['category'] - ); + 'selected' => $catID == $curBoard['category'], + ]; } // Get all the moderators. - Utils::$context['board']->moderators = array(); + Utils::$context['board']->moderators = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT mem.id_member, mem.real_name FROM {db_prefix}moderators AS mods INNER JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member) WHERE mods.id_board = {int:current_board}', - array( + [ 'current_board' => $_REQUEST['boardid'], - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { Utils::$context['board']->moderators[$row['id_member']] = $row['real_name']; } Db::$db->free_result($request); Utils::$context['board']->moderator_list = empty(Utils::$context['board']->moderators) ? '' : '"' . implode('", "', Utils::$context['board']->moderators) . '"'; - if (!empty(Utils::$context['board']->moderators)) - { - list (Utils::$context['board']->last_moderator_id) = array_slice(array_keys(Utils::$context['board']->moderators), -1); + if (!empty(Utils::$context['board']->moderators)) { + list(Utils::$context['board']->last_moderator_id) = array_slice(array_keys(Utils::$context['board']->moderators), -1); } // Get all the groups assigned as moderators. - Utils::$context['board']->moderator_groups = array(); + Utils::$context['board']->moderator_groups = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_group FROM {db_prefix}moderator_groups WHERE id_board = {int:current_board}', - array( + [ 'current_board' => $_REQUEST['boardid'], - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { Utils::$context['board']->moderator_groups[$row['id_group']] = Utils::$context['groups'][$row['id_group']]['name']; } Db::$db->free_result($request); Utils::$context['board']->moderator_groups_list = empty(Utils::$context['board']->moderator_groups) ? '' : '"' . implode('", &qout;', Utils::$context['board']->moderator_groups) . '"'; - if (!empty(Utils::$context['board']->moderator_groups)) - { - list (Utils::$context['board']->last_moderator_group_id) = array_slice(array_keys(Utils::$context['board']->moderator_groups), -1); + if (!empty(Utils::$context['board']->moderator_groups)) { + list(Utils::$context['board']->last_moderator_group_id) = array_slice(array_keys(Utils::$context['board']->moderator_groups), -1); } // Get all the themes... - Utils::$context['themes'] = array(); + Utils::$context['themes'] = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_theme AS id, value AS name FROM {db_prefix}themes WHERE variable = {literal:name} AND id_theme IN ({array_int:enable_themes})', - array( + [ 'enable_themes' => explode(',', Config::$modSettings['enableThemes']), - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { Utils::$context['themes'][] = $row; } Db::$db->free_result($request); - if (!isset($_REQUEST['delete'])) - { + if (!isset($_REQUEST['delete'])) { Utils::$context['sub_template'] = 'modify_board'; Utils::$context['page_title'] = Lang::$txt['boards_edit']; - Theme::loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest'); - } - else - { + Theme::loadJavaScriptFile('suggest.js', ['defer' => false, 'minimize' => true], 'smf_suggest'); + } else { Utils::$context['sub_template'] = 'confirm_board_delete'; Utils::$context['page_title'] = Lang::$txt['mboards_delete_board']; } @@ -710,21 +664,19 @@ public function editBoard2(): void SecurityToken::validate('admin-be-' . $_REQUEST['boardid']); // Mode: modify aka. don't delete. - if (isset($_POST['edit']) || isset($_POST['add'])) - { - $boardOptions = array(); + if (isset($_POST['edit']) || isset($_POST['add'])) { + $boardOptions = []; // Move this board to a new category? - if (!empty($_POST['new_cat'])) - { + if (!empty($_POST['new_cat'])) { $boardOptions['move_to'] = 'bottom'; $boardOptions['target_category'] = (int) $_POST['new_cat']; } // Change the boardorder of this board? - elseif (!empty($_POST['placement']) && !empty($_POST['board_order'])) - { - if (!in_array($_POST['placement'], array('before', 'after', 'child'))) + elseif (!empty($_POST['placement']) && !empty($_POST['board_order'])) { + if (!in_array($_POST['placement'], ['before', 'after', 'child'])) { ErrorHandler::fatalLang('mangled_post', false); + } $boardOptions['move_to'] = $_POST['placement']; $boardOptions['target_board'] = (int) $_POST['board_order']; @@ -734,26 +686,20 @@ public function editBoard2(): void $boardOptions['posts_count'] = isset($_POST['count']); $boardOptions['override_theme'] = isset($_POST['override_theme']); $boardOptions['board_theme'] = (int) $_POST['boardtheme']; - $boardOptions['access_groups'] = array(); - $boardOptions['deny_groups'] = array(); - - if (!empty($_POST['groups'])) - { - foreach ($_POST['groups'] as $group => $action) - { - if ($action == 'allow') - { + $boardOptions['access_groups'] = []; + $boardOptions['deny_groups'] = []; + + if (!empty($_POST['groups'])) { + foreach ($_POST['groups'] as $group => $action) { + if ($action == 'allow') { $boardOptions['access_groups'][] = (int) $group; - } - elseif ($action == 'deny') - { + } elseif ($action == 'deny') { $boardOptions['deny_groups'][] = (int) $group; } } } - if (strlen(implode(',', $boardOptions['access_groups'])) > 255 || strlen(implode(',', $boardOptions['deny_groups'])) > 255) - { + if (strlen(implode(',', $boardOptions['access_groups'])) > 255 || strlen(implode(',', $boardOptions['deny_groups'])) > 255) { ErrorHandler::fatalLang('too_many_groups', false); } @@ -763,24 +709,24 @@ public function editBoard2(): void $boardOptions['moderator_string'] = $_POST['moderators']; - if (isset($_POST['moderator_list']) && is_array($_POST['moderator_list'])) - { - $moderators = array(); + if (isset($_POST['moderator_list']) && is_array($_POST['moderator_list'])) { + $moderators = []; - foreach ($_POST['moderator_list'] as $moderator) + foreach ($_POST['moderator_list'] as $moderator) { $moderators[(int) $moderator] = (int) $moderator; + } $boardOptions['moderators'] = $moderators; } $boardOptions['moderator_group_string'] = $_POST['moderator_groups']; - if (isset($_POST['moderator_group_list']) && is_array($_POST['moderator_group_list'])) - { - $moderator_groups = array(); + if (isset($_POST['moderator_group_list']) && is_array($_POST['moderator_group_list'])) { + $moderator_groups = []; - foreach ($_POST['moderator_group_list'] as $moderator_group) + foreach ($_POST['moderator_group_list'] as $moderator_group) { $moderator_groups[(int) $moderator_group] = (int) $moderator_group; + } $boardOptions['moderator_groups'] = $moderator_groups; } @@ -793,32 +739,30 @@ public function editBoard2(): void $boardOptions['inherit_permissions'] = $_POST['profile'] == -1; // We need to know what used to be case in terms of redirection. - if (!empty($_POST['boardid'])) - { - $request = Db::$db->query('', ' + if (!empty($_POST['boardid'])) { + $request = Db::$db->query( + '', + ' SELECT redirect, num_posts, id_cat FROM {db_prefix}boards WHERE id_board = {int:current_board}', - array( + [ 'current_board' => $_POST['boardid'], - ) + ], ); - list ($oldRedirect, $numPosts, $old_id_cat) = Db::$db->fetch_row($request); + list($oldRedirect, $numPosts, $old_id_cat) = Db::$db->fetch_row($request); Db::$db->free_result($request); // If we're turning redirection on check the board doesn't have posts in it - if it does don't make it a redirection board. - if ($boardOptions['redirect'] && empty($oldRedirect) && $numPosts) - { + if ($boardOptions['redirect'] && empty($oldRedirect) && $numPosts) { unset($boardOptions['redirect']); } // Reset the redirection count when switching on/off. - elseif (empty($boardOptions['redirect']) != empty($oldRedirect)) - { + elseif (empty($boardOptions['redirect']) != empty($oldRedirect)) { $boardOptions['num_posts'] = 0; } // Resetting the count? - elseif ($boardOptions['redirect'] && !empty($_POST['reset_redirect'])) - { + elseif ($boardOptions['redirect'] && !empty($_POST['reset_redirect'])) { $boardOptions['num_posts'] = 0; } @@ -826,50 +770,42 @@ public function editBoard2(): void } // Create a new board... - if (isset($_POST['add'])) - { + if (isset($_POST['add'])) { // New boards by default go to the bottom of the category. - if (empty($_POST['new_cat'])) + if (empty($_POST['new_cat'])) { $boardOptions['target_category'] = (int) $_POST['cur_cat']; + } - if (!isset($boardOptions['move_to'])) + if (!isset($boardOptions['move_to'])) { $boardOptions['move_to'] = 'bottom'; + } Board::create($boardOptions); } // ...or update an existing board. - else - { + else { Board::modify($_POST['boardid'], $boardOptions); } - } - elseif (isset($_POST['delete']) && !isset($_POST['confirmation']) && !isset($_POST['no_children'])) - { + } elseif (isset($_POST['delete']) && !isset($_POST['confirmation']) && !isset($_POST['no_children'])) { $this->editBoard(); + return; - } - elseif (isset($_POST['delete'])) - { + } elseif (isset($_POST['delete'])) { // First off - check if we are moving all the current child boards first - before we start deleting! - if (isset($_POST['delete_action']) && $_POST['delete_action'] == 1) - { - if (empty($_POST['board_to'])) + if (isset($_POST['delete_action']) && $_POST['delete_action'] == 1) { + if (empty($_POST['board_to'])) { ErrorHandler::fatalLang('mboards_delete_board_error'); + } - Board::delete(array($_POST['boardid']), (int) $_POST['board_to']); - } - else - { - Board::delete(array($_POST['boardid']), 0); + Board::delete([$_POST['boardid']], (int) $_POST['board_to']); + } else { + Board::delete([$_POST['boardid']], 0); } } - if (isset($_REQUEST['rid']) && $_REQUEST['rid'] == 'permissions') - { + if (isset($_REQUEST['rid']) && $_REQUEST['rid'] == 'permissions') { Utils::redirectexit('action=admin;area=permissions;sa=board;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']); - } - else - { + } else { Utils::redirectexit('action=admin;area=manageboards'); } } @@ -883,31 +819,34 @@ public function modifyCat(): void Category::getTree(); // Allowed sub-actions... - $allowed_sa = array('add', 'modify', 'cut'); + $allowed_sa = ['add', 'modify', 'cut']; // Check our input. $_POST['id'] = empty($_POST['id']) ? array_keys((array) Board::$info) : (int) $_POST['id']; $_POST['id'] = substr($_POST['id'][1], 0, 3); // Select the stuff we need from the DB. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT CONCAT({string:post_id}, {string:feline_clause}, {string:subact}) FROM {db_prefix}categories LIMIT 1', - array( + [ 'post_id' => $_POST['id'] . 's ar', 'feline_clause' => 'e,o ', 'subact' => $allowed_sa[2] . 'e, ', - ) + ], ); - list ($cat) = Db::$db->fetch_row($request); + list($cat) = Db::$db->fetch_row($request); // Free resources. Db::$db->free_result($request); // This would probably never happen, but just to be sure. - if ($cat .= $allowed_sa[1]) + if ($cat .= $allowed_sa[1]) { die(str_replace(',', ' to', $cat)); + } Utils::redirectexit(); } @@ -934,8 +873,7 @@ public function settings(): void Utils::$context['force_form_onsubmit'] = 'if(document.getElementById(\'recycle_enable\').checked && document.getElementById(\'recycle_board\').value == 0) { return confirm(\'' . Lang::$txt['recycle_board_unselected_notice'] . '\');} return true;'; // Doing a save? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); IntegrationHook::call('integrate_save_board_settings'); @@ -963,8 +901,9 @@ public function settings(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -985,48 +924,52 @@ public static function call(): void public static function getConfigVars(): array { // Load the boards list - for the recycle bin! - $request = Db::$db->query('order_by_board_order', ' + $request = Db::$db->query( + 'order_by_board_order', + ' SELECT b.id_board, b.name AS board_name, c.name AS cat_name FROM {db_prefix}boards AS b LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat) WHERE redirect = {string:empty_string}', - array( + [ 'empty_string' => '', - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $recycle_boards[$row['id_board']] = $row['cat_name'] . ' - ' . $row['board_name']; } Db::$db->free_result($request); - if (!empty($recycle_boards)) + if (!empty($recycle_boards)) { Board::sort($recycle_boards); + } - $recycle_boards = array('') + ($recycle_boards ?? array()); + $recycle_boards = [''] + ($recycle_boards ?? []); // If this setting is missing, set it to 1 - if (empty(Config::$modSettings['boardindex_max_depth'])) + if (empty(Config::$modSettings['boardindex_max_depth'])) { Config::$modSettings['boardindex_max_depth'] = 1; + } // Here are the board settings... - $config_vars = array( - array('title', 'settings'), + $config_vars = [ + ['title', 'settings'], // Inline permissions. - array('permissions', 'manage_boards'), + ['permissions', 'manage_boards'], '', // Other board settings. - array('int', 'boardindex_max_depth', 'step' => 1, 'min' => 1, 'max' => 100), - array('check', 'countChildPosts'), - array('check', 'recycle_enable', 'onclick' => 'document.getElementById(\'recycle_board\').disabled = !this.checked;'), - array('select', 'recycle_board', $recycle_boards), - array('check', 'allow_ignore_boards'), - array('check', 'deny_boards_access'), - ); + ['int', 'boardindex_max_depth', 'step' => 1, 'min' => 1, 'max' => 100], + ['check', 'countChildPosts'], + ['check', 'recycle_enable', 'onclick' => 'document.getElementById(\'recycle_board\').disabled = !this.checked;'], + ['select', 'recycle_board', $recycle_boards], + ['check', 'allow_ignore_boards'], + ['check', 'deny_boards_access'], + ]; - IntegrationHook::call('integrate_modify_board_settings', array(&$config_vars)); + IntegrationHook::call('integrate_modify_board_settings', [&$config_vars]); return $config_vars; } @@ -1039,8 +982,9 @@ public static function getConfigVars(): array */ public static function editBoardSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::getConfigVars(); + } self::load(); self::$obj->subaction = 'settings'; @@ -1060,22 +1004,22 @@ protected function __construct() Lang::load('ManageBoards'); // Create the tabs for the template. - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['boards_and_cats'], 'help' => 'manage_boards', 'description' => Lang::$txt['boards_and_cats_desc'], - 'tabs' => array( - 'main' => array( - ), - 'newcat' => array( - ), - 'settings' => array( + 'tabs' => [ + 'main' => [ + ], + 'newcat' => [ + ], + 'settings' => [ 'description' => Lang::$txt['mboards_settings_desc'], - ), - ), - ); + ], + ], + ]; - IntegrationHook::call('integrate_manage_boards', array(&self::$subactions)); + IntegrationHook::call('integrate_manage_boards', [&self::$subactions]); // Default to sub action 'main' or 'settings' depending on permissions. $this->subaction = isset($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : (User::$me->allowedTo('manage_boards') ? 'main' : 'settings'); @@ -1090,7 +1034,8 @@ protected function __construct() } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Boards::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Boards::exportStatic')) { Boards::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Calendar.php b/Sources/Actions/Admin/Calendar.php index 3e27801ebb..ba8f2dd07e 100644 --- a/Sources/Actions/Admin/Calendar.php +++ b/Sources/Actions/Admin/Calendar.php @@ -15,11 +15,12 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\Actions\Calendar as Cal; +use SMF\BackwardCompatibility; use SMF\Board; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\IntegrationHook; use SMF\ItemList; use SMF\Lang; @@ -29,8 +30,6 @@ use SMF\Time; use SMF\User; use SMF\Utils; -use SMF\Actions\Calendar as Cal; -use SMF\Db\DatabaseApi as Db; /** * This class allows you to manage the calendar. @@ -44,13 +43,13 @@ class Calendar implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'ManageCalendar', 'modifyHolidays' => 'ModifyHolidays', 'editHoliday' => 'EditHoliday', - ), - ); + ], + ]; /******************* * Public properties @@ -73,11 +72,11 @@ class Calendar implements ActionInterface * * Available sub-actions. */ - public static array $subactions = array( + public static array $subactions = [ 'holidays' => 'holidays', 'editholiday' => 'edit', - 'settings' => 'settings' - ); + 'settings' => 'settings', + ]; /**************************** * Internal static properties @@ -102,10 +101,11 @@ public function execute(): void { User::$me->isAllowedTo('admin_forum'); - $call = method_exists($this, self::$subactions[$this->subaction]) ? array($this, self::$subactions[$this->subaction]) : Utils::getCallable(self::$subactions[$this->subaction]); + $call = method_exists($this, self::$subactions[$this->subaction]) ? [$this, self::$subactions[$this->subaction]] : Utils::getCallable(self::$subactions[$this->subaction]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } /** @@ -114,108 +114,107 @@ public function execute(): void public function holidays(): void { // Submitting something... - if (isset($_REQUEST['delete']) && !empty($_REQUEST['holiday'])) - { + if (isset($_REQUEST['delete']) && !empty($_REQUEST['holiday'])) { User::$me->checkSession(); SecurityToken::validate('admin-mc'); - foreach ($_REQUEST['holiday'] as $id => $value) + foreach ($_REQUEST['holiday'] as $id => $value) { $_REQUEST['holiday'][$id] = (int) $id; + } Cal::removeHolidays($_REQUEST['holiday']); } SecurityToken::create('admin-mc'); - $listOptions = array( + $listOptions = [ 'id' => 'holiday_list', 'title' => Lang::$txt['current_holidays'], 'items_per_page' => Config::$modSettings['defaultMaxListItems'], 'base_href' => Config::$scripturl . '?action=admin;area=managecalendar;sa=holidays', 'default_sort_col' => 'name', - 'get_items' => array( + 'get_items' => [ 'file' => Config::$sourcedir . '/Actions/Calendar.php', 'function' => 'SMF\\Actions\\Calendar::list_getHolidays', - ), - 'get_count' => array( + ], + 'get_count' => [ 'file' => Config::$sourcedir . '/Actions/Calendar.php', 'function' => 'SMF\\Actions\\Calendar::list_getNumHolidays', - ), + ], 'no_items_label' => Lang::$txt['holidays_no_entries'], - 'columns' => array( - 'name' => array( - 'header' => array( + 'columns' => [ + 'name' => [ + 'header' => [ 'value' => Lang::$txt['holidays_title'], - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '%2$s', - 'params' => array( + 'params' => [ 'id_holiday' => false, 'title' => false, - ), - ), - ), - 'sort' => array( + ], + ], + ], + 'sort' => [ 'default' => 'title ASC, event_date ASC', 'reverse' => 'title DESC, event_date ASC', - ) - ), - 'date' => array( - 'header' => array( + ], + ], + 'date' => [ + 'header' => [ 'value' => Lang::$txt['date'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { // Recurring every year or just a single year? $year = $rowData['year'] == '1004' ? sprintf('(%1$s)', Lang::$txt['every_year']) : $rowData['year']; // Construct the date. return sprintf('%1$d %2$s %3$s', $rowData['day'], Lang::$txt['months'][(int) $rowData['month']], $year); }, - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'event_date', 'reverse' => 'event_date DESC', - ), - ), - 'check' => array( - 'header' => array( + ], + ], + 'check' => [ + 'header' => [ 'value' => '', 'class' => 'centercol', - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '', - 'params' => array( + 'params' => [ 'id_holiday' => false, - ), - ), + ], + ], 'class' => 'centercol', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=managecalendar;sa=holidays', 'token' => 'admin-mc', - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'above_column_headers', 'value' => ' ' . Lang::$txt['holidays_add'] . '', - ), - array( + ], + [ 'position' => 'below_table_data', 'value' => ' ' . Lang::$txt['holidays_add'] . '', - ), - ), - ); + ], + ], + ]; new ItemList($listOptions); - //loadTemplate('ManageCalendar'); + // loadTemplate('ManageCalendar'); Utils::$context['page_title'] = Lang::$txt['manage_holidays']; // Since the list is the only thing to show, use the default list template. @@ -235,12 +234,12 @@ public function edit(): void Utils::$context['sub_template'] = 'edit_holiday'; // Cast this for safety... - if (isset($_REQUEST['holiday'])) + if (isset($_REQUEST['holiday'])) { $_REQUEST['holiday'] = (int) $_REQUEST['holiday']; + } // Submitting? - if (isset($_POST[Utils::$context['session_var']]) && (isset($_REQUEST['delete']) || $_REQUEST['title'] != '')) - { + if (isset($_POST[Utils::$context['session_var']]) && (isset($_REQUEST['delete']) || $_REQUEST['title'] != '')) { User::$me->checkSession(); SecurityToken::validate('admin-eh'); @@ -248,52 +247,51 @@ public function edit(): void $_REQUEST['title'] = Utils::entitySubstr(Utils::normalize($_REQUEST['title']), 0, 60); $_REQUEST['holiday'] = isset($_REQUEST['holiday']) ? (int) $_REQUEST['holiday'] : 0; - if (isset($_REQUEST['delete'])) - { - Db::$db->query('', ' + if (isset($_REQUEST['delete'])) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}calendar_holidays WHERE id_holiday = {int:selected_holiday}', - array( + [ 'selected_holiday' => $_REQUEST['holiday'], - ) + ], ); - } - else - { + } else { $date = Time::strftime($_REQUEST['year'] <= 1004 ? '1004-%m-%d' : '%Y-%m-%d', mktime(0, 0, 0, $_REQUEST['month'], $_REQUEST['day'], $_REQUEST['year'])); - if (isset($_REQUEST['edit'])) - { - Db::$db->query('', ' + if (isset($_REQUEST['edit'])) { + Db::$db->query( + '', + ' UPDATE {db_prefix}calendar_holidays SET event_date = {date:holiday_date}, title = {string:holiday_title} WHERE id_holiday = {int:selected_holiday}', - array( + [ 'holiday_date' => $date, 'selected_holiday' => $_REQUEST['holiday'], 'holiday_title' => $_REQUEST['title'], - ) + ], ); - } - else - { - Db::$db->insert('', + } else { + Db::$db->insert( + '', '{db_prefix}calendar_holidays', - array( + [ 'event_date' => 'date', 'title' => 'string-60', - ), - array( + ], + [ $date, $_REQUEST['title'], - ), - array('id_holiday') + ], + ['id_holiday'], ); } } - Config::updateModSettings(array( + Config::updateModSettings([ 'calendar_updated' => time(), 'settings_updated' => time(), - )); + ]); Utils::redirectexit('action=admin;area=managecalendar;sa=holidays'); } @@ -301,37 +299,37 @@ public function edit(): void SecurityToken::create('admin-eh'); // Default states... - if (Utils::$context['is_new']) - { - Utils::$context['holiday'] = array( + if (Utils::$context['is_new']) { + Utils::$context['holiday'] = [ 'id' => 0, 'day' => date('d'), 'month' => date('m'), 'year' => '0000', - 'title' => '' - ); + 'title' => '', + ]; } // If it's not new load the data. - else - { - $request = Db::$db->query('', ' + else { + $request = Db::$db->query( + '', + ' SELECT id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title FROM {db_prefix}calendar_holidays WHERE id_holiday = {int:selected_holiday} LIMIT 1', - array( + [ 'selected_holiday' => $_REQUEST['holiday'], - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { - Utils::$context['holiday'] = array( + + while ($row = Db::$db->fetch_assoc($request)) { + Utils::$context['holiday'] = [ 'id' => $row['id_holiday'], 'day' => $row['day'], 'month' => $row['month'], 'year' => $row['year'] <= 4 ? 0 : $row['year'], - 'title' => $row['title'] - ); + 'title' => $row['title'], + ]; } Db::$db->free_result($request); } @@ -356,16 +354,15 @@ public function settings(): void Utils::$context['settings_title'] = Lang::$txt['calendar_settings']; // Saving the settings? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); IntegrationHook::call('integrate_save_calendar_settings'); ACP::saveDBSettings($config_vars); // Update the stats in case. - Config::updateModSettings(array( + Config::updateModSettings([ 'calendar_updated' => time(), - )); + ]); $_SESSION['adm-save'] = true; Utils::redirectexit('action=admin;area=managecalendar;sa=settings'); @@ -389,8 +386,9 @@ public function settings(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -410,77 +408,76 @@ public static function call(): void */ public static function getConfigVars(): array { - if (!empty(Config::$modSettings['cal_enabled'])) - { + if (!empty(Config::$modSettings['cal_enabled'])) { // Load the boards list. - $boards = array(''); + $boards = ['']; - $request = Db::$db->query('order_by_board_order', ' + $request = Db::$db->query( + 'order_by_board_order', + ' SELECT b.id_board, b.name AS board_name, c.name AS cat_name FROM {db_prefix}boards AS b LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)', - array( - ) + [ + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $boards[$row['id_board']] = $row['cat_name'] . ' - ' . $row['board_name']; } Db::$db->free_result($request); Board::sort($boards); - $config_vars = array( - array('check', 'cal_enabled'), + $config_vars = [ + ['check', 'cal_enabled'], '', // All the permissions: - array('permissions', 'calendar_view'), - array('permissions', 'calendar_post'), - array('permissions', 'calendar_edit_own'), - array('permissions', 'calendar_edit_any'), + ['permissions', 'calendar_view'], + ['permissions', 'calendar_post'], + ['permissions', 'calendar_edit_own'], + ['permissions', 'calendar_edit_any'], '', // How many days to show on board index, and where to display events etc? - array('int', 'cal_days_for_index', 'help' => 'cal_maxdays_advance', 6, 'postinput' => Lang::$txt['days_word']), - array('select', 'cal_showholidays', array(0 => Lang::$txt['setting_cal_show_never'], 1 => Lang::$txt['setting_cal_show_cal'], 3 => Lang::$txt['setting_cal_show_index'], 2 => Lang::$txt['setting_cal_show_all'])), - array('select', 'cal_showbdays', array(0 => Lang::$txt['setting_cal_show_never'], 1 => Lang::$txt['setting_cal_show_cal'], 3 => Lang::$txt['setting_cal_show_index'], 2 => Lang::$txt['setting_cal_show_all'])), - array('select', 'cal_showevents', array(0 => Lang::$txt['setting_cal_show_never'], 1 => Lang::$txt['setting_cal_show_cal'], 3 => Lang::$txt['setting_cal_show_index'], 2 => Lang::$txt['setting_cal_show_all'])), - array('check', 'cal_export'), + ['int', 'cal_days_for_index', 'help' => 'cal_maxdays_advance', 6, 'postinput' => Lang::$txt['days_word']], + ['select', 'cal_showholidays', [0 => Lang::$txt['setting_cal_show_never'], 1 => Lang::$txt['setting_cal_show_cal'], 3 => Lang::$txt['setting_cal_show_index'], 2 => Lang::$txt['setting_cal_show_all']]], + ['select', 'cal_showbdays', [0 => Lang::$txt['setting_cal_show_never'], 1 => Lang::$txt['setting_cal_show_cal'], 3 => Lang::$txt['setting_cal_show_index'], 2 => Lang::$txt['setting_cal_show_all']]], + ['select', 'cal_showevents', [0 => Lang::$txt['setting_cal_show_never'], 1 => Lang::$txt['setting_cal_show_cal'], 3 => Lang::$txt['setting_cal_show_index'], 2 => Lang::$txt['setting_cal_show_all']]], + ['check', 'cal_export'], '', // Linking events etc... - array('select', 'cal_defaultboard', $boards), - array('check', 'cal_daysaslink', 'help' => 'cal_link_postevent'), - array('check', 'cal_allow_unlinked', 'help' => 'cal_allow_unlinkedevents'), - array('check', 'cal_showInTopic'), + ['select', 'cal_defaultboard', $boards], + ['check', 'cal_daysaslink', 'help' => 'cal_link_postevent'], + ['check', 'cal_allow_unlinked', 'help' => 'cal_allow_unlinkedevents'], + ['check', 'cal_showInTopic'], '', // Dates of calendar... - array('int', 'cal_minyear', 'help' => 'cal_min_year'), - array('int', 'cal_maxyear', 'help' => 'cal_max_year'), + ['int', 'cal_minyear', 'help' => 'cal_min_year'], + ['int', 'cal_maxyear', 'help' => 'cal_max_year'], '', // Calendar spanning... - array('int', 'cal_maxspan', 6, 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_for_no_limit'], 'help' => 'cal_maxevent_span'), + ['int', 'cal_maxspan', 6, 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_for_no_limit'], 'help' => 'cal_maxevent_span'], '', // Miscellaneous layout settings... - array('check', 'cal_disable_prev_next'), - array('select', 'cal_week_links', array(0 => Lang::$txt['setting_cal_week_links_none'], 1 => Lang::$txt['setting_cal_week_links_mini'], 2 => Lang::$txt['setting_cal_week_links_main'], 3 => Lang::$txt['setting_cal_week_links_both'])), - array('check', 'cal_prev_next_links'), - array('check', 'cal_short_days'), - array('check', 'cal_short_months'), - ); - } - else - { - $config_vars = array( - array('check', 'cal_enabled'), - ); + ['check', 'cal_disable_prev_next'], + ['select', 'cal_week_links', [0 => Lang::$txt['setting_cal_week_links_none'], 1 => Lang::$txt['setting_cal_week_links_mini'], 2 => Lang::$txt['setting_cal_week_links_main'], 3 => Lang::$txt['setting_cal_week_links_both']]], + ['check', 'cal_prev_next_links'], + ['check', 'cal_short_days'], + ['check', 'cal_short_months'], + ]; + } else { + $config_vars = [ + ['check', 'cal_enabled'], + ]; } - IntegrationHook::call('integrate_modify_calendar_settings', array(&$config_vars)); + IntegrationHook::call('integrate_modify_calendar_settings', [&$config_vars]); return $config_vars; } @@ -507,11 +504,11 @@ public static function editHoliday(): void /** * Backward compatibility wrapper for the settings sub-action. - * - * @param bool $return_config Whether to return the $config_vars array (used for admin search) - * @return void|array Returns nothing or returns $config_vars if $return_config is true - */ - public function modifyCalendarSettings($return_config = false) + * + * @param bool $return_config Whether to return the $config_vars array (used for admin search) + * @return void|array Returns nothing or returns $config_vars if $return_config is true + */ + public function modifyCalendarSettings($return_config = false) { self::load(); self::$obj->subaction = ''; @@ -530,40 +527,40 @@ protected function __construct() // Everything's gonna need this. Lang::load('ManageCalendar'); - if (empty(Config::$modSettings['cal_enabled'])) - { + if (empty(Config::$modSettings['cal_enabled'])) { unset(self::$subactions['holidays'], self::$subactions['editholiday']); $this->subaction = 'settings'; } // Set up the two tabs here... - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['manage_calendar'], 'help' => 'calendar', 'description' => Lang::$txt['calendar_settings_desc'], - ); + ]; - if (!empty(Config::$modSettings['cal_enabled'])) - { - Menu::$loaded['admin']->tab_data['tabs'] = array( - 'holidays' => array( + if (!empty(Config::$modSettings['cal_enabled'])) { + Menu::$loaded['admin']->tab_data['tabs'] = [ + 'holidays' => [ 'description' => Lang::$txt['manage_holidays_desc'], - ), - 'settings' => array( + ], + 'settings' => [ 'description' => Lang::$txt['calendar_settings_desc'], - ), - ); + ], + ]; } - IntegrationHook::call('integrate_manage_calendar', array(&self::$subactions)); + IntegrationHook::call('integrate_manage_calendar', [&self::$subactions]); - if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) + if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) { $this->subaction = $_REQUEST['sa']; + } } } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Calendar::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Calendar::exportStatic')) { Calendar::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/EndSession.php b/Sources/Actions/Admin/EndSession.php index 55c88b5c03..168f4476c6 100644 --- a/Sources/Actions/Admin/EndSession.php +++ b/Sources/Actions/Admin/EndSession.php @@ -13,9 +13,8 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\BackwardCompatibility; use SMF\Utils; /** @@ -30,11 +29,11 @@ class EndSession implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'AdminEndSession', - ), - ); + ], + ]; /**************************** * Internal static properties @@ -61,10 +60,10 @@ public function execute(): void unset($_SESSION['admin_time']); // Clean any admin tokens as well. - foreach ($_SESSION['token'] as $key => $token) - { - if (strpos($key, '-admin') !== false) + foreach ($_SESSION['token'] as $key => $token) { + if (strpos($key, '-admin') !== false) { unset($_SESSION['token'][$key]); + } } Utils::redirectexit(); @@ -81,8 +80,9 @@ public function execute(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -108,7 +108,8 @@ protected function __construct() } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\EndSession::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\EndSession::exportStatic')) { EndSession::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/ErrorLog.php b/Sources/Actions/Admin/ErrorLog.php index 28bfd7c07c..b5f247f526 100644 --- a/Sources/Actions/Admin/ErrorLog.php +++ b/Sources/Actions/Admin/ErrorLog.php @@ -13,13 +13,13 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\BackwardCompatibility; use SMF\BBCodeParser; use SMF\Config; -use SMF\IP; +use SMF\Db\DatabaseApi as Db; use SMF\ErrorHandler; +use SMF\IP; use SMF\Lang; use SMF\PageIndex; use SMF\SecurityToken; @@ -27,7 +27,6 @@ use SMF\Time; use SMF\User; use SMF\Utils; -use SMF\Db\DatabaseApi as Db; /** * Shows a list of all errors that were logged on the forum, @@ -42,11 +41,11 @@ class ErrorLog implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'ViewErrorLog', - ), - ); + ], + ]; /******************* * Public properties @@ -64,48 +63,48 @@ class ErrorLog implements ActionInterface * * Basic info about the available filters. */ - public array $filters = array( - 'id_member' => array( + public array $filters = [ + 'id_member' => [ 'txt' => 'username', 'operator' => '=', 'datatype' => 'int', - ), - 'ip' => array( + ], + 'ip' => [ 'txt' => 'ip_address', 'operator' => '=', 'datatype' => 'inet', - ), - 'session' => array( + ], + 'session' => [ 'txt' => 'session', 'operator' => 'LIKE', 'datatype' => 'string', - ), - 'url' => array( + ], + 'url' => [ 'txt' => 'error_url', 'operator' => 'LIKE', 'datatype' => 'string', - ), - 'message' => array( + ], + 'message' => [ 'txt' => 'error_message', 'operator' => 'LIKE', 'datatype' => 'string', - ), - 'error_type' => array( + ], + 'error_type' => [ 'txt' => 'error_type', 'operator' => 'LIKE', 'datatype' => 'string', - ), - 'file' => array( + ], + 'file' => [ 'txt' => 'file', 'operator' => 'LIKE', 'datatype' => 'string', - ), - 'line' => array( + ], + 'line' => [ 'txt' => 'line', 'operator' => '=', 'datatype' => 'int', - ), - ); + ], + ]; /**************************** * Internal static properties @@ -132,18 +131,15 @@ public function execute(): void User::$me->isAllowedTo('admin_forum'); // Viewing contents of a file? - if (isset($_GET['file'])) - { + if (isset($_GET['file'])) { $this->viewFile(); } // Viewing contents of a backtrace? - elseif (isset($_GET['backtrace'])) - { + elseif (isset($_GET['backtrace'])) { $this->viewBacktrace(); } // Viewing the log. - else - { + else { $this->view(); } } @@ -158,43 +154,45 @@ public function execute(): void public function view(): void { // Set up the filtering... - if (isset($_GET['value'], $_GET['filter']) && isset($this->filters[$_GET['filter']])) - { - $this->filter = array( + if (isset($_GET['value'], $_GET['filter'], $this->filters[$_GET['filter']])) { + $this->filter = [ 'variable' => $_GET['filter'], - 'value' => array( - 'sql' => in_array($_GET['filter'], array('message', 'url', 'file')) ? base64_decode(strtr($_GET['value'], array(' ' => '+'))) : Db::$db->escape_wildcard_string($_GET['value']), - ), + 'value' => [ + 'sql' => in_array($_GET['filter'], ['message', 'url', 'file']) ? base64_decode(strtr($_GET['value'], [' ' => '+'])) : Db::$db->escape_wildcard_string($_GET['value']), + ], 'href' => ';filter=' . $_GET['filter'] . ';value=' . $_GET['value'], - 'entity' => $this->filters[$_GET['filter']]['txt'] - ); + 'entity' => $this->filters[$_GET['filter']]['txt'], + ]; } // Deleting, are we? - if (isset($_POST['delall']) || isset($_POST['delete'])) + if (isset($_POST['delall']) || isset($_POST['delete'])) { $this->deleteErrors(); + } // Just how many errors are there? - $result = Db::$db->query('', ' + $result = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}log_errors' . (isset($this->filter) ? ' WHERE ' . $this->filter['variable'] . ' ' . $this->filters[$_GET['filter']]['operator'] . ' {' . $this->filters[$_GET['filter']]['datatype'] . ':filter}' : ''), - array( + [ 'filter' => isset($this->filter) ? $this->filter['value']['sql'] : '', - ) + ], ); list($num_errors) = Db::$db->fetch_row($result); Db::$db->free_result($result); // If this filter is empty... - if ($num_errors == 0 && isset($this->filter)) - { + if ($num_errors == 0 && isset($this->filter)) { Utils::redirectexit('action=admin;area=logs;sa=errorlog' . (isset($_REQUEST['desc']) ? ';desc' : '')); } // Clean up start. - if (!isset($_GET['start']) || $_GET['start'] < 0) + if (!isset($_GET['start']) || $_GET['start'] < 0) { $_GET['start'] = 0; + } // Do we want to reverse error listing? Utils::$context['sort_direction'] = isset($_REQUEST['desc']) ? 'down' : 'up'; @@ -205,84 +203,85 @@ public function view(): void Utils::$context['start'] = $_GET['start']; // Update the error count - if (!isset($this->filter)) - { + if (!isset($this->filter)) { Utils::$context['num_errors'] = $num_errors; - } - else - { + } else { // We want all errors, not just the number of filtered messages... - $query = Db::$db->query('', ' + $query = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}log_errors', - array() + [], ); list(Utils::$context['num_errors']) = Db::$db->fetch_row($query); Db::$db->free_result($query); } // Find and sort out the errors. - Utils::$context['errors'] = array(); - $members = array(); + Utils::$context['errors'] = []; + $members = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_error, id_member, ip, url, log_time, message, session, error_type, file, line FROM {db_prefix}log_errors' . (isset($this->filter) ? ' WHERE ' . $this->filter['variable'] . ' ' . $this->filters[$_GET['filter']]['operator'] . ' {' . $this->filters[$_GET['filter']]['datatype'] . ':filter}' : '') . ' ORDER BY id_error ' . (Utils::$context['sort_direction'] == 'down' ? 'DESC' : '') . ' LIMIT {int:start}, {int:max}', - array( + [ 'filter' => isset($this->filter) ? $this->filter['value']['sql'] : '', 'start' => $_GET['start'], 'max' => Config::$modSettings['defaultMaxListItems'], - ) + ], ); - for ($i = 0; $row = Db::$db->fetch_assoc($request); $i++) - { + + for ($i = 0; $row = Db::$db->fetch_assoc($request); $i++) { $search_message = preg_replace('~<span class="remove">(.+?)</span>~', '%', Db::$db->escape_wildcard_string($row['message'])); - if (isset($this->filter) && $search_message == $this->filter['value']['sql']) + if (isset($this->filter) && $search_message == $this->filter['value']['sql']) { $search_message = Db::$db->escape_wildcard_string($row['message']); + } - $show_message = strtr(strtr(preg_replace('~<span class="remove">(.+?)</span>~', '$1', $row['message']), array("\r" => '', '
' => "\n", '<' => '<', '>' => '>', '"' => '"')), array("\n" => '
')); + $show_message = strtr(strtr(preg_replace('~<span class="remove">(.+?)</span>~', '$1', $row['message']), ["\r" => '', '
' => "\n", '<' => '<', '>' => '>', '"' => '"']), ["\n" => '
']); - Utils::$context['errors'][$row['id_error']] = array( - 'member' => array( + Utils::$context['errors'][$row['id_error']] = [ + 'member' => [ 'id' => $row['id_member'], 'ip' => isset($row['ip']) ? new IP($row['ip']) : null, - 'session' => $row['session'] - ), + 'session' => $row['session'], + ], 'time' => Time::create('@' . $row['log_time'])->format(), 'timestamp' => $row['log_time'], - 'url' => array( + 'url' => [ 'html' => Utils::htmlspecialchars(strpos($row['url'], 'cron.php') === false ? (substr($row['url'], 0, 1) == '?' ? Config::$scripturl : '') . $row['url'] : $row['url']), - 'href' => base64_encode(Db::$db->escape_wildcard_string($row['url'])) - ), - 'message' => array( + 'href' => base64_encode(Db::$db->escape_wildcard_string($row['url'])), + ], + 'message' => [ 'html' => $show_message, - 'href' => base64_encode($search_message) - ), + 'href' => base64_encode($search_message), + ], 'id' => $row['id_error'], - 'error_type' => array( + 'error_type' => [ 'type' => $row['error_type'], - 'name' => isset(Lang::$txt['errortype_' . $row['error_type']]) ? Lang::$txt['errortype_' . $row['error_type']] : $row['error_type'], - ), - 'file' => array(), - ); + 'name' => Lang::$txt['errortype_' . $row['error_type']] ?? $row['error_type'], + ], + 'file' => [], + ]; - if (!empty($row['file']) && !empty($row['line'])) - { + if (!empty($row['file']) && !empty($row['line'])) { // Eval'd files rarely point to the right location and cause // havoc for linking, so don't link them. $linkfile = strpos($row['file'], 'eval') !== false && strpos($row['file'], '?') !== false; - Utils::$context['errors'][$row['id_error']]['file'] = array( + Utils::$context['errors'][$row['id_error']]['file'] = [ 'file' => $row['file'], 'line' => $row['line'], 'href' => Config::$scripturl . '?action=admin;area=logs;sa=errorlog;file=' . base64_encode($row['file']) . ';line=' . $row['line'], 'link' => $linkfile ? '' . $row['file'] . '' : $row['file'], 'search' => base64_encode($row['file']), - ); + ]; } // Make a list of members to load later. @@ -291,35 +290,35 @@ public function view(): void Db::$db->free_result($request); // Load the member data. - if (!empty($members)) - { + if (!empty($members)) { // Get some additional member info... - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_member, member_name, real_name FROM {db_prefix}members WHERE id_member IN ({array_int:member_list}) LIMIT {int:members}', - array( + [ 'member_list' => $members, 'members' => count($members), - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $members[$row['id_member']] = $row; } Db::$db->free_result($request); // This is a guest... - $members[0] = array( + $members[0] = [ 'id_member' => 0, 'member_name' => '', - 'real_name' => Lang::$txt['guest_title'] - ); + 'real_name' => Lang::$txt['guest_title'], + ]; // Go through each error and tack the data on. - foreach (Utils::$context['errors'] as $id => &$error) - { + foreach (Utils::$context['errors'] as $id => &$error) { $memID = $error['member']['id']; $error['member']['username'] = $members[$memID]['member_name']; @@ -330,73 +329,65 @@ public function view(): void } // Filtering anything? - if (isset($this->filter)) - { + if (isset($this->filter)) { Utils::$context['filter'] = &$this->filter; // Set the filtering context. - if ($this->filter['variable'] == 'id_member') - { + if ($this->filter['variable'] == 'id_member') { $id = $this->filter['value']['sql']; User::load($id, self::LOAD_BY_ID, 'minimal'); Utils::$context['filter']['value']['html'] = '' . (isset(User::$loaded[$id]) ? User::$loaded[$id]->name : Lang::$txt['guest']) . ''; - } - elseif ($this->filter['variable'] == 'url') - { - Utils::$context['filter']['value']['html'] = '\'' . strtr(Utils::htmlspecialchars((substr($this->filter['value']['sql'], 0, 1) == '?' ? Config::$scripturl : '') . $this->filter['value']['sql']), array('\_' => '_')) . '\''; - } - elseif ($this->filter['variable'] == 'message') - { - Utils::$context['filter']['value']['html'] = '\'' . strtr(Utils::htmlspecialchars($this->filter['value']['sql']), array("\n" => '
', '<br />' => '
', "\t" => '   ', '\_' => '_', '\\%' => '%', '\\\\' => '\\')) . '\''; + } elseif ($this->filter['variable'] == 'url') { + Utils::$context['filter']['value']['html'] = '\'' . strtr(Utils::htmlspecialchars((substr($this->filter['value']['sql'], 0, 1) == '?' ? Config::$scripturl : '') . $this->filter['value']['sql']), ['\\_' => '_']) . '\''; + } elseif ($this->filter['variable'] == 'message') { + Utils::$context['filter']['value']['html'] = '\'' . strtr(Utils::htmlspecialchars($this->filter['value']['sql']), ["\n" => '
', '<br />' => '
', "\t" => '   ', '\\_' => '_', '\\%' => '%', '\\\\' => '\\']) . '\''; Utils::$context['filter']['value']['html'] = preg_replace('~&lt;span class=&quot;remove&quot;&gt;(.+?)&lt;/span&gt;~', '$1', Utils::$context['filter']['value']['html']); - } - elseif ($this->filter['variable'] == 'error_type') - { - Utils::$context['filter']['value']['html'] = '\'' . strtr(Utils::htmlspecialchars($this->filter['value']['sql']), array("\n" => '
', '<br />' => '
', "\t" => '   ', '\_' => '_', '\\%' => '%', '\\\\' => '\\')) . '\''; - } - else - { + } elseif ($this->filter['variable'] == 'error_type') { + Utils::$context['filter']['value']['html'] = '\'' . strtr(Utils::htmlspecialchars($this->filter['value']['sql']), ["\n" => '
', '<br />' => '
', "\t" => '   ', '\\_' => '_', '\\%' => '%', '\\\\' => '\\']) . '\''; + } else { Utils::$context['filter']['value']['html'] = &$this->filter['value']['sql']; } } - Utils::$context['error_types'] = array(); + Utils::$context['error_types'] = []; - Utils::$context['error_types']['all'] = array( + Utils::$context['error_types']['all'] = [ 'label' => Lang::$txt['errortype_all'], 'error_type' => 'all', - 'description' => isset(Lang::$txt['errortype_all_desc']) ? Lang::$txt['errortype_all_desc'] : '', + 'description' => Lang::$txt['errortype_all_desc'] ?? '', 'url' => Config::$scripturl . '?action=admin;area=logs;sa=errorlog' . (Utils::$context['sort_direction'] == 'down' ? ';desc' : ''), 'is_selected' => empty($this->filter), - ); + ]; // What type of errors do we have and how many do we have? $sum = 0; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT error_type, COUNT(*) AS num_errors FROM {db_prefix}log_errors GROUP BY error_type ORDER BY error_type = {string:critical_type} DESC, error_type ASC', - array( + [ 'critical_type' => 'critical', - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { // Total errors so far? $sum += $row['num_errors']; - Utils::$context['error_types'][$sum] = array( - 'label' => (isset(Lang::$txt['errortype_' . $row['error_type']]) ? Lang::$txt['errortype_' . $row['error_type']] : $row['error_type']) . ' (' . $row['num_errors'] . ')', + Utils::$context['error_types'][$sum] = [ + 'label' => (Lang::$txt['errortype_' . $row['error_type']] ?? $row['error_type']) . ' (' . $row['num_errors'] . ')', 'error_type' => $row['error_type'], - 'description' => isset(Lang::$txt['errortype_' . $row['error_type'] . '_desc']) ? Lang::$txt['errortype_' . $row['error_type'] . '_desc'] : '', + 'description' => Lang::$txt['errortype_' . $row['error_type'] . '_desc'] ?? '', 'url' => Config::$scripturl . '?action=admin;area=logs;sa=errorlog' . (Utils::$context['sort_direction'] == 'down' ? ';desc' : '') . ';filter=error_type;value=' . $row['error_type'], 'is_selected' => isset($this->filter) && $this->filter['value']['sql'] == Db::$db->escape_wildcard_string($row['error_type']), - ); + ]; } Db::$db->free_result($request); @@ -404,12 +395,9 @@ public function view(): void Utils::$context['error_types']['all']['label'] .= ' (' . $sum . ')'; // Finally, work out what is the last tab! - if (isset(Utils::$context['error_types'][$sum])) - { + if (isset(Utils::$context['error_types'][$sum])) { Utils::$context['error_types'][$sum]['is_last'] = true; - } - else - { + } else { Utils::$context['error_types']['all']['is_last'] = true; } @@ -454,9 +442,8 @@ public function viewFile(): void || $basename == strtolower(basename(SMF_SETTINGS_BACKUP_FILE)) || strpos($file, $real_cache) !== false || !is_readable($file) - ) - { - ErrorHandler::fatalLang('error_bad_file', true, array(Utils::htmlspecialchars($file))); + ) { + ErrorHandler::fatalLang('error_bad_file', true, [Utils::htmlspecialchars($file)]); } // Get the min and max lines. @@ -464,8 +451,9 @@ public function viewFile(): void $min = max($line - 20, 1); $max = $line + 21; - if ($max <= 0 || $min >= $max) + if ($max <= 0 || $min >= $max) { ErrorHandler::fatalLang('error_bad_line'); + } $file_data = explode('
', BBCodeParser::highlightPhpCode(Utils::htmlspecialchars(file_get_contents($file)))); @@ -474,15 +462,15 @@ public function viewFile(): void $file_data = array_slice($file_data, $min - 1, $max - $min); - Utils::$context['file_data'] = array( + Utils::$context['file_data'] = [ 'contents' => $file_data, 'min' => $min, 'target' => $line, - 'file' => strtr($file, array('"' => '\\"')), - ); + 'file' => strtr($file, ['"' => '\\"']), + ]; Theme::loadTemplate('Errors'); - Utils::$context['template_layers'] = array(); + Utils::$context['template_layers'] = []; Utils::$context['sub_template'] = 'show_file'; } @@ -496,26 +484,28 @@ public function viewBacktrace(): void { $id_error = (int) $_REQUEST['backtrace']; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT backtrace, error_type, message, file, line, url FROM {db_prefix}log_errors WHERE id_error = {int:id_error}', - array( + [ 'id_error' => $id_error, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { Utils::$context['error_info'] = $row; Utils::$context['error_info']['url'] = Config::$scripturl . $row['url']; Utils::$context['error_info']['backtrace'] = Utils::jsonDecode($row['backtrace']); } Db::$db->free_result($request); - Theme::loadCSSFile('admin.css', array(), 'smf_admin'); + Theme::loadCSSFile('admin.css', [], 'smf_admin'); Theme::loadTemplate('Errors'); Lang::load('ManageMaintenance'); - Utils::$context['template_layers'] = array(); + Utils::$context['template_layers'] = []; Utils::$context['sub_template'] = 'show_backtrace'; } @@ -530,8 +520,9 @@ public function viewBacktrace(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -557,8 +548,9 @@ protected function __construct() Lang::load('ManageMaintenance'); Theme::loadTemplate('Errors'); - foreach ($this->filters as &$filter) + foreach ($this->filters as &$filter) { $filter['txt'] = Lang::$txt[$filter['txt']]; + } } /** @@ -575,38 +567,41 @@ protected function deleteErrors() SecurityToken::validate('admin-el'); // Delete all or just some? - if (isset($_POST['delall']) && !isset($this->filter)) - { - Db::$db->query('truncate_table', ' + if (isset($_POST['delall']) && !isset($this->filter)) { + Db::$db->query( + 'truncate_table', + ' TRUNCATE {db_prefix}log_errors', - array( - ) + [ + ], ); } // Deleting all with a filter? - elseif (isset($_POST['delall']) && isset($this->filter)) - { + elseif (isset($_POST['delall'], $this->filter)) { // IP addresses need a different placeholder type. $filter_type = $this->filter['variable'] == 'ip' ? 'inet' : 'string'; $filter_op = $this->filter['variable'] == 'ip' ? '=' : 'LIKE'; - Db::$db->query('', ' + Db::$db->query( + '', + ' DELETE FROM {db_prefix}log_errors WHERE ' . $this->filter['variable'] . ' ' . $filter_op . ' {' . $filter_type . ':filter}', - array( + [ 'filter' => $this->filter['value']['sql'], - ) + ], ); } // Just specific errors? - elseif (!empty($_POST['delete'])) - { - Db::$db->query('', ' + elseif (!empty($_POST['delete'])) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}log_errors WHERE id_error IN ({array_int:error_list})', - array( + [ 'error_list' => array_unique($_POST['delete']), - ) + ], ); // Go back to where we were. @@ -619,7 +614,8 @@ protected function deleteErrors() } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\ErrorLog::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\ErrorLog::exportStatic')) { ErrorLog::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Features.php b/Sources/Actions/Admin/Features.php index 8b0938e95f..45445fa6c4 100644 --- a/Sources/Actions/Admin/Features.php +++ b/Sources/Actions/Admin/Features.php @@ -13,12 +13,14 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\Actions\Profile\Notification; +use SMF\BackwardCompatibility; use SMF\BBCodeParser; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\ErrorHandler; +use SMF\Graphics\Image; use SMF\IntegrationHook; use SMF\ItemList; use SMF\Lang; @@ -29,9 +31,6 @@ use SMF\TimeZone; use SMF\User; use SMF\Utils; -use SMF\Actions\Profile\Notification; -use SMF\Db\DatabaseApi as Db; -use SMF\Graphics\Image; /** * Class to manage various core features. @@ -45,8 +44,8 @@ class Features implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'ModifyFeatureSettings', 'list_getProfileFields' => 'list_getProfileFields', 'list_getProfileFieldSize' => 'list_getProfileFieldSize', @@ -59,8 +58,8 @@ class Features implements ActionInterface 'modifyLikesSettings' => 'ModifyLikesSettings', 'modifyMentionsSettings' => 'ModifyMentionsSettings', 'modifyAlertsSettings' => 'ModifyAlertsSettings', - ), - ); + ], + ]; /******************* * Public properties @@ -83,7 +82,7 @@ class Features implements ActionInterface * * Available sub-actions. */ - public static array $subactions = array( + public static array $subactions = [ 'basic' => 'basic', 'bbc' => 'bbc', 'layout' => 'layout', @@ -93,7 +92,7 @@ class Features implements ActionInterface 'likes' => 'likes', 'mentions' => 'mentions', 'alerts' => 'alerts', - ); + ]; /**************************** * Internal static properties @@ -122,10 +121,11 @@ public function execute(): void Utils::$context['sub_template'] = 'show_settings'; Utils::$context['sub_action'] = $this->subaction; - $call = method_exists($this, self::$subactions[$this->subaction]) ? array($this, self::$subactions[$this->subaction]) : Utils::getCallable(self::$subactions[$this->subaction]); + $call = method_exists($this, self::$subactions[$this->subaction]) ? [$this, self::$subactions[$this->subaction]] : Utils::getCallable(self::$subactions[$this->subaction]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } /** @@ -138,19 +138,18 @@ public function basic(): void $config_vars = self::basicConfigVars(); // Saving? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); // Make sure the country codes are valid. - if (!empty($_POST['timezone_priority_countries'])) - { + if (!empty($_POST['timezone_priority_countries'])) { $_POST['timezone_priority_countries'] = TimeZone::validateIsoCountryCodes($_POST['timezone_priority_countries'], true); } // Prevent absurd boundaries here - make it a day tops. - if (isset($_POST['lastActive'])) + if (isset($_POST['lastActive'])) { $_POST['lastActive'] = min((int) $_POST['lastActive'], 1440); + } IntegrationHook::call('integrate_save_basic_settings'); @@ -158,8 +157,9 @@ public function basic(): void $_SESSION['adm-save'] = true; // Do a bit of housekeeping - if (empty($_POST['minimize_files']) || $_POST['minimize_files'] != Config::$modSettings['minimize_files']) + if (empty($_POST['minimize_files']) || $_POST['minimize_files'] != Config::$modSettings['minimize_files']) { Theme::deleteAllMinified(); + } User::$me->logOnline(); Utils::redirectexit('action=admin;area=featuresettings;sa=basic'); @@ -188,82 +188,69 @@ public function bbc(): void Utils::$context['page_title'] = Lang::$txt['manageposts_bbc_settings_title']; // Make sure we check the right tags! - Config::$modSettings['bbc_disabled_disabledBBC'] = empty(Config::$modSettings['disabledBBC']) ? array() : explode(',', Config::$modSettings['disabledBBC']); + Config::$modSettings['bbc_disabled_disabledBBC'] = empty(Config::$modSettings['disabledBBC']) ? [] : explode(',', Config::$modSettings['disabledBBC']); // Legacy BBC are listed separately, but we use the same info in both cases Config::$modSettings['bbc_disabled_legacyBBC'] = Config::$modSettings['bbc_disabled_disabledBBC']; $extra = ''; - if (isset($_REQUEST['cowsay'])) - { - $config_vars[] = array('permissions', 'bbc_cowsay', 'text_label' => sprintf(Lang::$txt['groups_can_use'], '[cowsay]')); + + if (isset($_REQUEST['cowsay'])) { + $config_vars[] = ['permissions', 'bbc_cowsay', 'text_label' => sprintf(Lang::$txt['groups_can_use'], '[cowsay]')]; $extra = ';cowsay'; } // Saving? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); // Clean up the tags. - $bbcTags = array(); - $bbcTagsChildren = array(); - foreach (BBCodeParser::getCodes() as $tag) - { + $bbcTags = []; + $bbcTagsChildren = []; + + foreach (BBCodeParser::getCodes() as $tag) { $bbcTags[] = $tag['tag']; - if (isset($tag['require_children'])) - { + if (isset($tag['require_children'])) { $bbcTagsChildren[$tag['tag']] = !isset($bbcTagsChildren[$tag['tag']]) ? $tag['require_children'] : array_unique(array_merge($bbcTagsChildren[$tag['tag']], $tag['require_children'])); } } // Clean up tags with children - foreach($bbcTagsChildren as $parent_tag => $children) - { - foreach($children as $index => $child_tag) - { + foreach($bbcTagsChildren as $parent_tag => $children) { + foreach($children as $index => $child_tag) { // Remove entries where parent and child tag is the same - if ($child_tag == $parent_tag) - { + if ($child_tag == $parent_tag) { unset($bbcTagsChildren[$parent_tag][$index]); + continue; } // Combine chains of tags - if (isset($bbcTagsChildren[$child_tag])) - { + if (isset($bbcTagsChildren[$child_tag])) { $bbcTagsChildren[$parent_tag] = array_merge($bbcTagsChildren[$parent_tag], $bbcTagsChildren[$child_tag]); unset($bbcTagsChildren[$child_tag]); } } } - if (!isset($_POST['disabledBBC_enabledTags'])) - { - $_POST['disabledBBC_enabledTags'] = array(); - } - elseif (!is_array($_POST['disabledBBC_enabledTags'])) - { - $_POST['disabledBBC_enabledTags'] = array($_POST['disabledBBC_enabledTags']); + if (!isset($_POST['disabledBBC_enabledTags'])) { + $_POST['disabledBBC_enabledTags'] = []; + } elseif (!is_array($_POST['disabledBBC_enabledTags'])) { + $_POST['disabledBBC_enabledTags'] = [$_POST['disabledBBC_enabledTags']]; } - if (!isset($_POST['legacyBBC_enabledTags'])) - { - $_POST['legacyBBC_enabledTags'] = array(); - } - elseif (!is_array($_POST['legacyBBC_enabledTags'])) - { - $_POST['legacyBBC_enabledTags'] = array($_POST['legacyBBC_enabledTags']); + if (!isset($_POST['legacyBBC_enabledTags'])) { + $_POST['legacyBBC_enabledTags'] = []; + } elseif (!is_array($_POST['legacyBBC_enabledTags'])) { + $_POST['legacyBBC_enabledTags'] = [$_POST['legacyBBC_enabledTags']]; } $_POST['disabledBBC_enabledTags'] = array_unique(array_merge($_POST['disabledBBC_enabledTags'], $_POST['legacyBBC_enabledTags'])); // Enable all children if parent is enabled - foreach ($bbcTagsChildren as $tag => $children) - { - if (in_array($tag, $_POST['disabledBBC_enabledTags'])) - { + foreach ($bbcTagsChildren as $tag => $children) { + if (in_array($tag, $_POST['disabledBBC_enabledTags'])) { $_POST['disabledBBC_enabledTags'] = array_merge($_POST['disabledBBC_enabledTags'], $children); } } @@ -275,13 +262,12 @@ public function bbc(): void unset($_POST['legacyBBC_enabledTags']); $config_vars = array_filter( $config_vars, - function($config_var) - { + function ($config_var) { return !isset($config_var[1]) || $config_var[1] != 'legacyBBC'; - } + }, ); - IntegrationHook::call('integrate_save_bbc_settings', array($bbcTags)); + IntegrationHook::call('integrate_save_bbc_settings', [$bbcTags]); ACP::saveDBSettings($config_vars); $_SESSION['adm-save'] = true; @@ -304,8 +290,7 @@ public function layout(): void $config_vars = self::layoutConfigVars(); // Saving? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); IntegrationHook::call('integrate_save_layout_settings'); @@ -340,13 +325,12 @@ public function signature(): void Utils::$context['settings_post_javascript'] = 'document.getElementById(\'signature_max_smileys\').disabled = !document.getElementById(\'signature_allow_smileys\').checked;'; // Load all the signature settings. - list ($sig_limits, $sig_bbc) = explode(':', Config::$modSettings['signature_settings']); + list($sig_limits, $sig_bbc) = explode(':', Config::$modSettings['signature_settings']); $sig_limits = explode(',', $sig_limits); - $disabledTags = !empty($sig_bbc) ? explode(',', $sig_bbc) : array(); + $disabledTags = !empty($sig_bbc) ? explode(',', $sig_bbc) : []; // Applying to ALL signatures?!! - if (isset($_GET['apply'])) - { + if (isset($_GET['apply'])) { // Security! User::$me->checkSession('get'); @@ -355,101 +339,93 @@ public function signature(): void $_GET['step'] = isset($_GET['step']) ? (int) $_GET['step'] : 0; $done = false; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT MAX(id_member) FROM {db_prefix}members', - array( - ) + [ + ], ); - list (Utils::$context['max_member']) = Db::$db->fetch_row($request); + list(Utils::$context['max_member']) = Db::$db->fetch_row($request); Db::$db->free_result($request); - while (!$done) - { - $changes = array(); + while (!$done) { + $changes = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_member, signature FROM {db_prefix}members WHERE id_member BETWEEN {int:step} AND {int:step} + 49 AND id_group != {int:admin_group} AND FIND_IN_SET({int:admin_group}, additional_groups) = 0', - array( + [ 'admin_group' => 1, 'step' => $_GET['step'], - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { // Apply all the rules we can realistically do. - $sig = strtr($row['signature'], array('
' => "\n")); + $sig = strtr($row['signature'], ['
' => "\n"]); // Max characters... - if (!empty($sig_limits[1])) + if (!empty($sig_limits[1])) { $sig = Utils::entitySubstr($sig, 0, $sig_limits[1]); + } + // Max lines... - if (!empty($sig_limits[2])) - { + if (!empty($sig_limits[2])) { $count = 0; - for ($i = 0; $i < strlen($sig); $i++) - { - if ($sig[$i] == "\n") - { + + for ($i = 0; $i < strlen($sig); $i++) { + if ($sig[$i] == "\n") { $count++; - if ($count >= $sig_limits[2]) - $sig = substr($sig, 0, $i) . strtr(substr($sig, $i), array("\n" => ' ')); + + if ($count >= $sig_limits[2]) { + $sig = substr($sig, 0, $i) . strtr(substr($sig, $i), ["\n" => ' ']); + } } } } - if (!empty($sig_limits[7]) && preg_match_all('~\[size=([\d\.]+)?(px|pt|em|x-large|larger)~i', $sig, $matches) !== false && isset($matches[2])) - { - foreach ($matches[1] as $ind => $size) - { + if (!empty($sig_limits[7]) && preg_match_all('~\\[size=([\\d\\.]+)?(px|pt|em|x-large|larger)~i', $sig, $matches) !== false && isset($matches[2])) { + foreach ($matches[1] as $ind => $size) { $limit_broke = 0; // Attempt to allow all sizes of abuse, so to speak. - if ($matches[2][$ind] == 'px' && $size > $sig_limits[7]) - { + if ($matches[2][$ind] == 'px' && $size > $sig_limits[7]) { $limit_broke = $sig_limits[7] . 'px'; - } - elseif ($matches[2][$ind] == 'pt' && $size > ($sig_limits[7] * 0.75)) - { + } elseif ($matches[2][$ind] == 'pt' && $size > ($sig_limits[7] * 0.75)) { $limit_broke = ((int) $sig_limits[7] * 0.75) . 'pt'; - } - elseif ($matches[2][$ind] == 'em' && $size > ((float) $sig_limits[7] / 16)) - { + } elseif ($matches[2][$ind] == 'em' && $size > ((float) $sig_limits[7] / 16)) { $limit_broke = ((float) $sig_limits[7] / 16) . 'em'; - } - elseif ($matches[2][$ind] != 'px' && $matches[2][$ind] != 'pt' && $matches[2][$ind] != 'em' && $sig_limits[7] < 18) - { + } elseif ($matches[2][$ind] != 'px' && $matches[2][$ind] != 'pt' && $matches[2][$ind] != 'em' && $sig_limits[7] < 18) { $limit_broke = 'large'; } - if ($limit_broke) - { + if ($limit_broke) { $sig = str_replace($matches[0][$ind], '[size=' . $sig_limits[7] . 'px', $sig); } } } // Stupid images - this is stupidly, stupidly challenging. - if ((!empty($sig_limits[3]) || !empty($sig_limits[5]) || !empty($sig_limits[6]))) - { - $replaces = array(); + if ((!empty($sig_limits[3]) || !empty($sig_limits[5]) || !empty($sig_limits[6]))) { + $replaces = []; $img_count = 0; // Get all BBC tags... - preg_match_all('~\[img(\s+width=([\d]+))?(\s+height=([\d]+))?(\s+width=([\d]+))?\s*\](?:
)*([^<">]+?)(?:
)*\[/img\]~i', $sig, $matches); + preg_match_all('~\\[img(\\s+width=([\\d]+))?(\\s+height=([\\d]+))?(\\s+width=([\\d]+))?\\s*\\](?:
)*([^<">]+?)(?:
)*\\[/img\\]~i', $sig, $matches); // ... and all HTML ones. - preg_match_all('~<img\s+src=(?:")?((?:http://|ftp://|https://|ftps://).+?)(?:")?(?:\s+alt=(?:")?(.*?)(?:")?)?(?:\s?/)?>~i', $sig, $matches2, PREG_PATTERN_ORDER); + preg_match_all('~<img\\s+src=(?:")?((?:http://|ftp://|https://|ftps://).+?)(?:")?(?:\\s+alt=(?:")?(.*?)(?:")?)?(?:\\s?/)?>~i', $sig, $matches2, PREG_PATTERN_ORDER); // And stick the HTML in the BBC. - if (!empty($matches2)) - { - foreach ($matches2[0] as $ind => $dummy) - { + if (!empty($matches2)) { + foreach ($matches2[0] as $ind => $dummy) { $matches[0][] = $matches2[0][$ind]; $matches[1][] = ''; $matches[2][] = ''; @@ -462,32 +438,26 @@ public function signature(): void } // Try to find all the images! - if (!empty($matches)) - { - $image_count_holder = array(); + if (!empty($matches)) { + $image_count_holder = []; - foreach ($matches[0] as $key => $image) - { + foreach ($matches[0] as $key => $image) { $width = -1; $height = -1; $img_count++; // Too many images? - if (!empty($sig_limits[3]) && $img_count > $sig_limits[3]) - { + if (!empty($sig_limits[3]) && $img_count > $sig_limits[3]) { // If we've already had this before we only want to remove the excess. - if (isset($image_count_holder[$image])) - { + if (isset($image_count_holder[$image])) { $img_offset = -1; $rep_img_count = 0; - while ($img_offset !== false) - { + while ($img_offset !== false) { $img_offset = strpos($sig, $image, $img_offset + 1); $rep_img_count++; - if ($rep_img_count > $image_count_holder[$image]) - { + if ($rep_img_count > $image_count_holder[$image]) { // Only replace the excess. $sig = substr($sig, 0, $img_offset) . str_replace($image, '', substr($sig, $img_offset)); @@ -495,9 +465,7 @@ public function signature(): void $img_offset = false; } } - } - else - { + } else { $replaces[$image] = ''; } @@ -505,66 +473,56 @@ public function signature(): void } // Does it have predefined restraints? Width first. - if ($matches[6][$key]) + if ($matches[6][$key]) { $matches[2][$key] = $matches[6][$key]; + } - if ($matches[2][$key] && $sig_limits[5] && $matches[2][$key] > $sig_limits[5]) - { + if ($matches[2][$key] && $sig_limits[5] && $matches[2][$key] > $sig_limits[5]) { $width = $sig_limits[5]; $matches[4][$key] = $matches[4][$key] * ($width / $matches[2][$key]); - } - elseif ($matches[2][$key]) - { + } elseif ($matches[2][$key]) { $width = $matches[2][$key]; } // ... and height. - if ($matches[4][$key] && $sig_limits[6] && $matches[4][$key] > $sig_limits[6]) - { + if ($matches[4][$key] && $sig_limits[6] && $matches[4][$key] > $sig_limits[6]) { $height = $sig_limits[6]; - if ($width != -1) + if ($width != -1) { $width = $width * ($height / $matches[4][$key]); - } - elseif ($matches[4][$key]) - { + } + } elseif ($matches[4][$key]) { $height = $matches[4][$key]; } // If the dimensions are still not fixed - we need to check the actual image. - if (($width == -1 && $sig_limits[5]) || ($height == -1 && $sig_limits[6])) - { + if (($width == -1 && $sig_limits[5]) || ($height == -1 && $sig_limits[6])) { $sizes = Image::getSizeExternal($matches[7][$key]); - if (is_array($sizes)) - { + if (is_array($sizes)) { // Too wide? - if ($sizes[0] > $sig_limits[5] && $sig_limits[5]) - { + if ($sizes[0] > $sig_limits[5] && $sig_limits[5]) { $width = $sig_limits[5]; $sizes[1] = $sizes[1] * ($width / $sizes[0]); } // Too high? - if ($sizes[1] > $sig_limits[6] && $sig_limits[6]) - { + if ($sizes[1] > $sig_limits[6] && $sig_limits[6]) { $height = $sig_limits[6]; - if ($width == -1) + if ($width == -1) { $width = $sizes[0]; + } $width = $width * ($height / $sizes[1]); - } - elseif ($width != -1) - { + } elseif ($width != -1) { $height = $sizes[1]; } } } // Did we come up with some changes? If so remake the string. - if ($width != -1 || $height != -1) - { + if ($width != -1 || $height != -1) { $replaces[$image] = '[img' . ($width != -1 ? ' width=' . round($width) : '') . ($height != -1 ? ' height=' . round($height) : '') . ']' . $matches[7][$key] . '[/img]'; } @@ -572,121 +530,119 @@ public function signature(): void $image_count_holder[$image] = isset($image_count_holder[$image]) ? $image_count_holder[$image] + 1 : 1; } - if (!empty($replaces)) - { + if (!empty($replaces)) { $sig = str_replace(array_keys($replaces), array_values($replaces), $sig); } } } + // Try to fix disabled tags. - if (!empty($disabledTags)) - { - $sig = preg_replace('~\[(?:' . implode('|', $disabledTags) . ').+?\]~i', '', $sig); + if (!empty($disabledTags)) { + $sig = preg_replace('~\\[(?:' . implode('|', $disabledTags) . ').+?\\]~i', '', $sig); - $sig = preg_replace('~\[/(?:' . implode('|', $disabledTags) . ')\]~i', '', $sig); + $sig = preg_replace('~\\[/(?:' . implode('|', $disabledTags) . ')\\]~i', '', $sig); } - $sig = strtr($sig, array("\n" => '
')); + $sig = strtr($sig, ["\n" => '
']); - IntegrationHook::call('integrate_apply_signature_settings', array(&$sig, $sig_limits, $disabledTags)); + IntegrationHook::call('integrate_apply_signature_settings', [&$sig, $sig_limits, $disabledTags]); - if ($sig != $row['signature']) + if ($sig != $row['signature']) { $changes[$row['id_member']] = $sig; + } } - if (Db::$db->num_rows($request) == 0) + if (Db::$db->num_rows($request) == 0) { $done = true; + } Db::$db->free_result($request); // Do we need to delete what we have? - if (!empty($changes)) - { - foreach ($changes as $id => $sig) - { - Db::$db->query('', ' + if (!empty($changes)) { + foreach ($changes as $id => $sig) { + Db::$db->query( + '', + ' UPDATE {db_prefix}members SET signature = {string:signature} WHERE id_member = {int:id_member}', - array( + [ 'id_member' => $id, 'signature' => $sig, - ) + ], ); } } $_GET['step'] += 50; - if (!$done) + if (!$done) { $this->pauseSignatureApplySettings(); + } } $settings_applied = true; } - Utils::$context['signature_settings'] = array( - 'enable' => isset($sig_limits[0]) ? $sig_limits[0] : 0, - 'max_length' => isset($sig_limits[1]) ? $sig_limits[1] : 0, - 'max_lines' => isset($sig_limits[2]) ? $sig_limits[2] : 0, - 'max_images' => isset($sig_limits[3]) ? $sig_limits[3] : 0, + Utils::$context['signature_settings'] = [ + 'enable' => $sig_limits[0] ?? 0, + 'max_length' => $sig_limits[1] ?? 0, + 'max_lines' => $sig_limits[2] ?? 0, + 'max_images' => $sig_limits[3] ?? 0, 'allow_smileys' => isset($sig_limits[4]) && $sig_limits[4] == -1 ? 0 : 1, 'max_smileys' => isset($sig_limits[4]) && $sig_limits[4] != -1 ? $sig_limits[4] : 0, - 'max_image_width' => isset($sig_limits[5]) ? $sig_limits[5] : 0, - 'max_image_height' => isset($sig_limits[6]) ? $sig_limits[6] : 0, - 'max_font_size' => isset($sig_limits[7]) ? $sig_limits[7] : 0, - ); + 'max_image_width' => $sig_limits[5] ?? 0, + 'max_image_height' => $sig_limits[6] ?? 0, + 'max_font_size' => $sig_limits[7] ?? 0, + ]; // Temporarily make each setting a modSetting! - foreach (Utils::$context['signature_settings'] as $key => $value) + foreach (Utils::$context['signature_settings'] as $key => $value) { Config::$modSettings['signature_' . $key] = $value; + } // Make sure we check the right tags! Config::$modSettings['bbc_disabled_signature_bbc'] = $disabledTags; // Saving? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); // Clean up the tag stuff! - $bbcTags = array(); + $bbcTags = []; - foreach (BBCodeParser::getCodes() as $tag) + foreach (BBCodeParser::getCodes() as $tag) { $bbcTags[] = $tag['tag']; - - if (!isset($_POST['signature_bbc_enabledTags'])) - { - $_POST['signature_bbc_enabledTags'] = array(); } - elseif (!is_array($_POST['signature_bbc_enabledTags'])) - { - $_POST['signature_bbc_enabledTags'] = array($_POST['signature_bbc_enabledTags']); + + if (!isset($_POST['signature_bbc_enabledTags'])) { + $_POST['signature_bbc_enabledTags'] = []; + } elseif (!is_array($_POST['signature_bbc_enabledTags'])) { + $_POST['signature_bbc_enabledTags'] = [$_POST['signature_bbc_enabledTags']]; } - $sig_limits = array(); - foreach (Utils::$context['signature_settings'] as $key => $value) - { - if ($key == 'allow_smileys') + $sig_limits = []; + + foreach (Utils::$context['signature_settings'] as $key => $value) { + if ($key == 'allow_smileys') { continue; + } - if ($key == 'max_smileys' && empty($_POST['signature_allow_smileys'])) - { + if ($key == 'max_smileys' && empty($_POST['signature_allow_smileys'])) { $sig_limits[] = -1; - } - else - { + } else { $sig_limits[] = !empty($_POST['signature_' . $key]) ? max(1, (int) $_POST['signature_' . $key]) : 0; } } - IntegrationHook::call('integrate_save_signature_settings', array(&$sig_limits, &$bbcTags)); + IntegrationHook::call('integrate_save_signature_settings', [&$sig_limits, &$bbcTags]); $_POST['signature_settings'] = implode(',', $sig_limits) . ':' . implode(',', array_diff($bbcTags, $_POST['signature_bbc_enabledTags'])); // Even though we have practically no settings let's keep the convention going! - $save_vars = array(); - $save_vars[] = array('text', 'signature_settings'); + $save_vars = []; + $save_vars[] = ['text', 'signature_settings']; ACP::saveDBSettings($save_vars); $_SESSION['adm-save'] = true; @@ -696,21 +652,18 @@ public function signature(): void Utils::$context['post_url'] = Config::$scripturl . '?action=admin;area=featuresettings;save;sa=sig'; Utils::$context['settings_title'] = Lang::$txt['signature_settings']; - if (!empty($settings_applied)) - { - Utils::$context['settings_message'] = array( + if (!empty($settings_applied)) { + Utils::$context['settings_message'] = [ 'label' => Lang::$txt['signature_settings_applied'], 'tag' => 'div', - 'class' => 'infobox' - ); - } - else - { - Utils::$context['settings_message'] = array( + 'class' => 'infobox', + ]; + } else { + Utils::$context['settings_message'] = [ 'label' => sprintf(Lang::$txt['signature_settings_warning'], Utils::$context['session_id'], Utils::$context['session_var'], Config::$scripturl), 'tag' => 'div', - 'class' => 'centertext' - ); + 'class' => 'centertext', + ]; } ACP::prepareDBSettingContext($config_vars); @@ -725,37 +678,35 @@ public function profile(): void Utils::$context['sub_template'] = 'show_custom_profile'; // What about standard fields they can tweak? - $standard_fields = array('website', 'personal_text', 'timezone', 'posts', 'warning_status'); + $standard_fields = ['website', 'personal_text', 'timezone', 'posts', 'warning_status']; // What fields can't you put on the registration page? - Utils::$context['fields_no_registration'] = array('posts', 'warning_status'); + Utils::$context['fields_no_registration'] = ['posts', 'warning_status']; // Are we saving any standard field changes? - if (isset($_POST['save'])) - { + if (isset($_POST['save'])) { User::$me->checkSession(); SecurityToken::validate('admin-scp'); // Do the active ones first. $disable_fields = array_flip($standard_fields); - if (!empty($_POST['active'])) - { - foreach ($_POST['active'] as $value) + if (!empty($_POST['active'])) { + foreach ($_POST['active'] as $value) { unset($disable_fields[$value]); + } } // What we have left! $changes['disabled_profile_fields'] = empty($disable_fields) ? '' : implode(',', array_keys($disable_fields)); // Things we want to show on registration? - $reg_fields = array(); + $reg_fields = []; - if (!empty($_POST['reg'])) - { - foreach ($_POST['reg'] as $value) - { - if (in_array($value, $standard_fields) && !isset($disable_fields[$value])) + if (!empty($_POST['reg'])) { + foreach ($_POST['reg'] as $value) { + if (in_array($value, $standard_fields) && !isset($disable_fields[$value])) { $reg_fields[] = $value; + } } } @@ -764,8 +715,9 @@ public function profile(): void $_SESSION['adm-save'] = true; - if (!empty($changes)) + if (!empty($changes)) { Config::updateModSettings($changes); + } } SecurityToken::create('admin-scp'); @@ -773,219 +725,218 @@ public function profile(): void // Need to know the max order for custom fields Utils::$context['custFieldsMaxOrder'] = $this->custFieldsMaxOrder(); - $listOptions = array( + $listOptions = [ 'id' => 'standard_profile_fields', 'title' => Lang::$txt['standard_profile_title'], 'base_href' => Config::$scripturl . '?action=admin;area=featuresettings;sa=profile', - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getProfileFields', - 'params' => array( + 'params' => [ true, - ), - ), - 'columns' => array( - 'field' => array( - 'header' => array( + ], + ], + 'columns' => [ + 'field' => [ + 'header' => [ 'value' => Lang::$txt['standard_profile_field'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'label', 'style' => 'width: 60%;', - ), - ), - 'active' => array( - 'header' => array( + ], + ], + 'active' => [ + 'header' => [ 'value' => Lang::$txt['custom_edit_active'], 'class' => 'centercol', - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { $isChecked = $rowData['disabled'] ? '' : ' checked'; $onClickHandler = $rowData['can_show_register'] ? sprintf(' onclick="document.getElementById(\'reg_%1$s\').disabled = !this.checked;"', $rowData['id']) : ''; + return sprintf('', $rowData['id'], $isChecked, $onClickHandler); }, 'style' => 'width: 20%;', 'class' => 'centercol', - ), - ), - 'show_on_registration' => array( - 'header' => array( + ], + ], + 'show_on_registration' => [ + 'header' => [ 'value' => Lang::$txt['custom_edit_registration'], 'class' => 'centercol', - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { $isChecked = $rowData['on_register'] && !$rowData['disabled'] ? ' checked' : ''; $isDisabled = $rowData['can_show_register'] ? '' : ' disabled'; + return sprintf('', $rowData['id'], $isChecked, $isDisabled); }, 'style' => 'width: 20%;', 'class' => 'centercol', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=featuresettings;sa=profile', 'name' => 'standardProfileFields', 'token' => 'admin-scp', - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'below_table_data', 'value' => '', - ), - ), - ); + ], + ], + ]; new ItemList($listOptions); - $listOptions = array( + $listOptions = [ 'id' => 'custom_profile_fields', 'title' => Lang::$txt['custom_profile_title'], 'base_href' => Config::$scripturl . '?action=admin;area=featuresettings;sa=profile', 'default_sort_col' => 'field_order', 'no_items_label' => Lang::$txt['custom_profile_none'], 'items_per_page' => 25, - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getProfileFields', - 'params' => array( + 'params' => [ false, - ), - ), - 'get_count' => array( + ], + ], + 'get_count' => [ 'function' => __CLASS__ . '::list_getProfileFieldSize', - ), - 'columns' => array( - 'field_order' => array( - 'header' => array( + ], + 'columns' => [ + 'field_order' => [ + 'header' => [ 'value' => Lang::$txt['custom_profile_fieldorder'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { $return = '

'; - if ($rowData['field_order'] > 1) + if ($rowData['field_order'] > 1) { $return .= ''; + } - if ($rowData['field_order'] < Utils::$context['custFieldsMaxOrder']) + if ($rowData['field_order'] < Utils::$context['custFieldsMaxOrder']) { $return .= ''; + } $return .= '

'; return $return; }, 'style' => 'width: 12%;', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'field_order', 'reverse' => 'field_order DESC', - ), - ), - 'field_name' => array( - 'header' => array( + ], + ], + 'field_name' => [ + 'header' => [ 'value' => Lang::$txt['custom_profile_fieldname'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { $field_name = Lang::tokenTxtReplace($rowData['field_name']); $field_desc = Lang::tokenTxtReplace($rowData['field_desc']); - return sprintf('%3$s
%4$s
', + return sprintf( + '%3$s
%4$s
', Config::$scripturl, $rowData['id_field'], $field_name, - $field_desc); + $field_desc, + ); }, 'style' => 'width: 62%;', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'field_name', 'reverse' => 'field_name DESC', - ), - ), - 'field_type' => array( - 'header' => array( + ], + ], + 'field_type' => [ + 'header' => [ 'value' => Lang::$txt['custom_profile_fieldtype'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { $textKey = sprintf('custom_profile_type_%1$s', $rowData['field_type']); - return isset(Lang::$txt[$textKey]) ? Lang::$txt[$textKey] : $textKey; + + return Lang::$txt[$textKey] ?? $textKey; }, 'style' => 'width: 15%;', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'field_type', 'reverse' => 'field_type DESC', - ), - ), - 'active' => array( - 'header' => array( + ], + ], + 'active' => [ + 'header' => [ 'value' => Lang::$txt['custom_profile_active'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return $rowData['active'] ? Lang::$txt['yes'] : Lang::$txt['no']; }, 'style' => 'width: 8%;', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'active DESC', 'reverse' => 'active', - ), - ), - 'placement' => array( - 'header' => array( + ], + ], + 'placement' => [ + 'header' => [ 'value' => Lang::$txt['custom_profile_placement'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return Lang::$txt['custom_profile_placement_' . (empty($rowData['placement']) ? 'standard' : Utils::$context['cust_profile_fields_placement'][$rowData['placement']])]; }, 'style' => 'width: 8%;', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'placement DESC', 'reverse' => 'placement', - ), - ), - 'show_on_registration' => array( - 'data' => array( - 'sprintf' => array( + ], + ], + 'show_on_registration' => [ + 'data' => [ + 'sprintf' => [ 'format' => '' . Lang::$txt['modify'] . '', - 'params' => array( + 'params' => [ 'id_field' => false, - ), - ), + ], + ], 'style' => 'width: 15%;', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=featuresettings;sa=profileedit', 'name' => 'customProfileFields', - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'below_table_data', 'value' => '', - ), - ), - ); + ], + ], + ]; new ItemList($listOptions); // There are two different ways we could get to this point. To keep it simple, they both do // the same basic thing. - if (isset($_SESSION['adm-save'])) - { + if (isset($_SESSION['adm-save'])) { Utils::$context['saved_successful'] = true; - unset ($_SESSION['adm-save']); + unset($_SESSION['adm-save']); } } @@ -1004,38 +955,36 @@ public function profileEdit() Lang::load('Profile'); // There's really only a few places we can go... - $move_to = array('up', 'down'); + $move_to = ['up', 'down']; // We need this for both moving and saving so put it right here. $order_count = $this->custFieldsMaxOrder(); - if (Utils::$context['fid'] && !isset($_GET['move'])) - { - Utils::$context['field'] = array(); - $request = Db::$db->query('', ' + if (Utils::$context['fid'] && !isset($_GET['move'])) { + Utils::$context['field'] = []; + $request = Db::$db->query( + '', + ' SELECT id_field, col_name, field_name, field_desc, field_type, field_order, field_length, field_options, show_reg, show_display, show_mlist, show_profile, private, active, default_value, can_search, bbc, mask, enclose, placement FROM {db_prefix}custom_fields WHERE id_field = {int:current_field}', - array( + [ 'current_field' => Utils::$context['fid'], - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { - if ($row['field_type'] == 'textarea') - { + + while ($row = Db::$db->fetch_assoc($request)) { + if ($row['field_type'] == 'textarea') { @list($rows, $cols) = @explode(',', $row['default_value']); - } - else - { + } else { $rows = 3; $cols = 30; } - Utils::$context['field'] = array( + Utils::$context['field'] = [ 'name' => $row['field_name'], 'desc' => $row['field_desc'], 'col_name' => $row['col_name'], @@ -1051,7 +1000,7 @@ public function profileEdit() 'bbc' => $row['bbc'] ? true : false, 'default_check' => $row['field_type'] == 'check' && $row['default_value'] ? true : false, 'default_select' => $row['field_type'] == 'select' || $row['field_type'] == 'radio' ? $row['default_value'] : '', - 'options' => strlen($row['field_options']) > 1 ? explode(',', $row['field_options']) : array('', '', ''), + 'options' => strlen($row['field_options']) > 1 ? explode(',', $row['field_options']) : ['', '', ''], 'active' => $row['active'], 'private' => $row['private'], 'can_search' => $row['can_search'], @@ -1059,14 +1008,14 @@ public function profileEdit() 'regex' => substr($row['mask'], 0, 5) == 'regex' ? substr($row['mask'], 5) : '', 'enclose' => $row['enclose'], 'placement' => $row['placement'], - ); + ]; } Db::$db->free_result($request); } // Setup the default values as needed. - if (empty(Utils::$context['field'])) - Utils::$context['field'] = array( + if (empty(Utils::$context['field'])) { + Utils::$context['field'] = [ 'name' => '', 'col_name' => '???', 'desc' => '', @@ -1082,7 +1031,7 @@ public function profileEdit() 'bbc' => false, 'default_check' => false, 'default_select' => '', - 'options' => array('', '', ''), + 'options' => ['', '', ''], 'active' => true, 'private' => false, 'can_search' => false, @@ -1090,60 +1039,59 @@ public function profileEdit() 'regex' => '', 'enclose' => '', 'placement' => 0, - ); + ]; + } // Are we moving it? - if (Utils::$context['fid'] && isset($_GET['move']) && in_array(Utils::htmlspecialchars($_GET['move']), $move_to)) - { - $fields = array(); - $new_sort = array(); + if (Utils::$context['fid'] && isset($_GET['move']) && in_array(Utils::htmlspecialchars($_GET['move']), $move_to)) { + $fields = []; + $new_sort = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_field, field_order FROM {db_prefix}custom_fields ORDER BY field_order', - array() + [], ); - while($row = Db::$db->fetch_assoc($request)) - { + + while($row = Db::$db->fetch_assoc($request)) { $fields[] = $row['id_field']; } Db::$db->free_result($request); $idx = array_search(Utils::$context['fid'], $fields); - if ($_GET['move'] == 'down' && count($fields) - 1 > $idx ) - { - $new_sort = array_slice($fields ,0 ,$idx ,true); + if ($_GET['move'] == 'down' && count($fields) - 1 > $idx) { + $new_sort = array_slice($fields, 0, $idx, true); $new_sort[] = $fields[$idx + 1]; $new_sort[] = $fields[$idx]; - $new_sort += array_slice($fields ,$idx + 2 ,count($fields) ,true); - } - elseif (Utils::$context['fid'] > 0 and $idx < count($fields)) - { - $new_sort = array_slice($fields ,0 ,($idx - 1) ,true); + $new_sort += array_slice($fields, $idx + 2, count($fields), true); + } elseif (Utils::$context['fid'] > 0 and $idx < count($fields)) { + $new_sort = array_slice($fields, 0, ($idx - 1), true); $new_sort[] = $fields[$idx]; $new_sort[] = $fields[$idx - 1]; - $new_sort += array_slice($fields ,($idx + 1) ,count($fields) ,true); - } - else - { + $new_sort += array_slice($fields, ($idx + 1), count($fields), true); + } else { // @todo implement an error handler Utils::redirectexit('action=admin;area=featuresettings;sa=profile'); } $sql_update = 'CASE '; - foreach ($new_sort as $orderKey => $PKid) - { + + foreach ($new_sort as $orderKey => $PKid) { $sql_update .= 'WHEN id_field = ' . $PKid . ' THEN ' . ($orderKey + 1) . ' '; } $sql_update .= 'END'; - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}custom_fields SET field_order = ' . $sql_update, - array() + [], ); // @todo perhaps a nice confirmation message, dunno. @@ -1151,20 +1099,17 @@ public function profileEdit() } // Are we saving? - if (isset($_POST['save'])) - { + if (isset($_POST['save'])) { User::$me->checkSession(); SecurityToken::validate('admin-ecp'); // Everyone needs a name - even the (bracket) unknown... - if (trim($_POST['field_name']) == '') - { + if (trim($_POST['field_name']) == '') { Utils::redirectexit(Config::$scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $_GET['fid'] . ';msg=need_name'); } // Regex you say? Do a very basic test to see if the pattern is valid - if (!empty($_POST['regex']) && @preg_match($_POST['regex'], 'dummy') === false) - { + if (!empty($_POST['regex']) && @preg_match($_POST['regex'], 'dummy') === false) { Utils::redirectexit(Config::$scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $_GET['fid'] . ';msg=regex_error'); } @@ -1182,10 +1127,11 @@ public function profileEdit() $can_search = isset($_POST['can_search']) ? 1 : 0; // Some masking stuff... - $mask = isset($_POST['mask']) ? $_POST['mask'] : ''; + $mask = $_POST['mask'] ?? ''; - if ($mask == 'regex' && isset($_POST['regex'])) + if ($mask == 'regex' && isset($_POST['regex'])) { $mask .= $_POST['regex']; + } $mask = Utils::normalize($mask); @@ -1195,20 +1141,19 @@ public function profileEdit() // Select options? $field_options = ''; - $newOptions = array(); + $newOptions = []; $default = isset($_POST['default_check']) && $_POST['field_type'] == 'check' ? 1 : ''; - if (!empty($_POST['select_option']) && ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio')) - { - foreach ($_POST['select_option'] as $k => $v) - { + if (!empty($_POST['select_option']) && ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio')) { + foreach ($_POST['select_option'] as $k => $v) { // Clean, clean, clean... $v = Utils::htmlspecialchars($v); - $v = strtr($v, array(',' => '')); + $v = strtr($v, [',' => '']); // Nada, zip, etc... - if (trim($v) == '') + if (trim($v) == '') { continue; + } // Otherwise, save it boy. $field_options .= $v . ','; @@ -1216,23 +1161,24 @@ public function profileEdit() $newOptions[$k] = $v; // Is it default? - if (isset($_POST['default_select']) && $_POST['default_select'] == $k) + if (isset($_POST['default_select']) && $_POST['default_select'] == $k) { $default = $v; + } } $field_options = substr($field_options, 0, -1); } // Text area has default has dimensions - if ($_POST['field_type'] == 'textarea') + if ($_POST['field_type'] == 'textarea') { $default = (int) $_POST['rows'] . ',' . (int) $_POST['cols']; + } // Come up with the unique name? - if (empty(Utils::$context['fid'])) - { + if (empty(Utils::$context['fid'])) { $col_name = Utils::normalize($_POST['field_name'], 'kc_casefold'); $col_name = Utils::sanitizeChars($col_name, 2, '-'); - $col_name = preg_replace('~[^\w-]~u', '', $col_name); + $col_name = preg_replace('~[^\\w-]~u', '', $col_name); $col_name = trim($col_name, '-_'); $col_name = Utils::truncate($col_name, 6); @@ -1240,39 +1186,39 @@ public function profileEdit() $col_name = $initial_col_name = 'cust_' . (!empty($col_name) ? $col_name : bin2hex(Utils::randomBytes(3))); // Make sure this is unique. - $current_fields = array(); - $request = Db::$db->query('', ' + $current_fields = []; + $request = Db::$db->query( + '', + ' SELECT id_field, col_name - FROM {db_prefix}custom_fields' + FROM {db_prefix}custom_fields', ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $current_fields[$row['id_field']] = $row['col_name']; } Db::$db->free_result($request); $i = 0; - while (in_array($col_name, $current_fields)) - { + + while (in_array($col_name, $current_fields)) { // First try appending an integer to the supplied name. - if ($i <= 9) - { + if ($i <= 9) { $col_name = $initial_col_name . $i; } // Still not a unique column name? Use a random one, then. - else - { + else { $col_name = substr('cust_' . bin2hex(Utils::randomBytes(4)), 0, 12); } // In this extremely unlikely event, bail out. - if (++$i > 20) + if (++$i > 20) { ErrorHandler::fatalLang('custom_option_not_unique'); + } } } // Work out what to do with the user data otherwise... - else - { + else { // Anything going to check or select is pointless keeping - as is anything coming from check! if ( ( @@ -1291,53 +1237,54 @@ public function profileEdit() Utils::$context['field']['type'] == 'check' && $_POST['field_type'] != 'check' ) - ) - { - Db::$db->query('', ' + ) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}themes WHERE variable = {string:current_column} AND id_member > {int:no_member}', - array( + [ 'no_member' => 0, 'current_column' => Utils::$context['field']['col_name'], - ) + ], ); } // Otherwise - if the select is edited may need to adjust! - elseif ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') - { - $optionChanges = array(); - $takenKeys = array(); + elseif ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') { + $optionChanges = []; + $takenKeys = []; // Work out what's changed! - foreach (Utils::$context['field']['options'] as $k => $option) - { - if (trim($option) == '') + foreach (Utils::$context['field']['options'] as $k => $option) { + if (trim($option) == '') { continue; + } // Still exists? - if (in_array($option, $newOptions)) + if (in_array($option, $newOptions)) { $takenKeys[] = $k; + } } // Finally - have we renamed it - or is it really gone? - foreach ($optionChanges as $k => $option) - { + foreach ($optionChanges as $k => $option) { // Just been renamed? - if (!in_array($k, $takenKeys) && !empty($newOptions[$k])) - { - Db::$db->query('', ' + if (!in_array($k, $takenKeys) && !empty($newOptions[$k])) { + Db::$db->query( + '', + ' UPDATE {db_prefix}themes SET value = {string:new_value} WHERE variable = {string:current_column} AND value = {string:old_value} AND id_member > {int:no_member}', - array( + [ 'no_member' => 0, 'new_value' => $newOptions[$k], 'current_column' => Utils::$context['field']['col_name'], 'old_value' => $option, - ) + ], ); } } @@ -1346,9 +1293,10 @@ public function profileEdit() } // Do the insertion/updates. - if (Utils::$context['fid']) - { - Db::$db->query('', ' + if (Utils::$context['fid']) { + Db::$db->query( + '', + ' UPDATE {db_prefix}custom_fields SET field_name = {string:field_name}, field_desc = {string:field_desc}, @@ -1359,7 +1307,7 @@ public function profileEdit() can_search = {int:can_search}, bbc = {int:bbc}, mask = {string:mask}, enclose = {string:enclose}, placement = {int:placement} WHERE id_field = {int:current_field}', - array( + [ 'field_length' => $field_length, 'show_reg' => $show_reg, 'show_display' => $show_display, @@ -1378,94 +1326,100 @@ public function profileEdit() 'mask' => $mask, 'enclose' => $enclose, 'placement' => $placement, - ) + ], ); // Just clean up any old selects - these are a pain! - if (($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') && !empty($newOptions)) - { - Db::$db->query('', ' + if (($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') && !empty($newOptions)) { + Db::$db->query( + '', + ' DELETE FROM {db_prefix}themes WHERE variable = {string:current_column} AND value NOT IN ({array_string:new_option_values}) AND id_member > {int:no_member}', - array( + [ 'no_member' => 0, 'new_option_values' => $newOptions, 'current_column' => Utils::$context['field']['col_name'], - ) + ], ); } - } - else - { + } else { // Gotta figure it out the order. $new_order = $order_count > 1 ? ($order_count + 1) : 1; - Db::$db->insert('', + Db::$db->insert( + '', '{db_prefix}custom_fields', - array( + [ 'col_name' => 'string', 'field_name' => 'string', 'field_desc' => 'string', 'field_type' => 'string', 'field_length' => 'string', 'field_options' => 'string', 'field_order' => 'int', 'show_reg' => 'int', 'show_display' => 'int', 'show_mlist' => 'int', 'show_profile' => 'string', 'private' => 'int', 'active' => 'int', 'default_value' => 'string', 'can_search' => 'int', 'bbc' => 'int', 'mask' => 'string', 'enclose' => 'string', 'placement' => 'int', - ), - array( + ], + [ $col_name, $_POST['field_name'], $_POST['field_desc'], $_POST['field_type'], $field_length, $field_options, $new_order, $show_reg, $show_display, $show_mlist, $show_profile, $private, $active, $default, $can_search, $bbc, $mask, $enclose, $placement, - ), - array('id_field') + ], + ['id_field'], ); } } // Deleting? - elseif (isset($_POST['delete']) && Utils::$context['field']['col_name']) - { + elseif (isset($_POST['delete']) && Utils::$context['field']['col_name']) { User::$me->checkSession(); SecurityToken::validate('admin-ecp'); // Delete the user data first. - Db::$db->query('', ' + Db::$db->query( + '', + ' DELETE FROM {db_prefix}themes WHERE variable = {string:current_column} AND id_member > {int:no_member}', - array( + [ 'no_member' => 0, 'current_column' => Utils::$context['field']['col_name'], - ) + ], ); // Finally - the field itself is gone! - Db::$db->query('', ' + Db::$db->query( + '', + ' DELETE FROM {db_prefix}custom_fields WHERE id_field = {int:current_field}', - array( + [ 'current_field' => Utils::$context['fid'], - ) + ], ); // Re-arrange the order. - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}custom_fields SET field_order = field_order - 1 WHERE field_order > {int:current_order}', - array( + [ 'current_order' => Utils::$context['field']['order'], - ) + ], ); } // Rebuild display cache etc. - if (isset($_POST['delete']) || isset($_POST['save'])) - { + if (isset($_POST['delete']) || isset($_POST['save'])) { User::$me->checkSession(); - $fields = array(); - $request = Db::$db->query('', ' + $fields = []; + $request = Db::$db->query( + '', + ' SELECT col_name, field_name, field_type, field_order, bbc, enclose, placement, show_mlist, field_options FROM {db_prefix}custom_fields WHERE show_display = {int:is_displayed} @@ -1473,30 +1427,30 @@ public function profileEdit() AND private != {int:not_owner_only} AND private != {int:not_admin_only} ORDER BY field_order', - array( + [ 'is_displayed' => 1, 'active' => 1, 'not_owner_only' => 2, 'not_admin_only' => 3, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { - $fields[] = array( - 'col_name' => strtr($row['col_name'], array('|' => '', ';' => '')), - 'title' => strtr($row['field_name'], array('|' => '', ';' => '')), + + while ($row = Db::$db->fetch_assoc($request)) { + $fields[] = [ + 'col_name' => strtr($row['col_name'], ['|' => '', ';' => '']), + 'title' => strtr($row['field_name'], ['|' => '', ';' => '']), 'type' => $row['field_type'], 'order' => $row['field_order'], 'bbc' => $row['bbc'] ? '1' : '0', 'placement' => !empty($row['placement']) ? $row['placement'] : '0', 'enclose' => !empty($row['enclose']) ? $row['enclose'] : '', 'mlist' => $row['show_mlist'], - 'options' => (!empty($row['field_options']) ? explode(',', $row['field_options']) : array()), - ); + 'options' => (!empty($row['field_options']) ? explode(',', $row['field_options']) : []), + ]; } Db::$db->free_result($request); - Config::updateModSettings(array('displayFields' => Utils::jsonEncode($fields))); + Config::updateModSettings(['displayFields' => Utils::jsonEncode($fields)]); $_SESSION['adm-save'] = true; Utils::redirectexit('action=admin;area=featuresettings;sa=profile'); } @@ -1514,8 +1468,7 @@ public function likes(): void $config_vars = self::likesConfigVars(); // Saving? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); IntegrationHook::call('integrate_save_likes_settings'); @@ -1541,8 +1494,7 @@ public function mentions(): void $config_vars = self::mentionsConfigVars(); // Saving? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); IntegrationHook::call('integrate_save_mentions_settings'); @@ -1565,7 +1517,7 @@ public function alerts() { // Dummy settings for the template... User::$me->is_owner = false; - Utils::$context['member'] = array(); + Utils::$context['member'] = []; Utils::$context['id_member'] = 0; Utils::$context['menu_item_selected'] = 'alerts'; Utils::$context['token_check'] = 'noti-admin'; @@ -1597,8 +1549,9 @@ public function alerts() */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -1620,88 +1573,88 @@ public static function basicConfigVars(): array { // We need to know if personal text is enabled, and if it's in the registration fields option. // If admins have set it up as an on-registration thing, they can't set a default value (because it'll never be used) - $disabled_fields = isset(Config::$modSettings['disabled_profile_fields']) ? explode(',', Config::$modSettings['disabled_profile_fields']) : array(); - $reg_fields = isset(Config::$modSettings['registration_fields']) ? explode(',', Config::$modSettings['registration_fields']) : array(); + $disabled_fields = isset(Config::$modSettings['disabled_profile_fields']) ? explode(',', Config::$modSettings['disabled_profile_fields']) : []; + $reg_fields = isset(Config::$modSettings['registration_fields']) ? explode(',', Config::$modSettings['registration_fields']) : []; $can_personal_text = !in_array('personal_text', $disabled_fields) && !in_array('personal_text', $reg_fields); - $config_vars = array( + $config_vars = [ // Big Options... polls, sticky, bbc.... - array('select', 'pollMode', array(Lang::$txt['disable_polls'], Lang::$txt['enable_polls'], Lang::$txt['polls_as_topics'])), + ['select', 'pollMode', [Lang::$txt['disable_polls'], Lang::$txt['enable_polls'], Lang::$txt['polls_as_topics']]], '', // Basic stuff, titles, flash, permissions... - array('check', 'allow_guestAccess'), - array('check', 'enable_buddylist'), - array('check', 'allow_hideOnline'), - array('check', 'titlesEnable'), - array('text', 'default_personal_text', 'subtext' => Lang::$txt['default_personal_text_note'], 'disabled' => !$can_personal_text), - array('check', 'topic_move_any'), - array('int', 'defaultMaxListItems', 'step' => 1, 'min' => 1, 'max' => 999), + ['check', 'allow_guestAccess'], + ['check', 'enable_buddylist'], + ['check', 'allow_hideOnline'], + ['check', 'titlesEnable'], + ['text', 'default_personal_text', 'subtext' => Lang::$txt['default_personal_text_note'], 'disabled' => !$can_personal_text], + ['check', 'topic_move_any'], + ['int', 'defaultMaxListItems', 'step' => 1, 'min' => 1, 'max' => 999], '', // Jquery source - array( + [ 'select', 'jquery_source', - array( + [ 'cdn' => Lang::$txt['jquery_google_cdn'], 'jquery_cdn' => Lang::$txt['jquery_jquery_cdn'], 'microsoft_cdn' => Lang::$txt['jquery_microsoft_cdn'], 'local' => Lang::$txt['jquery_local'], - 'custom' => Lang::$txt['jquery_custom'] - ), - 'onchange' => 'if (this.value == \'custom\'){document.getElementById(\'jquery_custom\').disabled = false; } else {document.getElementById(\'jquery_custom\').disabled = true;}' - ), - array( + 'custom' => Lang::$txt['jquery_custom'], + ], + 'onchange' => 'if (this.value == \'custom\'){document.getElementById(\'jquery_custom\').disabled = false; } else {document.getElementById(\'jquery_custom\').disabled = true;}', + ], + [ 'text', 'jquery_custom', - 'disabled' => !isset(Config::$modSettings['jquery_source']) || (isset(Config::$modSettings['jquery_source']) && Config::$modSettings['jquery_source'] != 'custom'), 'size' => 75 - ), + 'disabled' => !isset(Config::$modSettings['jquery_source']) || (isset(Config::$modSettings['jquery_source']) && Config::$modSettings['jquery_source'] != 'custom'), 'size' => 75, + ], '', // css and js minification. - array('check', 'minimize_files'), + ['check', 'minimize_files'], '', // SEO stuff - array('check', 'queryless_urls', 'subtext' => '' . Lang::$txt['queryless_urls_note'] . ''), - array('text', 'meta_keywords', 'subtext' => Lang::$txt['meta_keywords_note'], 'size' => 50), + ['check', 'queryless_urls', 'subtext' => '' . Lang::$txt['queryless_urls_note'] . ''], + ['text', 'meta_keywords', 'subtext' => Lang::$txt['meta_keywords_note'], 'size' => 50], '', // Time zone and formatting. - array('text', 'time_format'), - array('select', 'default_timezone', array_filter(TimeZone::list(), 'is_string', ARRAY_FILTER_USE_KEY)), - array('text', 'timezone_priority_countries', 'subtext' => Lang::$txt['setting_timezone_priority_countries_note']), + ['text', 'time_format'], + ['select', 'default_timezone', array_filter(TimeZone::list(), 'is_string', ARRAY_FILTER_USE_KEY)], + ['text', 'timezone_priority_countries', 'subtext' => Lang::$txt['setting_timezone_priority_countries_note']], '', // Who's online? - array('check', 'who_enabled'), - array('int', 'lastActive', 6, 'postinput' => Lang::$txt['minutes']), + ['check', 'who_enabled'], + ['int', 'lastActive', 6, 'postinput' => Lang::$txt['minutes']], '', // Statistics. - array('check', 'trackStats'), - array('check', 'hitStats'), + ['check', 'trackStats'], + ['check', 'hitStats'], '', // Option-ish things... miscellaneous sorta. - array('check', 'disallow_sendBody'), + ['check', 'disallow_sendBody'], '', // Alerts stuff - array('check', 'enable_ajax_alerts'), - array('select', 'alerts_auto_purge', - array( + ['check', 'enable_ajax_alerts'], + ['select', 'alerts_auto_purge', + [ '0' => Lang::$txt['alerts_auto_purge_0'], '7' => Lang::$txt['alerts_auto_purge_7'], '30' => Lang::$txt['alerts_auto_purge_30'], '90' => Lang::$txt['alerts_auto_purge_90'], - ), - ), - array('int', 'alerts_per_page', 'step' => 1, 'min' => 0, 'max' => 999), - ); + ], + ], + ['int', 'alerts_per_page', 'step' => 1, 'min' => 0, 'max' => 999], + ]; - IntegrationHook::call('integrate_modify_basic_settings', array(&$config_vars)); + IntegrationHook::call('integrate_modify_basic_settings', [&$config_vars]); return $config_vars; } @@ -1713,32 +1666,34 @@ public static function basicConfigVars(): array */ public static function bbcConfigVars(): array { - $config_vars = array( + $config_vars = [ // Main tweaks - array('check', 'enableBBC'), - array('check', 'enableBBC', 0, 'onchange' => 'toggleBBCDisabled(\'disabledBBC\', !this.checked); toggleBBCDisabled(\'legacyBBC\', !this.checked);'), - array('check', 'enablePostHTML'), - array('check', 'autoLinkUrls'), + ['check', 'enableBBC'], + ['check', 'enableBBC', 0, 'onchange' => 'toggleBBCDisabled(\'disabledBBC\', !this.checked); toggleBBCDisabled(\'legacyBBC\', !this.checked);'], + ['check', 'enablePostHTML'], + ['check', 'autoLinkUrls'], '', - array('bbc', 'disabledBBC'), + ['bbc', 'disabledBBC'], // This one is actually pretend... - array('bbc', 'legacyBBC', 'help' => 'legacy_bbc'), - ); + ['bbc', 'legacyBBC', 'help' => 'legacy_bbc'], + ]; // Permissions for restricted BBC - if (!empty(Utils::$context['restricted_bbc'])) + if (!empty(Utils::$context['restricted_bbc'])) { $config_vars[] = ''; + } - foreach (Utils::$context['restricted_bbc'] as $bbc) - $config_vars[] = array('permissions', 'bbc_' . $bbc, 'text_label' => sprintf(Lang::$txt['groups_can_use'], '[' . $bbc . ']')); + foreach (Utils::$context['restricted_bbc'] as $bbc) { + $config_vars[] = ['permissions', 'bbc_' . $bbc, 'text_label' => sprintf(Lang::$txt['groups_can_use'], '[' . $bbc . ']')]; + } Utils::$context['settings_post_javascript'] = ' toggleBBCDisabled(\'disabledBBC\', ' . (empty(Config::$modSettings['enableBBC']) ? 'true' : 'false') . '); toggleBBCDisabled(\'legacyBBC\', ' . (empty(Config::$modSettings['enableBBC']) ? 'true' : 'false') . ');'; - IntegrationHook::call('integrate_modify_bbc_settings', array(&$config_vars)); + IntegrationHook::call('integrate_modify_bbc_settings', [&$config_vars]); return $config_vars; } @@ -1750,28 +1705,28 @@ public static function bbcConfigVars(): array */ public static function layoutConfigVars(): array { - $config_vars = array( + $config_vars = [ // Pagination stuff. - array('check', 'compactTopicPagesEnable'), - array( + ['check', 'compactTopicPagesEnable'], + [ 'int', 'compactTopicPagesContiguous', null, - Lang::$txt['contiguous_page_display'] . '
' . str_replace(' ', ' ', '"3" ' . Lang::$txt['to_display'] . ': 1 ... 4 [5] 6 ... 9') . '
' . str_replace(' ', ' ', '"5" ' . Lang::$txt['to_display'] . ': 1 ... 3 4 [5] 6 7 ... 9') . '
' - ), - array('int', 'defaultMaxMembers'), + Lang::$txt['contiguous_page_display'] . '
' . str_replace(' ', ' ', '"3" ' . Lang::$txt['to_display'] . ': 1 ... 4 [5] 6 ... 9') . '
' . str_replace(' ', ' ', '"5" ' . Lang::$txt['to_display'] . ': 1 ... 3 4 [5] 6 7 ... 9') . '
', + ], + ['int', 'defaultMaxMembers'], '', // Stuff that just is everywhere - today, search, online, etc. - array('select', 'todayMod', array(Lang::$txt['today_disabled'], Lang::$txt['today_only'], Lang::$txt['yesterday_today'])), - array('check', 'onlineEnable'), + ['select', 'todayMod', [Lang::$txt['today_disabled'], Lang::$txt['today_only'], Lang::$txt['yesterday_today']]], + ['check', 'onlineEnable'], '', // This is like debugging sorta. - array('check', 'timeLoadPageEnable'), - ); + ['check', 'timeLoadPageEnable'], + ]; - IntegrationHook::call('integrate_layout_settings', array(&$config_vars)); + IntegrationHook::call('integrate_layout_settings', [&$config_vars]); return $config_vars; } @@ -1783,29 +1738,29 @@ public static function layoutConfigVars(): array */ public static function sigConfigVars(): array { - $config_vars = array( + $config_vars = [ // Are signatures even enabled? - array('check', 'signature_enable'), + ['check', 'signature_enable'], '', // Tweaking settings! - array('int', 'signature_max_length', 'subtext' => Lang::$txt['zero_for_no_limit']), - array('int', 'signature_max_lines', 'subtext' => Lang::$txt['zero_for_no_limit']), - array('int', 'signature_max_font_size', 'subtext' => Lang::$txt['zero_for_no_limit']), - array('check', 'signature_allow_smileys', 'onclick' => 'document.getElementById(\'signature_max_smileys\').disabled = !this.checked;'), - array('int', 'signature_max_smileys', 'subtext' => Lang::$txt['zero_for_no_limit']), + ['int', 'signature_max_length', 'subtext' => Lang::$txt['zero_for_no_limit']], + ['int', 'signature_max_lines', 'subtext' => Lang::$txt['zero_for_no_limit']], + ['int', 'signature_max_font_size', 'subtext' => Lang::$txt['zero_for_no_limit']], + ['check', 'signature_allow_smileys', 'onclick' => 'document.getElementById(\'signature_max_smileys\').disabled = !this.checked;'], + ['int', 'signature_max_smileys', 'subtext' => Lang::$txt['zero_for_no_limit']], '', // Image settings. - array('int', 'signature_max_images', 'subtext' => Lang::$txt['signature_max_images_note']), - array('int', 'signature_max_image_width', 'subtext' => Lang::$txt['zero_for_no_limit']), - array('int', 'signature_max_image_height', 'subtext' => Lang::$txt['zero_for_no_limit']), + ['int', 'signature_max_images', 'subtext' => Lang::$txt['signature_max_images_note']], + ['int', 'signature_max_image_width', 'subtext' => Lang::$txt['zero_for_no_limit']], + ['int', 'signature_max_image_height', 'subtext' => Lang::$txt['zero_for_no_limit']], '', - array('bbc', 'signature_bbc'), - ); + ['bbc', 'signature_bbc'], + ]; - IntegrationHook::call('integrate_signature_settings', array(&$config_vars)); + IntegrationHook::call('integrate_signature_settings', [&$config_vars]); return $config_vars; } @@ -1817,12 +1772,12 @@ public static function sigConfigVars(): array */ public static function likesConfigVars(): array { - $config_vars = array( - array('check', 'enable_likes'), - array('permissions', 'likes_like'), - ); + $config_vars = [ + ['check', 'enable_likes'], + ['permissions', 'likes_like'], + ]; - IntegrationHook::call('integrate_likes_settings', array(&$config_vars)); + IntegrationHook::call('integrate_likes_settings', [&$config_vars]); return $config_vars; } @@ -1834,12 +1789,12 @@ public static function likesConfigVars(): array */ public static function mentionsConfigVars(): array { - $config_vars = array( - array('check', 'enable_mentions'), - array('permissions', 'mention'), - ); + $config_vars = [ + ['check', 'enable_mentions'], + ['permissions', 'mention'], + ]; - IntegrationHook::call('integrate_mentions_settings', array(&$config_vars)); + IntegrationHook::call('integrate_mentions_settings', [&$config_vars]); return $config_vars; } @@ -1855,40 +1810,42 @@ public static function mentionsConfigVars(): array */ public static function list_getProfileFields($start, $items_per_page, $sort, $standardFields): array { - $list = array(); + $list = []; - if ($standardFields) - { - $standard_fields = array('website', 'personal_text', 'timezone', 'posts', 'warning_status'); - $fields_no_registration = array('posts', 'warning_status'); - $disabled_fields = isset(Config::$modSettings['disabled_profile_fields']) ? explode(',', Config::$modSettings['disabled_profile_fields']) : array(); - $registration_fields = isset(Config::$modSettings['registration_fields']) ? explode(',', Config::$modSettings['registration_fields']) : array(); + if ($standardFields) { + $standard_fields = ['website', 'personal_text', 'timezone', 'posts', 'warning_status']; + $fields_no_registration = ['posts', 'warning_status']; + $disabled_fields = isset(Config::$modSettings['disabled_profile_fields']) ? explode(',', Config::$modSettings['disabled_profile_fields']) : []; + $registration_fields = isset(Config::$modSettings['registration_fields']) ? explode(',', Config::$modSettings['registration_fields']) : []; - foreach ($standard_fields as $field) - $list[] = array( + foreach ($standard_fields as $field) { + $list[] = [ 'id' => $field, - 'label' => isset(Lang::$txt['standard_profile_field_' . $field]) ? Lang::$txt['standard_profile_field_' . $field] : (isset(Lang::$txt[$field]) ? Lang::$txt[$field] : $field), + 'label' => Lang::$txt['standard_profile_field_' . $field] ?? (Lang::$txt[$field] ?? $field), 'disabled' => in_array($field, $disabled_fields), 'on_register' => in_array($field, $registration_fields) && !in_array($field, $fields_no_registration), 'can_show_register' => !in_array($field, $fields_no_registration), - ); - } - else - { + ]; + } + } else { // Load all the fields. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_field, col_name, field_name, field_desc, field_type, field_order, active, placement FROM {db_prefix}custom_fields ORDER BY {raw:sort} LIMIT {int:start}, {int:items_per_page}', - array( + [ 'sort' => $sort, 'start' => $start, 'items_per_page' => $items_per_page, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) + + while ($row = Db::$db->fetch_assoc($request)) { $list[] = $row; + } Db::$db->free_result($request); } @@ -1902,14 +1859,16 @@ public static function list_getProfileFields($start, $items_per_page, $sort, $st */ public static function list_getProfileFieldSize(): int { - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}custom_fields', - array( - ) + [ + ], ); - list ($numProfileFields) = Db::$db->fetch_row($request); + list($numProfileFields) = Db::$db->fetch_row($request); Db::$db->free_result($request); return $numProfileFields; @@ -1923,8 +1882,9 @@ public static function list_getProfileFieldSize(): int */ public static function modifyBasicSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::basicConfigVars(); + } self::load(); self::$obj->subaction = 'basic'; @@ -1939,8 +1899,9 @@ public static function modifyBasicSettings($return_config = false) */ public static function modifyBBCSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::bbcConfigVars(); + } self::load(); self::$obj->subaction = 'bbc'; @@ -1955,8 +1916,9 @@ public static function modifyBBCSettings($return_config = false) */ public static function modifyLayoutSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::layoutConfigVars(); + } self::load(); self::$obj->subaction = 'layout'; @@ -1971,8 +1933,9 @@ public static function modifyLayoutSettings($return_config = false) */ public static function modifySignatureSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::sigConfigVars(); + } self::load(); self::$obj->subaction = 'sig'; @@ -2007,8 +1970,9 @@ public static function editCustomProfiles(): void */ public static function modifyLikesSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::likesConfigVars(); + } self::load(); self::$obj->subaction = 'likes'; @@ -2023,8 +1987,9 @@ public static function modifyLikesSettings($return_config = false) */ public static function modifyMentionsSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::mentionsConfigVars(); + } self::load(); self::$obj->subaction = 'mentions'; @@ -2057,38 +2022,39 @@ protected function __construct() Utils::$context['show_privacy_policy_warning'] = empty(Config::$modSettings['policy_' . Lang::$default]); // Load up all the tabs... - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['modSettings_title'], 'help' => 'featuresettings', 'description' => sprintf(Lang::$txt['modSettings_desc'], Theme::$current->settings['theme_id'], Utils::$context['session_id'], Utils::$context['session_var'], Config::$scripturl), - 'tabs' => array( - 'basic' => array( - ), - 'bbc' => array( + 'tabs' => [ + 'basic' => [ + ], + 'bbc' => [ 'description' => Lang::$txt['manageposts_bbc_settings_description'], - ), - 'layout' => array( - ), - 'sig' => array( + ], + 'layout' => [ + ], + 'sig' => [ 'description' => Lang::$txt['signature_settings_desc'], - ), - 'profile' => array( + ], + 'profile' => [ 'description' => Lang::$txt['custom_profile_desc'], - ), - 'likes' => array( - ), - 'mentions' => array( - ), - 'alerts' => array( + ], + 'likes' => [ + ], + 'mentions' => [ + ], + 'alerts' => [ 'description' => Lang::$txt['notifications_desc'], - ), - ), - ); + ], + ], + ]; - IntegrationHook::call('integrate_modify_features', array(&self::$subactions)); + IntegrationHook::call('integrate_modify_features', [&self::$subactions]); - if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) + if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) { $this->subaction = $_REQUEST['sa']; + } } /** @@ -2099,12 +2065,14 @@ protected function pauseSignatureApplySettings(): void // Try get more time... @set_time_limit(600); - if (function_exists('apache_reset_timeout')) + if (function_exists('apache_reset_timeout')) { @apache_reset_timeout(); + } // Have we exhausted all the time we allowed? - if (time() - array_sum(explode(' ', Utils::$context['sig_start'])) < 3) + if (time() - array_sum(explode(' ', Utils::$context['sig_start'])) < 3) { return; + } Utils::$context['continue_get_data'] = '?action=admin;area=featuresettings;sa=sig;apply;step=' . $_GET['step'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['page_title'] = Lang::$txt['not_done_title']; @@ -2132,10 +2100,12 @@ protected function pauseSignatureApplySettings(): void protected function custFieldsMaxOrder(): int { // Gotta know the order limit - $result = Db::$db->query('', ' + $result = Db::$db->query( + '', + ' SELECT MAX(field_order) FROM {db_prefix}custom_fields', - array() + [], ); list($order_count) = Db::$db->fetch_row($result); @@ -2146,7 +2116,8 @@ protected function custFieldsMaxOrder(): int } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Features::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Features::exportStatic')) { Features::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Find.php b/Sources/Actions/Admin/Find.php index 93c7f50de0..e16cad0748 100644 --- a/Sources/Actions/Admin/Find.php +++ b/Sources/Actions/Admin/Find.php @@ -13,9 +13,8 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\BackwardCompatibility; use SMF\Config; use SMF\ErrorHandler; use SMF\IntegrationHook; @@ -37,11 +36,11 @@ class Find implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'AdminSearch', - ), - ); + ], + ]; /******************* * Public properties @@ -66,43 +65,43 @@ class Find implements ActionInterface * * Format: array('function_to_get_config_vars', 'url_for_admin_area_and_sa') */ - public array $settings_search = array( - array(__NAMESPACE__ . '\\Features::basicConfigVars', 'area=featuresettings;sa=basic'), - array(__NAMESPACE__ . '\\Features::bbcConfigVars', 'area=featuresettings;sa=bbc'), - array(__NAMESPACE__ . '\\Features::layoutConfigVars', 'area=featuresettings;sa=layout'), - array(__NAMESPACE__ . '\\Features::likesConfigVars', 'area=featuresettings;sa=likes'), - array(__NAMESPACE__ . '\\Features::mentionsConfigVars', 'area=featuresettings;sa=mentions'), - array(__NAMESPACE__ . '\\Features::sigConfigVars', 'area=featuresettings;sa=sig'), - array(__NAMESPACE__ . '\\AntiSpam::getConfigVars', 'area=antispam'), - array(__NAMESPACE__ . '\\Warnings::getConfigVars', 'area=warnings'), - array(__NAMESPACE__ . '\\Mods::getConfigVars', 'area=modsettings;sa=general'), - array(__NAMESPACE__ . '\\Attachments::attachConfigVars', 'area=manageattachments;sa=attachments'), - array(__NAMESPACE__ . '\\Attachments::avatarConfigVars', 'area=manageattachments;sa=avatars'), - array(__NAMESPACE__ . '\\Calendar::getConfigVars', 'area=managecalendar;sa=settings'), - array(__NAMESPACE__ . '\\Boards::getConfigVars', 'area=manageboards;sa=settings'), - array(__NAMESPACE__ . '\\Mail::getConfigVars', 'area=mailqueue;sa=settings'), - array(__NAMESPACE__ . '\\News::getConfigVars', 'area=news;sa=settings'), - array(__NAMESPACE__ . '\\Membergroups::getConfigVars', 'area=membergroups;sa=settings'), - array(__NAMESPACE__ . '\\Permissions::getConfigVars', 'area=permissions;sa=settings'), - array(__NAMESPACE__ . '\\Posts::postConfigVars', 'area=postsettings;sa=posts'), - array(__NAMESPACE__ . '\\Posts::topicConfigVars', 'area=postsettings;sa=topics'), - array(__NAMESPACE__ . '\\Posts::draftConfigVars', 'area=postsettings;sa=drafts'), - array(__NAMESPACE__ . '\\Search::getConfigVars', 'area=managesearch;sa=settings'), - array(__NAMESPACE__ . '\\Smileys::getConfigVars', 'area=smileys;sa=settings'), - array(__NAMESPACE__ . '\\Server::generalConfigVars', 'area=serversettings;sa=general'), - array(__NAMESPACE__ . '\\Server::databaseConfigVars', 'area=serversettings;sa=database'), - array(__NAMESPACE__ . '\\Server::cookieConfigVars', 'area=serversettings;sa=cookie'), - array(__NAMESPACE__ . '\\Server::securityConfigVars', 'area=serversettings;sa=security'), - array(__NAMESPACE__ . '\\Server::cacheConfigVars', 'area=serversettings;sa=cache'), - array(__NAMESPACE__ . '\\Server::exportConfigVars', 'area=serversettings;sa=export'), - array(__NAMESPACE__ . '\\Server::loadBalancingConfigVars', 'area=serversettings;sa=loads'), - array(__NAMESPACE__ . '\\Languages::getConfigVars', 'area=languages;sa=settings'), - array(__NAMESPACE__ . '\\Registration::getConfigVars', 'area=regcenter;sa=settings'), - array(__NAMESPACE__ . '\\SearchEngines::getConfigVars', 'area=sengines;sa=settings'), - array(__NAMESPACE__ . '\\Subscriptions::getConfigVars', 'area=paidsubscribe;sa=settings'), - array(__NAMESPACE__ . '\\Tasks::getConfigVars', 'area=scheduledtasks;sa=settings'), - array(__NAMESPACE__ . '\\Logs::getConfigVars', 'area=logs;sa=settings'), - ); + public array $settings_search = [ + [__NAMESPACE__ . '\\Features::basicConfigVars', 'area=featuresettings;sa=basic'], + [__NAMESPACE__ . '\\Features::bbcConfigVars', 'area=featuresettings;sa=bbc'], + [__NAMESPACE__ . '\\Features::layoutConfigVars', 'area=featuresettings;sa=layout'], + [__NAMESPACE__ . '\\Features::likesConfigVars', 'area=featuresettings;sa=likes'], + [__NAMESPACE__ . '\\Features::mentionsConfigVars', 'area=featuresettings;sa=mentions'], + [__NAMESPACE__ . '\\Features::sigConfigVars', 'area=featuresettings;sa=sig'], + [__NAMESPACE__ . '\\AntiSpam::getConfigVars', 'area=antispam'], + [__NAMESPACE__ . '\\Warnings::getConfigVars', 'area=warnings'], + [__NAMESPACE__ . '\\Mods::getConfigVars', 'area=modsettings;sa=general'], + [__NAMESPACE__ . '\\Attachments::attachConfigVars', 'area=manageattachments;sa=attachments'], + [__NAMESPACE__ . '\\Attachments::avatarConfigVars', 'area=manageattachments;sa=avatars'], + [__NAMESPACE__ . '\\Calendar::getConfigVars', 'area=managecalendar;sa=settings'], + [__NAMESPACE__ . '\\Boards::getConfigVars', 'area=manageboards;sa=settings'], + [__NAMESPACE__ . '\\Mail::getConfigVars', 'area=mailqueue;sa=settings'], + [__NAMESPACE__ . '\\News::getConfigVars', 'area=news;sa=settings'], + [__NAMESPACE__ . '\\Membergroups::getConfigVars', 'area=membergroups;sa=settings'], + [__NAMESPACE__ . '\\Permissions::getConfigVars', 'area=permissions;sa=settings'], + [__NAMESPACE__ . '\\Posts::postConfigVars', 'area=postsettings;sa=posts'], + [__NAMESPACE__ . '\\Posts::topicConfigVars', 'area=postsettings;sa=topics'], + [__NAMESPACE__ . '\\Posts::draftConfigVars', 'area=postsettings;sa=drafts'], + [__NAMESPACE__ . '\\Search::getConfigVars', 'area=managesearch;sa=settings'], + [__NAMESPACE__ . '\\Smileys::getConfigVars', 'area=smileys;sa=settings'], + [__NAMESPACE__ . '\\Server::generalConfigVars', 'area=serversettings;sa=general'], + [__NAMESPACE__ . '\\Server::databaseConfigVars', 'area=serversettings;sa=database'], + [__NAMESPACE__ . '\\Server::cookieConfigVars', 'area=serversettings;sa=cookie'], + [__NAMESPACE__ . '\\Server::securityConfigVars', 'area=serversettings;sa=security'], + [__NAMESPACE__ . '\\Server::cacheConfigVars', 'area=serversettings;sa=cache'], + [__NAMESPACE__ . '\\Server::exportConfigVars', 'area=serversettings;sa=export'], + [__NAMESPACE__ . '\\Server::loadBalancingConfigVars', 'area=serversettings;sa=loads'], + [__NAMESPACE__ . '\\Languages::getConfigVars', 'area=languages;sa=settings'], + [__NAMESPACE__ . '\\Registration::getConfigVars', 'area=regcenter;sa=settings'], + [__NAMESPACE__ . '\\SearchEngines::getConfigVars', 'area=sengines;sa=settings'], + [__NAMESPACE__ . '\\Subscriptions::getConfigVars', 'area=paidsubscribe;sa=settings'], + [__NAMESPACE__ . '\\Tasks::getConfigVars', 'area=scheduledtasks;sa=settings'], + [__NAMESPACE__ . '\\Logs::getConfigVars', 'area=logs;sa=settings'], + ]; /** * @var array @@ -112,7 +111,7 @@ class Find implements ActionInterface * MOD AUTHORS: If your mod uses it's own language file for its settings, * add the language file to this array via the integrate_admin_search hook. */ - public array $language_files = array( + public array $language_files = [ 'Drafts', 'Help', 'Login', @@ -124,7 +123,7 @@ class Find implements ActionInterface 'ManageSettings', 'ManageSmileys', 'Search', - ); + ]; /** * @var array @@ -135,7 +134,7 @@ class Find implements ActionInterface * worry about this array. Otherwise, you can add your file to this array * via the integrate_admin_search hook. */ - public array $include_files = array(); + public array $include_files = []; /************************** * Public static properties @@ -146,11 +145,11 @@ class Find implements ActionInterface * * Available sub-actions. */ - public static array $subactions = array( + public static array $subactions = [ 'internal' => 'internal', 'online' => 'online', 'member' => 'member', - ); + ]; /**************************** * Internal static properties @@ -182,24 +181,21 @@ public function execute(): void Utils::$context['page_title'] = Lang::$txt['admin_search_results']; // Keep track of what the admin wants. - if (empty(Utils::$context['admin_preferences']['sb']) || Utils::$context['admin_preferences']['sb'] != $this->subaction) - { + if (empty(Utils::$context['admin_preferences']['sb']) || Utils::$context['admin_preferences']['sb'] != $this->subaction) { Utils::$context['admin_preferences']['sb'] = $this->subaction; // Update the preferences. ACP::updateAdminPreferences(); } - if (trim(Utils::$context['search_term']) == '') - { - Utils::$context['search_results'] = array(); - } - else - { - $call = method_exists($this, self::$subactions[$this->subaction]) ? array($this, self::$subactions[$this->subaction]) : Utils::getCallable(self::$subactions[$this->subaction]); + if (trim(Utils::$context['search_term']) == '') { + Utils::$context['search_results'] = []; + } else { + $call = method_exists($this, self::$subactions[$this->subaction]) ? [$this, self::$subactions[$this->subaction]] : Utils::getCallable(self::$subactions[$this->subaction]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } } @@ -212,12 +208,13 @@ public function internal() // Try to get some more memory. Config::setMemoryLimit('128M'); - IntegrationHook::call('integrate_admin_search', array(&$this->language_files, &$this->include_files, &$this->settings_search)); + IntegrationHook::call('integrate_admin_search', [&$this->language_files, &$this->include_files, &$this->settings_search]); Lang::load(implode('+', $this->language_files)); - foreach ($this->include_files as $file) - require_once(Config::$sourcedir . '/' . $file . '.php'); + foreach ($this->include_files as $file) { + require_once Config::$sourcedir . '/' . $file . '.php'; + } /* This is the huge array that defines everything... it's a huge array of items formatted as follows: 0 = Language index (Can be array of indexes) to search through for this setting. @@ -225,67 +222,57 @@ public function internal() 2 = Help index for help associated with this item (If different from 0) */ - $search_data = array( + $search_data = [ // All the major sections of the forum. - 'sections' => array( - ), - 'settings' => array( - array('COPPA', 'area=regcenter;sa=settings'), - array('CAPTCHA', 'area=antispam'), - ), - ); + 'sections' => [ + ], + 'settings' => [ + ['COPPA', 'area=regcenter;sa=settings'], + ['CAPTCHA', 'area=antispam'], + ], + ]; // Go through the admin menu structure trying to find suitably named areas! - foreach (Menu::$loaded['admin']['sections'] as $section) - { - foreach ($section['areas'] as $menu_key => $menu_item) - { - $search_data['sections'][] = array($menu_item['label'], 'area=' . $menu_key); - - if (!empty($menu_item['subsections'])) - { - foreach ($menu_item['subsections'] as $key => $sublabel) - { - if (isset($sublabel['label'])) - { - $search_data['sections'][] = array($sublabel['label'], 'area=' . $menu_key . ';sa=' . $key); + foreach (Menu::$loaded['admin']['sections'] as $section) { + foreach ($section['areas'] as $menu_key => $menu_item) { + $search_data['sections'][] = [$menu_item['label'], 'area=' . $menu_key]; + + if (!empty($menu_item['subsections'])) { + foreach ($menu_item['subsections'] as $key => $sublabel) { + if (isset($sublabel['label'])) { + $search_data['sections'][] = [$sublabel['label'], 'area=' . $menu_key . ';sa=' . $key]; } } } } } - foreach ($this->settings_search as $setting_area) - { + foreach ($this->settings_search as $setting_area) { // Get a list of their variables. $config_vars = call_user_func($setting_area[0], true); - foreach ($config_vars as $var) - { - if (!empty($var[1]) && !in_array($var[0], array('permissions', 'switch', 'desc'))) - { - $search_data['settings'][] = array($var[(isset($var[2]) && in_array($var[2], array('file', 'db'))) ? 0 : 1], $setting_area[1], 'alttxt' => (isset($var[2]) && in_array($var[2], array('file', 'db'))) || isset($var[3]) ? (in_array($var[2], array('file', 'db')) ? $var[1] : $var[3]) : ''); + foreach ($config_vars as $var) { + if (!empty($var[1]) && !in_array($var[0], ['permissions', 'switch', 'desc'])) { + $search_data['settings'][] = [$var[(isset($var[2]) && in_array($var[2], ['file', 'db'])) ? 0 : 1], $setting_area[1], 'alttxt' => (isset($var[2]) && in_array($var[2], ['file', 'db'])) || isset($var[3]) ? (in_array($var[2], ['file', 'db']) ? $var[1] : $var[3]) : '']; } } } Utils::$context['page_title'] = Lang::$txt['admin_search_results']; - Utils::$context['search_results'] = array(); + Utils::$context['search_results'] = []; $search_term = strtolower(Utils::htmlspecialcharsDecode(Utils::$context['search_term'])); // Go through all the search data trying to find this text! - foreach ($search_data as $section => $data) - { - foreach ($data as $item) - { + foreach ($search_data as $section => $data) { + foreach ($data as $item) { $found = false; - if (!is_array($item[0])) - $item[0] = array($item[0]); + if (!is_array($item[0])) { + $item[0] = [$item[0]]; + } - foreach ($item[0] as $term) - { + foreach ($item[0] as $term) { if ( stripos($term, $search_term) !== false || ( @@ -296,26 +283,25 @@ public function internal() isset(Lang::$txt['setting_' . $term]) && stripos(Lang::$txt['setting_' . $term], $search_term) !== false ) - ) - { + ) { $found = $term; + break; } } - if ($found) - { + if ($found) { // Format the name - and remove any descriptions the entry may have. - $name = isset(Lang::$txt[$found]) ? Lang::$txt[$found] : (isset(Lang::$txt['setting_' . $found]) ? Lang::$txt['setting_' . $found] : (!empty($item['alttxt']) ? $item['alttxt'] : $found)); + $name = Lang::$txt[$found] ?? (Lang::$txt['setting_' . $found] ?? (!empty($item['alttxt']) ? $item['alttxt'] : $found)); - $name = preg_replace('~<(?:div|span)\sclass="smalltext">.+?~', '', $name); + $name = preg_replace('~<(?:div|span)\\sclass="smalltext">.+?~', '', $name); - Utils::$context['search_results'][] = array( + Utils::$context['search_results'][] = [ 'url' => (substr($item[1], 0, 4) == 'area' ? Config::$scripturl . '?action=admin;' . $item[1] : $item[1]) . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'] . ((substr($item[1], 0, 4) == 'area' && $section == 'settings' ? '#' . $item[0][0] : '')), 'name' => $name, 'type' => $section, 'help' => Utils::shorten(isset($item[2]) ? strip_tags(Lang::$helptxt[$item[2]]) : (isset(Lang::$helptxt[$found]) ? strip_tags(Lang::$helptxt[$found]) : ''), 255), - ); + ]; } } } @@ -347,8 +333,9 @@ public function online() $postVars = explode(' ', Utils::$context['search_term']); // Encode the search data. - foreach ($postVars as $k => $v) + foreach ($postVars as $k => $v) { $postVars[$k] = urlencode($v); + } // This is what we will send. $postVars = implode('+', $postVars); @@ -359,32 +346,33 @@ public function online() $search_results = WebFetchApi::fetch(Utils::$context['doc_apiurl'] . '?action=query&list=search&srprop=timestamp|snippet&format=xml&srwhat=text&srsearch=' . $postVars); // If we didn't get any xml back we are in trouble - perhaps the doc site is overloaded? - if (!$search_results || preg_match('~<' . '\?xml\sversion="\d+\.\d+"\?' . '>\s*(]*>.+?)~is', $search_results, $matches) != true) + if (!$search_results || preg_match('~<' . '\\?xml\\sversion="\\d+\\.\\d+"\\?' . '>\\s*(]*>.+?)~is', $search_results, $matches) != true) { ErrorHandler::fatalLang('cannot_connect_doc_site'); + } $search_results = $matches[1]; // Otherwise we simply walk through the XML and stick it in context for display. - Utils::$context['search_results'] = array(); + Utils::$context['search_results'] = []; // Get the results loaded into an array for processing! $results = new XmlArray($search_results, false); // Move through the api layer. - if (!$results->exists('api')) + if (!$results->exists('api')) { ErrorHandler::fatalLang('cannot_connect_doc_site'); + } // Are there actually some results? - if ($results->exists('api/query/search/p')) - { + if ($results->exists('api/query/search/p')) { $relevance = 0; - foreach ($results->set('api/query/search/p') as $result) - { - Utils::$context['search_results'][$result->fetch('@title')] = array( + + foreach ($results->set('api/query/search/p') as $result) { + Utils::$context['search_results'][$result->fetch('@title')] = [ 'title' => $result->fetch('@title'), 'relevance' => $relevance++, 'snippet' => str_replace('class=\'searchmatch\'', 'class="highlight"', Utils::htmlspecialcharsDecode($result->fetch('@snippet'))), - ); + ]; } } } @@ -400,8 +388,9 @@ public function online() */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -428,7 +417,8 @@ protected function __construct() } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Find::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Find::exportStatic')) { Find::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Home.php b/Sources/Actions/Admin/Home.php index e2abbd036c..64c0f088e3 100644 --- a/Sources/Actions/Admin/Home.php +++ b/Sources/Actions/Admin/Home.php @@ -13,17 +13,16 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\Actions\Credits; +use SMF\Actions\Groups; +use SMF\BackwardCompatibility; use SMF\Config; use SMF\Lang; use SMF\Menu; use SMF\Theme; use SMF\User; use SMF\Utils; -use SMF\Actions\Credits; -use SMF\Actions\Groups; /** * The administration home page. @@ -42,11 +41,11 @@ class Home implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'AdminHome', - ), - ); + ], + ]; /******************* * Public properties @@ -57,7 +56,7 @@ class Home implements ActionInterface * * You have to be able to do at least one of these to see this page. */ - public array $permissions = array( + public array $permissions = [ 'admin_forum', 'edit_news', 'manage_attachments', @@ -68,14 +67,14 @@ class Home implements ActionInterface 'manage_smileys', 'moderate_forum', 'send_mail', - ); + ]; /** * @var array * * Server software to check the versions of. */ - public array $checkFor = array( + public array $checkFor = [ 'gd', 'imagemagick', 'db_server', @@ -88,7 +87,7 @@ class Home implements ActionInterface 'filebased', 'php', 'server', - ); + ]; /**************************** * Internal static properties @@ -114,8 +113,7 @@ public function execute(): void User::$me->isAllowedTo($this->permissions); // Find all of this forum's administrators... - if (Groups::listMembergroupMembers_Href(Utils::$context['administrators'], 1, 32) && User::$me->allowedTo('manage_membergroups')) - { + if (Groups::listMembergroupMembers_Href(Utils::$context['administrators'], 1, 32) && User::$me->allowedTo('manage_membergroups')) { // Add a 'more'-link if there are more than 32. Utils::$context['more_admins_link'] = '' . Lang::$txt['more'] . ''; } @@ -136,36 +134,36 @@ public function execute(): void Utils::$context['page_title'] = Utils::$context['admin_area'] == 'credits' ? Lang::$txt['support_credits_title'] : Lang::$txt['admin_center']; - if (Utils::$context['admin_area'] != 'credits') - { - Menu::$loaded['admin']->tab_data = array( + if (Utils::$context['admin_area'] != 'credits') { + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['admin_center'], 'help' => '', 'description' => '' . Lang::$txt['hello_guest'] . ' ' . User::$me->name . '! ' . sprintf(Lang::$txt['admin_main_welcome'], Lang::$txt['admin_center'], Lang::$txt['help'], Lang::$txt['help']), - ); + ]; } // Lastly, fill in the blanks in the support resources paragraphs. - Lang::$txt['support_resources_p1'] = sprintf(Lang::$txt['support_resources_p1'], + Lang::$txt['support_resources_p1'] = sprintf( + Lang::$txt['support_resources_p1'], 'https://wiki.simplemachines.org/', 'https://wiki.simplemachines.org/smf/features2', 'https://wiki.simplemachines.org/smf/options2', 'https://wiki.simplemachines.org/smf/themes2', - 'https://wiki.simplemachines.org/smf/packages2' + 'https://wiki.simplemachines.org/smf/packages2', ); - Lang::$txt['support_resources_p2'] = sprintf(Lang::$txt['support_resources_p2'], + Lang::$txt['support_resources_p2'] = sprintf( + Lang::$txt['support_resources_p2'], 'https://www.simplemachines.org/community/', 'https://www.simplemachines.org/redirect/english_support', 'https://www.simplemachines.org/redirect/international_support_boards', 'https://www.simplemachines.org/redirect/smf_support', - 'https://www.simplemachines.org/redirect/customize_support' + 'https://www.simplemachines.org/redirect/customize_support', ); - if (Utils::$context['admin_area'] == 'admin') - { - Theme::loadJavaScriptFile('admin.js', array('defer' => false, 'minimize' => true), 'smf_admin'); + if (Utils::$context['admin_area'] == 'admin') { + Theme::loadJavaScriptFile('admin.js', ['defer' => false, 'minimize' => true], 'smf_admin'); } } @@ -180,8 +178,9 @@ public function execute(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -207,7 +206,8 @@ protected function __construct() } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Home::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Home::exportStatic')) { Home::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Languages.php b/Sources/Actions/Admin/Languages.php index 656fbd2c6f..553bb9232b 100644 --- a/Sources/Actions/Admin/Languages.php +++ b/Sources/Actions/Admin/Languages.php @@ -13,23 +13,22 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\BackwardCompatibility; +use SMF\Cache\CacheApi; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\ErrorHandler; use SMF\IntegrationHook; use SMF\ItemList; use SMF\Lang; use SMF\Menu; +use SMF\PackageManager\SubsPackage; +use SMF\PackageManager\XmlArray; use SMF\SecurityToken; use SMF\Theme; use SMF\User; use SMF\Utils; -use SMF\Cache\CacheApi; -use SMF\Db\DatabaseApi as Db; -use SMF\PackageManager\SubsPackage; -use SMF\PackageManager\XmlArray; use SMF\WebFetch\WebFetchApi; /** @@ -44,8 +43,8 @@ class Languages implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'ManageLanguages', 'list_getLanguagesList' => 'list_getLanguagesList', 'list_getNumLanguages' => 'list_getNumLanguages', @@ -55,8 +54,8 @@ class Languages implements ActionInterface 'modifyLanguageSettings' => 'ModifyLanguageSettings', 'downloadLanguage' => 'DownloadLanguage', 'modifyLanguage' => 'ModifyLanguage', - ), - ); + ], + ]; /******************* * Public properties @@ -79,13 +78,13 @@ class Languages implements ActionInterface * * Available sub-actions. */ - public static array $subactions = array( + public static array $subactions = [ 'edit' => 'editLanguages', 'add' => 'add', 'settings' => 'settings', 'downloadlang' => 'download', 'editlang' => 'editEntries', - ); + ]; /**************************** * Internal static properties @@ -108,10 +107,11 @@ class Languages implements ActionInterface */ public function execute(): void { - $call = method_exists($this, self::$subactions[$this->subaction]) ? array($this, self::$subactions[$this->subaction]) : Utils::getCallable(self::$subactions[$this->subaction]); + $call = method_exists($this, self::$subactions[$this->subaction]) ? [$this, self::$subactions[$this->subaction]] : Utils::getCallable(self::$subactions[$this->subaction]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } /** @@ -122,60 +122,59 @@ public function execute(): void public function add(): void { // Are we searching for new languages courtesy of Simple Machines? - if (!empty($_POST['smf_add_sub'])) - { + if (!empty($_POST['smf_add_sub'])) { Utils::$context['smf_search_term'] = Utils::htmlspecialchars(trim($_POST['smf_add'])); - $listOptions = array( + $listOptions = [ 'id' => 'smf_languages', - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getLanguagesList', - ), - 'columns' => array( - 'name' => array( - 'header' => array( + ], + 'columns' => [ + 'name' => [ + 'header' => [ 'value' => Lang::$txt['name'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'name', - ), - ), - 'description' => array( - 'header' => array( + ], + ], + 'description' => [ + 'header' => [ 'value' => Lang::$txt['add_language_smf_desc'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'description', - ), - ), - 'version' => array( - 'header' => array( + ], + ], + 'version' => [ + 'header' => [ 'value' => Lang::$txt['add_language_smf_version'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'version', - ), - ), - 'utf8' => array( - 'header' => array( + ], + ], + 'utf8' => [ + 'header' => [ 'value' => Lang::$txt['add_language_smf_utf8'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'utf8', - ), - ), - 'install_link' => array( - 'header' => array( + ], + ], + 'install_link' => [ + 'header' => [ 'value' => Lang::$txt['add_language_smf_install'], 'class' => 'centercol', - ), - 'data' => array( + ], + 'data' => [ 'db' => 'install_link', 'class' => 'centercol', - ), - ), - ), - ); + ], + ], + ], + ]; new ItemList($listOptions); @@ -200,8 +199,9 @@ public function download(): void Lang::load('ManageSettings'); // Clearly we need to know what to request. - if (!isset($_GET['did'])) + if (!isset($_GET['did'])) { ErrorHandler::fatalLang('no_access', false); + } // Some lovely context. Utils::$context['download_id'] = $_GET['did']; @@ -209,20 +209,17 @@ public function download(): void Utils::$context['menu_data_' . Utils::$context['admin_menu_id']]['current_subsection'] = 'add'; // Can we actually do the installation - and do they want to? - if (!empty($_POST['do_install']) && !empty($_POST['copy_file'])) - { + if (!empty($_POST['do_install']) && !empty($_POST['copy_file'])) { User::$me->checkSession('get'); SecurityToken::validate('admin-dlang'); - $chmod_files = array(); - $install_files = array(); + $chmod_files = []; + $install_files = []; // Check writable status. - foreach ($_POST['copy_file'] as $file) - { + foreach ($_POST['copy_file'] as $file) { // Check it's not very bad. - if (strpos($file, '..') !== false || (strpos($file, 'Themes') !== 0 && !preg_match('~agreement\.[A-Za-z-_0-9]+\.txt$~', $file))) - { + if (strpos($file, '..') !== false || (strpos($file, 'Themes') !== 0 && !preg_match('~agreement\\.[A-Za-z-_0-9]+\\.txt$~', $file))) { ErrorHandler::fatal(Lang::$txt['languages_download_illegal_paths']); } @@ -235,13 +232,11 @@ public function download(): void $files_left = $file_status['files']['notwritable']; // Something not writable? - if (!empty($files_left)) - { + if (!empty($files_left)) { Utils::$context['error_message'] = Lang::$txt['languages_download_not_chmod']; } // Otherwise, go go go! - elseif (!empty($install_files)) - { + elseif (!empty($install_files)) { SubsPackage::read_tgz_file('https://download.simplemachines.org/fetch_language.php?version=' . urlencode(SMF_VERSION) . ';fetch=' . urlencode($_GET['did']), Config::$boarddir, false, true, $install_files); // Make sure the files aren't stuck in the cache. @@ -254,35 +249,35 @@ public function download(): void } // Open up the old china. - if (!isset($archive_content)) - { + if (!isset($archive_content)) { $archive_content = SubsPackage::read_tgz_file('https://download.simplemachines.org/fetch_language.php?version=' . urlencode(SMF_VERSION) . ';fetch=' . urlencode($_GET['did']), null); } - if (empty($archive_content)) + if (empty($archive_content)) { ErrorHandler::fatal(Lang::$txt['add_language_error_no_response']); + } // Now for each of the files, let's do some *stuff* - Utils::$context['files'] = array( - 'lang' => array(), - 'other' => array(), - ); + Utils::$context['files'] = [ + 'lang' => [], + 'other' => [], + ]; - Utils::$context['make_writable'] = array(); + Utils::$context['make_writable'] = []; - foreach ($archive_content as $file) - { + foreach ($archive_content as $file) { $pathinfo = pathinfo($file['filename']); $dirname = $pathinfo['dirname']; $basename = $pathinfo['basename']; $extension = $pathinfo['extension']; // Don't do anything with files we don't understand. - if (!in_array($extension, array('php', 'jpg', 'gif', 'jpeg', 'png', 'txt'))) + if (!in_array($extension, ['php', 'jpg', 'gif', 'jpeg', 'png', 'txt'])) { continue; + } // Basic data. - $context_data = array( + $context_data = [ 'name' => $basename, 'destination' => Config::$boarddir . '/' . $file['filename'], 'generaldest' => $file['filename'], @@ -293,209 +288,186 @@ public function download(): void 'default_copy' => true, // Does the file already exist, if so is it same or different? 'exists' => false, - ); + ]; // Does the file exist, is it different and can we overwrite? - if (file_exists(Config::$boarddir . '/' . $file['filename'])) - { - if (is_writable(Config::$boarddir . '/' . $file['filename'])) + if (file_exists(Config::$boarddir . '/' . $file['filename'])) { + if (is_writable(Config::$boarddir . '/' . $file['filename'])) { $context_data['writable'] = true; + } // Finally, do we actually think the content has changed? - if ($file['size'] == filesize(Config::$boarddir . '/' . $file['filename']) && $file['md5'] == md5_file(Config::$boarddir . '/' . $file['filename'])) - { + if ($file['size'] == filesize(Config::$boarddir . '/' . $file['filename']) && $file['md5'] == md5_file(Config::$boarddir . '/' . $file['filename'])) { $context_data['exists'] = 'same'; $context_data['default_copy'] = false; } // Attempt to discover newline character differences. - elseif ($file['md5'] == md5(preg_replace("~[\r]?\n~", "\r\n", file_get_contents(Config::$boarddir . '/' . $file['filename'])))) - { + elseif ($file['md5'] == md5(preg_replace("~[\r]?\n~", "\r\n", file_get_contents(Config::$boarddir . '/' . $file['filename'])))) { $context_data['exists'] = 'same'; $context_data['default_copy'] = false; - } - else - { + } else { $context_data['exists'] = 'different'; } } // No overwrite? - else - { + else { // Can we at least stick it in the directory... - if (is_writable(Config::$boarddir . '/' . $dirname)) + if (is_writable(Config::$boarddir . '/' . $dirname)) { $context_data['writable'] = true; + } } // I love PHP files, that's why I'm a developer and not an artistic type spending my time drinking absinth and living a life of sin... - if ($extension == 'php' && preg_match('~\w+\.\w+(?:-utf8)?\.php~', $basename)) - { - $context_data += array( + if ($extension == 'php' && preg_match('~\\w+\\.\\w+(?:-utf8)?\\.php~', $basename)) { + $context_data += [ 'version' => '??', 'cur_version' => false, 'version_compare' => 'newer', - ); + ]; - list ($name, $language) = explode('.', $basename); + list($name, $language) = explode('.', $basename); // Let's get the new version, I like versions, they tell me that I'm up to date. - if (preg_match('~\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '~i', $file['preview'], $match) == 1) - { + if (preg_match('~\\s*Version:\\s+(.+?);\\s*' . preg_quote($name, '~') . '~i', $file['preview'], $match) == 1) { $context_data['version'] = $match[1]; } // Now does the old file exist - if so what is it's version? - if (file_exists(Config::$boarddir . '/' . $file['filename'])) - { + if (file_exists(Config::$boarddir . '/' . $file['filename'])) { // OK - what is the current version? $fp = fopen(Config::$boarddir . '/' . $file['filename'], 'rb'); $header = fread($fp, 768); fclose($fp); // Find the version. - if (preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '(?:[\s]{2}|\*/)~i', $header, $match) == 1) - { + if (preg_match('~(?://|/\\*)\\s*Version:\\s+(.+?);\\s*' . preg_quote($name, '~') . '(?:[\\s]{2}|\\*/)~i', $header, $match) == 1) { $context_data['cur_version'] = $match[1]; // How does this compare? - if ($context_data['cur_version'] == $context_data['version']) - { + if ($context_data['cur_version'] == $context_data['version']) { $context_data['version_compare'] = 'same'; - } - elseif ($context_data['cur_version'] > $context_data['version']) - { + } elseif ($context_data['cur_version'] > $context_data['version']) { $context_data['version_compare'] = 'older'; } // Don't recommend copying if the version is the same. - if ($context_data['version_compare'] != 'newer') + if ($context_data['version_compare'] != 'newer') { $context_data['default_copy'] = false; + } } } // Add the context data to the main set. Utils::$context['files']['lang'][] = $context_data; - } - elseif ($extension == 'txt' && stripos($basename, 'agreement') !== false) - { - $context_data += array( + } elseif ($extension == 'txt' && stripos($basename, 'agreement') !== false) { + $context_data += [ 'version' => '??', 'cur_version' => false, 'version_compare' => 'newer', - ); + ]; // Registration agreement is a primary file Utils::$context['files']['lang'][] = $context_data; - } - else - { + } else { // There shouldn't be anything else, but load this into "other" in case we decide to handle it in the future Utils::$context['files']['other'][] = $context_data; } // Collect together all non-writable areas. - if (!$context_data['writable']) + if (!$context_data['writable']) { Utils::$context['make_writable'][] = $context_data['destination']; + } } // Before we go to far can we make anything writable, eh, eh? - if (!empty(Utils::$context['make_writable'])) - { + if (!empty(Utils::$context['make_writable'])) { // What is left to be made writable? $file_status = SubsPackage::create_chmod_control(Utils::$context['make_writable']); Utils::$context['still_not_writable'] = $file_status['files']['notwritable']; // Mark those which are now writable as such. - foreach (Utils::$context['files'] as $type => $data) - { - foreach ($data as $k => $file) - { - if (!$file['writable'] && !in_array($file['destination'], Utils::$context['still_not_writable'])) - { + foreach (Utils::$context['files'] as $type => $data) { + foreach ($data as $k => $file) { + if (!$file['writable'] && !in_array($file['destination'], Utils::$context['still_not_writable'])) { Utils::$context['files'][$type][$k]['writable'] = true; } } } // Are we going to need more language stuff? - if (!empty(Utils::$context['still_not_writable'])) + if (!empty(Utils::$context['still_not_writable'])) { Lang::load('Packages'); + } } // This is the list for the main files. - $listOptions = array( + $listOptions = [ 'id' => 'lang_main_files_list', 'title' => Lang::$txt['languages_download_main_files'], - 'get_items' => array( - 'function' => function() - { + 'get_items' => [ + 'function' => function () { return Utils::$context['files']['lang']; }, - ), - 'columns' => array( - 'name' => array( - 'header' => array( + ], + 'columns' => [ + 'name' => [ + 'header' => [ 'value' => Lang::$txt['languages_download_filename'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return '' . $rowData['name'] . '
' . Lang::$txt['languages_download_dest'] . ': ' . $rowData['destination'] . '' . ($rowData['version_compare'] == 'older' ? '
' . Lang::$txt['languages_download_older'] : ''); }, - ), - ), - 'writable' => array( - 'header' => array( + ], + ], + 'writable' => [ + 'header' => [ 'value' => Lang::$txt['languages_download_writable'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return '' . ($rowData['writable'] ? Lang::$txt['yes'] : Lang::$txt['no']) . ''; }, - ), - ), - 'version' => array( - 'header' => array( + ], + ], + 'version' => [ + 'header' => [ 'value' => Lang::$txt['languages_download_version'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return '' . $rowData['version'] . ''; }, - ), - ), - 'exists' => array( - 'header' => array( + ], + ], + 'exists' => [ + 'header' => [ 'value' => Lang::$txt['languages_download_exists'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return $rowData['exists'] ? ($rowData['exists'] == 'same' ? Lang::$txt['languages_download_exists_same'] : Lang::$txt['languages_download_exists_different']) : Lang::$txt['no']; }, - ), - ), - 'copy' => array( - 'header' => array( + ], + ], + 'copy' => [ + 'header' => [ 'value' => Lang::$txt['languages_download_overwrite'], 'class' => 'centercol', - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return ''; }, 'style' => 'width: 4%;', 'class' => 'centercol', - ), - ), - ), - ); + ], + ], + ], + ]; // Kill the cache, as it is now invalid.. - if (!empty(CacheApi::$enable)) - { + if (!empty(CacheApi::$enable)) { CacheApi::put('known_languages', null, !empty(CacheApi::$enable) && CacheApi::$enable < 1 ? 86400 : 3600); CacheApi::put('known_languages_all', null, !empty(CacheApi::$enable) && CacheApi::$enable < 1 ? 86400 : 3600); } @@ -512,26 +484,23 @@ public function download(): void public function editLanguages() { // Setting a new default? - if (!empty($_POST['set_default']) && !empty($_POST['def_language'])) - { + if (!empty($_POST['set_default']) && !empty($_POST['def_language'])) { User::$me->checkSession(); SecurityToken::validate('admin-lang'); Lang::get(); $lang_exists = false; - foreach (Utils::$context['languages'] as $lang) - { - if ($_POST['def_language'] == $lang['filename']) - { + foreach (Utils::$context['languages'] as $lang) { + if ($_POST['def_language'] == $lang['filename']) { $lang_exists = true; + break; } } - if ($_POST['def_language'] != Lang::$default && $lang_exists) - { - Config::updateSettingsFile(array('language' => $_POST['def_language'])); + if ($_POST['def_language'] != Lang::$default && $lang_exists) { + Config::updateSettingsFile(['language' => $_POST['def_language']]); Lang::$default = $_POST['def_language']; } } @@ -539,96 +508,93 @@ public function editLanguages() // Create another one time token here. SecurityToken::create('admin-lang'); - $listOptions = array( + $listOptions = [ 'id' => 'language_list', 'items_per_page' => Config::$modSettings['defaultMaxListItems'], 'base_href' => Config::$scripturl . '?action=admin;area=languages', 'title' => Lang::$txt['edit_languages'], - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getLanguages', - ), - 'get_count' => array( + ], + 'get_count' => [ 'function' => __CLASS__ . '::list_getNumLanguages', - ), - 'columns' => array( - 'default' => array( - 'header' => array( + ], + 'columns' => [ + 'default' => [ + 'header' => [ 'value' => Lang::$txt['languages_default'], 'class' => 'centercol', - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return ''; }, 'style' => 'width: 8%;', 'class' => 'centercol', - ), - ), - 'name' => array( - 'header' => array( + ], + ], + 'name' => [ + 'header' => [ 'value' => Lang::$txt['languages_lang_name'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return sprintf('%3$s', Config::$scripturl, $rowData['id'], $rowData['name']); }, 'class' => 'centercol', - ), - ), - 'character_set' => array( - 'header' => array( + ], + ], + 'character_set' => [ + 'header' => [ 'value' => Lang::$txt['languages_character_set'], - ), - 'data' => array( + ], + 'data' => [ 'db_htmlsafe' => 'char_set', 'class' => 'centercol', - ), - ), - 'count' => array( - 'header' => array( + ], + ], + 'count' => [ + 'header' => [ 'value' => Lang::$txt['languages_users'], - ), - 'data' => array( + ], + 'data' => [ 'db_htmlsafe' => 'count', 'class' => 'centercol', - ), - ), - 'locale' => array( - 'header' => array( + ], + ], + 'locale' => [ + 'header' => [ 'value' => Lang::$txt['languages_locale'], - ), - 'data' => array( + ], + 'data' => [ 'db_htmlsafe' => 'locale', 'class' => 'centercol', - ), - ), - 'editlang' => array( - 'header' => array( + ], + ], + 'editlang' => [ + 'header' => [ 'value' => '', - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return sprintf('%3$s', Config::$scripturl, $rowData['id'], Lang::$txt['edit']); }, 'style' => 'width: 8%;', 'class' => 'centercol', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=languages', 'token' => 'admin-lang', - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'bottom_of_list', 'value' => '', - ), - ), - ); + ], + ], + ]; // We want to highlight the selected language. Need some Javascript for this. Theme::addInlineJavaScript(' @@ -640,13 +606,12 @@ function highlightSelected(box) highlightSelected("list_language_list_' . (Lang::$default == '' ? 'english' : Lang::$default) . '");', true); // Display a warning if we cannot edit the default setting. - if (!is_writable(SMF_SETTINGS_FILE)) - { - $listOptions['additional_rows'][] = array( + if (!is_writable(SMF_SETTINGS_FILE)) { + $listOptions['additional_rows'][] = [ 'position' => 'after_title', 'value' => Lang::$txt['language_settings_writable'], 'class' => 'smalltext alert', - ); + ]; } new ItemList($listOptions); @@ -668,25 +633,24 @@ public function settings($return_config = false) // Get our languages. No cache. Lang::get(false); - foreach (Utils::$context['languages'] as $lang) - { - $config_vars['language'][4][$lang['filename']] = array($lang['filename'], $lang['name']); + foreach (Utils::$context['languages'] as $lang) { + $config_vars['language'][4][$lang['filename']] = [$lang['filename'], $lang['name']]; } // Warn the user if Settings.php is not writable or cannot be backed up. $safe = Server::checkSettingsFileWriteSafe(); // Saving settings? - if (isset($_REQUEST['save'])) - { + if (isset($_REQUEST['save'])) { User::$me->checkSession(); - IntegrationHook::call('integrate_save_language_settings', array(&$config_vars)); + IntegrationHook::call('integrate_save_language_settings', [&$config_vars]); ACP::saveSettings($config_vars); - if ($safe) + if ($safe) { $_SESSION['adm-save'] = true; + } Utils::redirectexit('action=admin;area=languages;sa=settings'); } @@ -696,21 +660,18 @@ public function settings($return_config = false) Utils::$context['settings_title'] = Lang::$txt['language_settings']; Utils::$context['save_disabled'] = Server::$settings_not_writable; - if (Server::$settings_not_writable) - { - Utils::$context['settings_message'] = array( + if (Server::$settings_not_writable) { + Utils::$context['settings_message'] = [ 'label' => Lang::$txt['settings_not_writable'], 'tag' => 'div', - 'class' => 'centertext strong' - ); - } - elseif (Server::$settings_backup_fail) - { - Utils::$context['settings_message'] = array( + 'class' => 'centertext strong', + ]; + } elseif (Server::$settings_backup_fail) { + Utils::$context['settings_message'] = [ 'label' => Lang::$txt['admin_backup_fail'], 'tag' => 'div', - 'class' => 'centertext strong' - ); + 'class' => 'centertext strong', + ]; } // Fill the config array. @@ -730,7 +691,7 @@ public function editEntries() Utils::$context['sub_template'] = 'modify_language_entries'; $lang_id = $_GET['lid']; - list($theme_id, $file_id) = empty($_REQUEST['tfid']) || strpos($_REQUEST['tfid'], '+') === false ? array(1, '') : explode('+', $_REQUEST['tfid']); + list($theme_id, $file_id) = empty($_REQUEST['tfid']) || strpos($_REQUEST['tfid'], '+') === false ? [1, ''] : explode('+', $_REQUEST['tfid']); // Clean the ID - just in case. preg_match('~([A-Za-z0-9_-]+)~', $lang_id, $matches); @@ -739,74 +700,71 @@ public function editEntries() Utils::$context['lang_id'] = &$lang_id; // Get all the theme data. - $themes = array( - 1 => array( + $themes = [ + 1 => [ 'name' => Lang::$txt['dvc_default'], 'theme_dir' => Theme::$current->settings['default_theme_dir'], - ), - ); + ], + ]; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_theme, variable, value FROM {db_prefix}themes WHERE id_theme != {int:default_theme} AND id_member = {int:no_member} AND variable IN ({string:name}, {string:theme_dir})', - array( + [ 'default_theme' => 1, 'no_member' => 0, 'name' => 'name', 'theme_dir' => 'theme_dir', - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { $themes[$row['id_theme']][$row['variable']] = $row['value']; } Db::$db->free_result($request); // This will be where we look - $lang_dirs = array(); + $lang_dirs = []; // There are different kinds of strings - $string_types = array('txt', 'helptxt', 'editortxt', 'tztxt', 'txtBirthdayEmails'); - $additional_string_types = array(); + $string_types = ['txt', 'helptxt', 'editortxt', 'tztxt', 'txtBirthdayEmails']; + $additional_string_types = []; // Some files allow the admin to add and/or remove certain types of strings - $allows_add_remove = array( - 'Timezones' => array( - 'add' => array('tztxt', 'txt'), - 'remove' => array('tztxt', 'txt'), - ), - 'Modifications' => array( - 'add' => array('txt'), - 'remove' => array('txt'), - ), - 'ThemeStrings' => array( - 'add' => array('txt'), - ), - ); + $allows_add_remove = [ + 'Timezones' => [ + 'add' => ['tztxt', 'txt'], + 'remove' => ['tztxt', 'txt'], + ], + 'Modifications' => [ + 'add' => ['txt'], + 'remove' => ['txt'], + ], + 'ThemeStrings' => [ + 'add' => ['txt'], + ], + ]; // Does a hook need to add in some additional places to look for languages or info about how to handle them? - IntegrationHook::call('integrate_modifylanguages', array(&$themes, &$lang_dirs, &$allows_add_remove, &$additional_string_types)); + IntegrationHook::call('integrate_modifylanguages', [&$themes, &$lang_dirs, &$allows_add_remove, &$additional_string_types]); $string_types = array_unique(array_merge($string_types, $additional_string_types)); // Check we have themes with a path and a name - just in case - and add the path. - foreach ($themes as $id => $data) - { - if (count($data) != 2) - { + foreach ($themes as $id => $data) { + if (count($data) != 2) { unset($themes[$id]); - } - elseif (is_dir($data['theme_dir'] . '/languages')) - { + } elseif (is_dir($data['theme_dir'] . '/languages')) { $lang_dirs[$id] = $data['theme_dir'] . '/languages'; } // How about image directories? - if (is_dir($data['theme_dir'] . '/images/' . $lang_id)) - { + if (is_dir($data['theme_dir'] . '/images/' . $lang_id)) { $images_dirs[$id] = $data['theme_dir'] . '/images/' . $lang_id; } } @@ -814,115 +772,110 @@ public function editEntries() $current_file = $file_id ? $lang_dirs[$theme_id] . '/' . $file_id . '.' . $lang_id . '.php' : ''; // Now for every theme get all the files and stick them in context! - Utils::$context['possible_files'] = array(); + Utils::$context['possible_files'] = []; - foreach ($lang_dirs as $theme => $theme_dir) - { + foreach ($lang_dirs as $theme => $theme_dir) { // Open it up. $dir = dir($theme_dir); - while ($entry = $dir->read()) - { + while ($entry = $dir->read()) { // We're only after the files for this language. - if (!preg_match('~^([A-Za-z]+)\.' . $lang_id . '\.php$~', $entry, $matches)) + if (!preg_match('~^([A-Za-z]+)\\.' . $lang_id . '\\.php$~', $entry, $matches)) { continue; + } - if (!isset(Utils::$context['possible_files'][$theme])) - { - Utils::$context['possible_files'][$theme] = array( + if (!isset(Utils::$context['possible_files'][$theme])) { + Utils::$context['possible_files'][$theme] = [ 'id' => $theme, 'name' => $themes[$theme]['name'], - 'files' => array(), - ); + 'files' => [], + ]; } - Utils::$context['possible_files'][$theme]['files'][] = array( + Utils::$context['possible_files'][$theme]['files'][] = [ 'id' => $matches[1], - 'name' => isset(Lang::$txt['lang_file_desc_' . $matches[1]]) ? Lang::$txt['lang_file_desc_' . $matches[1]] : $matches[1], + 'name' => Lang::$txt['lang_file_desc_' . $matches[1]] ?? $matches[1], 'selected' => $theme_id == $theme && $file_id == $matches[1], - ); + ]; } $dir->close(); - if (!empty(Utils::$context['possible_files'][$theme]['files'])) - { + if (!empty(Utils::$context['possible_files'][$theme]['files'])) { usort( Utils::$context['possible_files'][$theme]['files'], - function($val1, $val2) - { + function ($val1, $val2) { return strcmp($val1['name'], $val2['name']); - } + }, ); } } // We no longer wish to speak this language. - if (!empty($_POST['delete_main']) && $lang_id != 'english') - { + if (!empty($_POST['delete_main']) && $lang_id != 'english') { User::$me->checkSession(); SecurityToken::validate('admin-mlang'); // First, Make a backup? - if (!empty(Config::$modSettings['package_make_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $lang_id . '$$$')) - { + if (!empty(Config::$modSettings['package_make_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $lang_id . '$$$')) { $_SESSION['last_backup_for'] = $lang_id . '$$$'; $result = SubsPackage::package_create_backup('backup_lang_' . $lang_id); - if (!$result) + if (!$result) { ErrorHandler::fatalLang('could_not_language_backup', false); + } } // Second, loop through the array to remove the files. - foreach ($lang_dirs as $curPath) - { - foreach (Utils::$context['possible_files'][1]['files'] as $lang) - { - if (file_exists($curPath . '/' . $lang['id'] . '.' . $lang_id . '.php')) + foreach ($lang_dirs as $curPath) { + foreach (Utils::$context['possible_files'][1]['files'] as $lang) { + if (file_exists($curPath . '/' . $lang['id'] . '.' . $lang_id . '.php')) { unlink($curPath . '/' . $lang['id'] . '.' . $lang_id . '.php'); + } } // Check for the email template. - if (file_exists($curPath . '/EmailTemplates.' . $lang_id . '.php')) + if (file_exists($curPath . '/EmailTemplates.' . $lang_id . '.php')) { unlink($curPath . '/EmailTemplates.' . $lang_id . '.php'); + } } // Third, the agreement file. - if (file_exists(Config::$boarddir . '/agreement.' . $lang_id . '.txt')) + if (file_exists(Config::$boarddir . '/agreement.' . $lang_id . '.txt')) { unlink(Config::$boarddir . '/agreement.' . $lang_id . '.txt'); + } // Fourth, a related images folder, if it exists... - if (!empty($images_dirs)) - { - foreach ($images_dirs as $curPath) - { - if (is_dir($curPath)) + if (!empty($images_dirs)) { + foreach ($images_dirs as $curPath) { + if (is_dir($curPath)) { SubsPackage::deltree($curPath); + } } } // Members can no longer use this language. - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}members SET lngfile = {empty} WHERE lngfile = {string:current_language}', - array( + [ 'empty_string' => '', 'current_language' => $lang_id, - ) + ], ); // Fifth, update Lang::get() cache. - if (!empty(CacheApi::$enable)) - { + if (!empty(CacheApi::$enable)) { CacheApi::put('known_languages', null, !empty(CacheApi::$enable) && CacheApi::$enable < 1 ? 86400 : 3600); } // Sixth, if we deleted the default language, set us back to english? - if ($lang_id == Lang::$default) - { + if ($lang_id == Lang::$default) { Lang::$default = 'english'; - Config::updateSettingsFile(array('language' => Lang::$default)); + Config::updateSettingsFile(['language' => Lang::$default]); } // Seventh, get out of here. @@ -930,19 +883,18 @@ function($val1, $val2) } // Saving primary settings? - $primary_settings = array( + $primary_settings = [ 'native_name' => 'string', 'lang_character_set' => 'string', 'lang_locale' => 'string', 'lang_rtl' => 'string', 'lang_dictionary' => 'string', 'lang_recaptcha' => 'string', - ); + ]; $madeSave = false; - if (!empty($_POST['save_main']) && !$current_file) - { + if (!empty($_POST['save_main']) && !$current_file) { User::$me->checkSession(); SecurityToken::validate('admin-mlang'); @@ -950,11 +902,10 @@ function($val1, $val2) $current_data = implode('', file(Theme::$current->settings['default_theme_dir'] . '/languages/index.' . $lang_id . '.php')); // Build the replacements. old => new - $replace_array = array(); + $replace_array = []; - foreach ($primary_settings as $setting => $type) - { - $replace_array['~\$txt\[\'' . $setting . '\'\]\s*=\s*[^\r\n]+~'] = '$txt[\'' . $setting . '\'] = ' . ($type === 'bool' ? (!empty($_POST[$setting]) ? 'true' : 'false') : '\'' . ($setting = 'native_name' ? htmlentities(Utils::htmlspecialcharsDecode($_POST[$setting]), ENT_QUOTES, Utils::$context['character_set']) : preg_replace('~[^\w-]~i', '', $_POST[$setting])) . '\'') . ';'; + foreach ($primary_settings as $setting => $type) { + $replace_array['~\\$txt\\[\'' . $setting . '\'\\]\\s*=\\s*[^\\r\\n]+~'] = '$txt[\'' . $setting . '\'] = ' . ($type === 'bool' ? (!empty($_POST[$setting]) ? 'true' : 'false') : '\'' . ($setting = 'native_name' ? htmlentities(Utils::htmlspecialcharsDecode($_POST[$setting]), ENT_QUOTES, Utils::$context['character_set']) : preg_replace('~[^\\w-]~i', '', $_POST[$setting])) . '\'') . ';'; } $current_data = preg_replace(array_keys($replace_array), array_values($replace_array), $current_data); @@ -969,86 +920,69 @@ function($val1, $val2) // Quickly load index language entries. $old_txt = Lang::$txt; - require(Theme::$current->settings['default_theme_dir'] . '/languages/index.' . $lang_id . '.php'); + require Theme::$current->settings['default_theme_dir'] . '/languages/index.' . $lang_id . '.php'; Utils::$context['lang_file_not_writable_message'] = is_writable(Theme::$current->settings['default_theme_dir'] . '/languages/index.' . $lang_id . '.php') ? '' : sprintf(Lang::$txt['lang_file_not_writable'], Theme::$current->settings['default_theme_dir'] . '/languages/index.' . $lang_id . '.php'); // Setup the primary settings context. - Utils::$context['primary_settings']['name'] = Utils::ucwords(strtr($lang_id, array('_' => ' ', '-utf8' => ''))); + Utils::$context['primary_settings']['name'] = Utils::ucwords(strtr($lang_id, ['_' => ' ', '-utf8' => ''])); - foreach ($primary_settings as $setting => $type) - { - Utils::$context['primary_settings'][$setting] = array( + foreach ($primary_settings as $setting => $type) { + Utils::$context['primary_settings'][$setting] = [ 'label' => str_replace('lang_', '', $setting), 'value' => Lang::$txt[$setting], - ); + ]; } // Restore normal service. Lang::$txt = $old_txt; // Are we saving? - $save_strings = array(); - $remove_strings = array(); - $add_strings = array(); + $save_strings = []; + $remove_strings = []; + $add_strings = []; - if (isset($_POST['save_entries'])) - { + if (isset($_POST['save_entries'])) { User::$me->checkSession(); SecurityToken::validate('admin-mlang'); - if (!empty($_POST['edit'])) - { - foreach ($_POST['edit'] as $k => $v) - { - if (is_string($v)) - { + if (!empty($_POST['edit'])) { + foreach ($_POST['edit'] as $k => $v) { + if (is_string($v)) { // Only try to save if 'edit' was specified and if the string has changed if ( $v == 'edit' - && isset($_POST['entry'][$k]) - && isset($_POST['comp'][$k]) + && isset($_POST['entry'][$k], $_POST['comp'][$k]) + && $_POST['entry'][$k] != $_POST['comp'][$k] - ) - { + ) { $save_strings[$k] = $this->cleanLangString($_POST['entry'][$k], false); } // Record any add or remove requests. We'll decide on them later. - elseif ($v == 'remove') - { + elseif ($v == 'remove') { $remove_strings[] = $k; - } - elseif ($v == 'add' && isset($_POST['entry'][$k])) - { - $add_strings[$k] = array( - 'group' => isset($_POST['grp'][$k]) ? $_POST['grp'][$k] : 'txt', + } elseif ($v == 'add' && isset($_POST['entry'][$k])) { + $add_strings[$k] = [ + 'group' => $_POST['grp'][$k] ?? 'txt', 'string' => $this->cleanLangString($_POST['entry'][$k], false), - ); + ]; } - } - elseif (is_array($v)) - { - foreach ($v as $subk => $subv) - { + } elseif (is_array($v)) { + foreach ($v as $subk => $subv) { if ( $subv == 'edit' - && isset($_POST['entry'][$k][$subk]) - && isset($_POST['comp'][$k][$subk]) + && isset($_POST['entry'][$k][$subk], $_POST['comp'][$k][$subk]) + && $_POST['entry'][$k][$subk] != $_POST['comp'][$k][$subk] - ) - { + ) { $save_strings[$k][$subk] = $this->cleanLangString($_POST['entry'][$k][$subk], false); - } - elseif ($subv == 'remove') - { + } elseif ($subv == 'remove') { $remove_strings[$k][] = $subk; - } - elseif ($subv == 'add' && isset($_POST['entry'][$k][$subk])) - { - $add_strings[$k][$subk] = array( - 'group' => isset($_POST['grp'][$k]) ? $_POST['grp'][$k] : 'txt', + } elseif ($subv == 'add' && isset($_POST['entry'][$k][$subk])) { + $add_strings[$k][$subk] = [ + 'group' => $_POST['grp'][$k] ?? 'txt', 'string' => $this->cleanLangString($_POST['entry'][$k][$subk], false), - ); + ]; } } @@ -1058,10 +992,9 @@ function($val1, $val2) } // If we are editing a file work away at that. - Utils::$context['can_add_lang_entry'] = array(); + Utils::$context['can_add_lang_entry'] = []; - if ($current_file) - { + if ($current_file) { Utils::$context['entries_not_writable_message'] = is_writable($current_file) ? '' : sprintf(Lang::$txt['lang_entries_not_writable'], $current_file); // How many strings will PHP let us edit at once? @@ -1069,42 +1002,39 @@ function($val1, $val2) Utils::$context['max_inputs'] = floor(ini_get('max_input_vars') / 3) - 5; // Do we want to override the helptxt for certain types of text variables? - $special_groups = array( - 'Timezones' => array('txt' => 'txt_for_timezones'), - 'EmailTemplates' => array('txt' => 'txt_for_email_templates', 'txtBirthdayEmails' => 'txt_for_email_templates'), - ); + $special_groups = [ + 'Timezones' => ['txt' => 'txt_for_timezones'], + 'EmailTemplates' => ['txt' => 'txt_for_email_templates', 'txtBirthdayEmails' => 'txt_for_email_templates'], + ]; - IntegrationHook::call('integrate_language_edit_helptext', array(&$special_groups)); + IntegrationHook::call('integrate_language_edit_helptext', [&$special_groups]); // Determine which groups of strings (if any) allow adding new entries - if (isset($allows_add_remove[$file_id]['add'])) - { - foreach ($allows_add_remove[$file_id]['add'] as $var_group) - { + if (isset($allows_add_remove[$file_id]['add'])) { + foreach ($allows_add_remove[$file_id]['add'] as $var_group) { $group = !empty($special_groups[$file_id][$var_group]) ? $special_groups[$file_id][$var_group] : $var_group; - if (in_array($var_group, $allows_add_remove[$file_id]['add'])) + if (in_array($var_group, $allows_add_remove[$file_id]['add'])) { Utils::$context['can_add_lang_entry'][$group] = true; + } } } // Read in the file's contents and process it into entries. // Also, remove any lines for uneditable variables like $forum_copyright from the working data. - $entries = array(); + $entries = []; - foreach (preg_split('~^(?=\$(?:' . implode('|', $string_types) . ')\[\'([^\n]+?)\'\])~m' . (Utils::$context['utf8'] ? 'u' : ''), preg_replace('~\s*\n(\$(?!(?:' . implode('|', $string_types) . '))[^\n]*)~', '', file_get_contents($current_file))) as $blob) - { + foreach (preg_split('~^(?=\\$(?:' . implode('|', $string_types) . ')\\[\'([^\\n]+?)\'\\])~m' . (Utils::$context['utf8'] ? 'u' : ''), preg_replace('~\\s*\\n(\\$(?!(?:' . implode('|', $string_types) . '))[^\\n]*)~', '', file_get_contents($current_file))) as $blob) { // Comment lines at the end of the blob can make terrible messes - $blob = preg_replace('~(\n[ \t]*//[^\n]*)*$~' . (Utils::$context['utf8'] ? 'u' : ''), '', $blob); + $blob = preg_replace('~(\\n[ \\t]*//[^\\n]*)*$~' . (Utils::$context['utf8'] ? 'u' : ''), '', $blob); // Extract the variable - if (preg_match('~^\$(' . implode('|', $string_types) . ')\[\'([^\n]+?)\'\](?:\[\'?([^\n]+?)\'?\])?\s?=\s?(.+);([ \t]*(?://[^\n]*)?)$~ms' . (Utils::$context['utf8'] ? 'u' : ''), strtr($blob, array("\r" => '')), $matches)) - { + if (preg_match('~^\\$(' . implode('|', $string_types) . ')\\[\'([^\\n]+?)\'\\](?:\\[\'?([^\\n]+?)\'?\\])?\\s?=\\s?(.+);([ \\t]*(?://[^\\n]*)?)$~ms' . (Utils::$context['utf8'] ? 'u' : ''), strtr($blob, ["\r" => '']), $matches)) { // If no valid subkey was found, we need it to be explicitly null $matches[3] = isset($matches[3]) && $matches[3] !== '' ? $matches[3] : null; // The point of this exercise - $entries[$matches[2] . (isset($matches[3]) ? '[' . $matches[3] . ']' : '')] = array( + $entries[$matches[2] . (isset($matches[3]) ? '[' . $matches[3] . ']' : '')] = [ 'type' => $matches[1], 'group' => !empty($special_groups[$file_id][$matches[1]]) ? $special_groups[$file_id][$matches[1]] : $matches[1], 'can_remove' => isset($allows_add_remove[$file_id]['remove']) && in_array($matches[1], $allows_add_remove[$file_id]['remove']), @@ -1113,25 +1043,26 @@ function($val1, $val2) 'full' => $matches[0], 'entry' => $matches[4], 'cruft' => $matches[5], - ); + ]; } } // These will be the entries we can definitely save. - $final_saves = array(); - Utils::$context['file_entries'] = array(); - foreach ($entries as $entryKey => $entryValue) - { + $final_saves = []; + Utils::$context['file_entries'] = []; + + foreach ($entries as $entryKey => $entryValue) { // Ignore some things we set separately. - if (in_array($entryKey, array_keys($primary_settings))) + if (in_array($entryKey, array_keys($primary_settings))) { continue; + } // These are arrays that need breaking out. - if (strpos($entryValue['entry'], 'array(') === 0 && substr($entryValue['entry'], -1) === ')') - { + if (strpos($entryValue['entry'], 'array(') === 0 && substr($entryValue['entry'], -1) === ')') { // No, you may not use multidimensional arrays of Lang::$txt strings. Madness stalks that path. - if (isset($entryValue['subkey'])) + if (isset($entryValue['subkey'])) { continue; + } // Trim off the array construct bits. $entryValue['entry'] = substr($entryValue['entry'], strpos($entryValue['entry'], 'array(') + 6, -1); @@ -1143,29 +1074,29 @@ function($val1, $val2) # Optional explicit key assignment (?: (?: - \d+ + \\d+ | (?: (?: - \'(?:[^\']|(?<=\\\)\')*\' + \'(?:[^\']|(?<=\\\\)\')*\' ) | (?: - "(?:[^"]|(?<=\\\)")*" + "(?:[^"]|(?<=\\\\)")*" ) ) ) - \s*=>\s* + \\s*=>\\s* )? # String value in single or double quotes (?: (?: - \'(?:[^\']|(?<=\\\)\')*\' + \'(?:[^\']|(?<=\\\\)\')*\' ) | (?: - "(?:[^"]|(?<=\\\)")*" + "(?:[^"]|(?<=\\\\)")*" ) ) @@ -1174,77 +1105,68 @@ function($val1, $val2) /x' . (Utils::$context['utf8'] ? 'u' : ''), $entryValue['entry'], $matches); - if (empty($m)) + if (empty($m)) { continue; + } $entryValue['entry'] = $matches[0]; // Now create an entry for each item. $cur_index = -1; - $save_cache = array( + $save_cache = [ 'enabled' => false, - 'entries' => array(), - ); - foreach ($entryValue['entry'] as $id => $subValue) - { + 'entries' => [], + ]; + + foreach ($entryValue['entry'] as $id => $subValue) { // Is this a new index? - if (preg_match('/^(\d+|(?:(?:\'(?:[^\']|(?<=\\\)\')*\')|(?:"(?:[^"]|(?<=\\\)")*")))\s*=>/', $subValue, $matches)) - { + if (preg_match('/^(\\d+|(?:(?:\'(?:[^\']|(?<=\\\\)\')*\')|(?:"(?:[^"]|(?<=\\\\)")*")))\\s*=>/', $subValue, $matches)) { $subKey = trim($matches[1], '\'"'); - if (ctype_digit($subKey)) + if (ctype_digit($subKey)) { $cur_index = $subKey; + } $subValue = trim(substr($subValue, strpos($subValue, '=>') + 2)); - } - else - { + } else { $subKey = ++$cur_index; } // Clean up some bits. - if (strpos($subValue, '\'') === 0) - { + if (strpos($subValue, '\'') === 0) { $subValue = trim($subValue, '\''); - } - elseif (strpos($subValue, '"') === 0) - { + } elseif (strpos($subValue, '"') === 0) { $subValue = trim($subValue, '"'); } // Can we save? - if (isset($save_strings[$entryKey][$subKey])) - { - $save_cache['entries'][$subKey] = strtr($save_strings[$entryKey][$subKey], array('\'' => '')); + if (isset($save_strings[$entryKey][$subKey])) { + $save_cache['entries'][$subKey] = strtr($save_strings[$entryKey][$subKey], ['\'' => '']); $save_cache['enabled'] = true; } // Should we remove this one? - elseif (isset($remove_strings[$entryKey]) && in_array($subKey, $remove_strings[$entryKey]) && $entryValue['can_remove']) - { + elseif (isset($remove_strings[$entryKey]) && in_array($subKey, $remove_strings[$entryKey]) && $entryValue['can_remove']) { $save_cache['enabled'] = true; } // Just keep this one as it is - else - { + else { $save_cache['entries'][$subKey] = $subValue; } - Utils::$context['file_entries'][$entryValue['group']][] = array( + Utils::$context['file_entries'][$entryValue['group']][] = [ 'key' => $entryKey, 'subkey' => $subKey, 'value' => $subValue, 'rows' => 1, 'can_remove' => $entryValue['can_remove'], - ); + ]; } // Should we add a new string to this array? - if (!empty(Utils::$context['can_add_lang_entry'][$entryValue['type']]) && isset($add_strings[$entryKey])) - { - foreach ($add_strings[$entryKey] as $string_key => $string_val) - { - $save_cache['entries'][$string_key] = strtr($string_val['string'], array('\'' => '')); + if (!empty(Utils::$context['can_add_lang_entry'][$entryValue['type']]) && isset($add_strings[$entryKey])) { + foreach ($add_strings[$entryKey] as $string_key => $string_val) { + $save_cache['entries'][$string_key] = strtr($string_val['string'], ['\'' => '']); } $save_cache['enabled'] = true; @@ -1252,26 +1174,23 @@ function($val1, $val2) // Make sure we don't add this again as an independent line unset($add_strings[$entryKey][$string_key]); - if (empty($add_strings[$entryKey])) + if (empty($add_strings[$entryKey])) { unset($add_strings[$entryKey]); + } } // Do we need to save? - if ($save_cache['enabled']) - { + if ($save_cache['enabled']) { // Format the string, checking the indexes first. - $items = array(); + $items = []; $cur_index = 0; - foreach ($save_cache['entries'] as $k2 => $v2) - { + + foreach ($save_cache['entries'] as $k2 => $v2) { // Manually show the custom index. - if ($k2 != $cur_index) - { + if ($k2 != $cur_index) { $items[] = $k2 . ' => \'' . $v2 . '\''; $cur_index = $k2; - } - else - { + } else { $items[] = '\'' . $v2 . '\''; } @@ -1279,20 +1198,19 @@ function($val1, $val2) } // Now create the string! - $final_saves[$entryKey] = array( + $final_saves[$entryKey] = [ 'find' => $entryValue['full'], 'replace' => '// ' . implode("\n// ", explode("\n", rtrim($entryValue['full'], "\n"))) . "\n" . '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = array(' . implode(', ', $items) . ');' . $entryValue['cruft'], - ); + ]; } } // A single array element, like: Lang::$txt['foo']['bar'] = 'baz'; - elseif (isset($entryValue['subkey'])) - { + elseif (isset($entryValue['subkey'])) { // Saving? - if (isset($save_strings[$entryValue['key']][$entryValue['subkey']]) && $save_strings[$entryValue['key']][$entryValue['subkey']] != $entryValue['entry']) - { - if ($save_strings[$entryValue['key']][$entryValue['subkey']] == '') + if (isset($save_strings[$entryValue['key']][$entryValue['subkey']]) && $save_strings[$entryValue['key']][$entryValue['subkey']] != $entryValue['entry']) { + if ($save_strings[$entryValue['key']][$entryValue['subkey']] == '') { $save_strings[$entryValue['key']][$entryValue['subkey']] = '\'\''; + } // Preserve subkey as either digit or string $subKey = ctype_digit($entryValue['subkey']) ? $entryValue['subkey'] : '\'' . $entryValue['subkey'] . '\''; @@ -1301,135 +1219,124 @@ function($val1, $val2) $entryValue['entry'] = $save_strings[$entryValue['key']][$entryValue['subkey']]; // And save it - $final_saves[$entryKey] = array( + $final_saves[$entryKey] = [ 'find' => $entryValue['full'], 'replace' => '// ' . implode("\n// ", explode("\n", rtrim($entryValue['full'], "\n"))) . "\n" . '$' . $entryValue['type'] . '[\'' . $entryValue['key'] . '\'][' . $subKey . '] = ' . $save_strings[$entryValue['key']][$entryValue['subkey']] . ';' . $entryValue['cruft'], - ); + ]; } // Remove this entry only if it is allowed - if (isset($remove_strings[$entryValue['key']]) && in_array($entryValue['subkey'], $remove_strings[$entryValue['key']]) && $entryValue['can_remove']) - { + if (isset($remove_strings[$entryValue['key']]) && in_array($entryValue['subkey'], $remove_strings[$entryValue['key']]) && $entryValue['can_remove']) { $entryValue['entry'] = '\'\''; - $final_saves[$entryKey] = array( + $final_saves[$entryKey] = [ 'find' => $entryValue['full'], 'replace' => '// ' . implode("\n// ", explode("\n", rtrim($entryValue['full'], "\n"))) . "\n", - ); + ]; } $editing_string = $this->cleanLangString($entryValue['entry'], true); - Utils::$context['file_entries'][$entryValue['group']][] = array( + Utils::$context['file_entries'][$entryValue['group']][] = [ 'key' => $entryValue['key'], 'subkey' => $entryValue['subkey'], 'value' => $editing_string, 'rows' => strlen($editing_string) / 38 + substr_count($editing_string, "\n") + 1, 'can_remove' => $entryValue['can_remove'], - ); + ]; } // A simple string entry - else - { + else { // Saving? - if (isset($save_strings[$entryValue['key']]) && $save_strings[$entryValue['key']] != $entryValue['entry']) - { - if ($save_strings[$entryValue['key']] == '') + if (isset($save_strings[$entryValue['key']]) && $save_strings[$entryValue['key']] != $entryValue['entry']) { + if ($save_strings[$entryValue['key']] == '') { $save_strings[$entryValue['key']] = '\'\''; + } // Set the new value. $entryValue['entry'] = $save_strings[$entryValue['key']]; // And we know what to save now! - $final_saves[$entryKey] = array( + $final_saves[$entryKey] = [ 'find' => $entryValue['full'], 'replace' => '// ' . implode("\n// ", explode("\n", rtrim($entryValue['full'], "\n"))) . "\n" . '$' . $entryValue['type'] . '[\'' . $entryValue['key'] . '\'] = ' . $save_strings[$entryValue['key']] . ';' . $entryValue['cruft'], - ); + ]; } // Remove this entry only if it is allowed - if (in_array($entryValue['key'], $remove_strings) && $entryValue['can_remove']) - { + if (in_array($entryValue['key'], $remove_strings) && $entryValue['can_remove']) { $entryValue['entry'] = '\'\''; - $final_saves[$entryKey] = array( + $final_saves[$entryKey] = [ 'find' => $entryValue['full'], 'replace' => '// ' . implode("\n// ", explode("\n", rtrim($entryValue['full'], "\n"))) . "\n", - ); + ]; } $editing_string = $this->cleanLangString($entryValue['entry'], true); - Utils::$context['file_entries'][$entryValue['group']][] = array( + Utils::$context['file_entries'][$entryValue['group']][] = [ 'key' => $entryValue['key'], 'subkey' => null, 'value' => $editing_string, 'rows' => (int) (strlen($editing_string) / 38) + substr_count($editing_string, "\n") + 1, 'can_remove' => $entryValue['can_remove'], - ); + ]; } } // Do they want to add some brand new strings? Does this file allow that? - if (!empty($add_strings) && !empty($allows_add_remove[$file_id]['add'])) - { - $special_types = isset($special_groups[$file_id]) ? array_flip($special_groups[$file_id]) : array(); + if (!empty($add_strings) && !empty($allows_add_remove[$file_id]['add'])) { + $special_types = isset($special_groups[$file_id]) ? array_flip($special_groups[$file_id]) : []; - foreach ($add_strings as $string_key => $string_val) - { + foreach ($add_strings as $string_key => $string_val) { // Adding a normal string - if (isset($string_val['string']) && is_string($string_val['string'])) - { - $type = isset($special_types[$string_val['group']]) ? $special_types[$string_val['group']] : $string_val['group']; + if (isset($string_val['string']) && is_string($string_val['string'])) { + $type = $special_types[$string_val['group']] ?? $string_val['group']; - if (empty(Utils::$context['can_add_lang_entry'][$type])) + if (empty(Utils::$context['can_add_lang_entry'][$type])) { continue; + } - $final_saves[$string_key] = array( - 'find' => "\s*\?" . '>$', + $final_saves[$string_key] = [ + 'find' => '\\s*\\?' . '>$', 'replace' => "\n\$" . $type . '[\'' . $string_key . '\'] = ' . $string_val['string'] . ';' . "\n\n?" . '>', 'is_regex' => true, - ); + ]; } // Adding an array element - else - { - foreach ($string_val as $substring_key => $substring_val) - { - $type = isset($special_types[$substring_val['group']]) ? $special_types[$substring_val['group']] : $substring_val['group']; + else { + foreach ($string_val as $substring_key => $substring_val) { + $type = $special_types[$substring_val['group']] ?? $substring_val['group']; - if (empty(Utils::$context['can_add_lang_entry'][$type])) + if (empty(Utils::$context['can_add_lang_entry'][$type])) { continue; + } $subKey = ctype_digit(trim($substring_key, '\'')) ? trim($substring_key, '\'') : '\'' . $substring_key . '\''; - $final_saves[$string_key . '[' . $substring_key . ']'] = array( - 'find' => "\s*\?" . '>$', + $final_saves[$string_key . '[' . $substring_key . ']'] = [ + 'find' => '\\s*\\?' . '>$', 'replace' => "\n\$" . $type . '[\'' . $string_key . '\'][' . $subKey . '] = ' . $substring_val['string'] . ';' . "\n\n?" . '>', 'is_regex' => true, - ); + ]; } } } } // Any saves to make? - if (!empty($final_saves)) - { + if (!empty($final_saves)) { User::$me->checkSession(); // Get a fresh copy of the file's current content. $file_contents = file_get_contents($current_file); // Apply our changes. - foreach ($final_saves as $save) - { - if (!empty($save['is_regex'])) - { + foreach ($final_saves as $save) { + if (!empty($save['is_regex'])) { $file_contents = preg_replace('~' . $save['find'] . '~' . (Utils::$context['utf8'] ? 'u' : ''), $save['replace'], $file_contents); - } - else - { + } else { $file_contents = str_replace($save['find'], $save['replace'], $file_contents); } } @@ -1444,13 +1351,12 @@ function($val1, $val2) Lang::$txt = $old_txt; // If they can add new language entries, make sure the UI is set up for that. - if (!empty(Utils::$context['can_add_lang_entry'])) - { + if (!empty(Utils::$context['can_add_lang_entry'])) { // Make sure the Add button has a place to show up. - foreach (Utils::$context['can_add_lang_entry'] as $group => $value) - { - if (!isset(Utils::$context['file_entries'][$group])) - Utils::$context['file_entries'][$group] = array(); + foreach (Utils::$context['can_add_lang_entry'] as $group => $value) { + if (!isset(Utils::$context['file_entries'][$group])) { + Utils::$context['file_entries'][$group] = []; + } } Theme::addInlineJavaScript(' @@ -1460,7 +1366,7 @@ function add_lang_entry(group) { if (key !== null) { ++entry_num; - var array_regex = /^(.*)(\[[^\[\]]*\])$/ + var array_regex = /^(.*)(\\[[^\\[\\]]*\\])$/ var result = array_regex.exec(key); if (result != null) { key = result[1]; @@ -1469,13 +1375,13 @@ function add_lang_entry(group) { var subkey = ""; } - var bracket_regex = /[\[\]]/ + var bracket_regex = /[\\[\\]]/ if (bracket_regex.test(key)) { alert("' . Lang::$txt['languages_invalid_key'] . '" + key + subkey); return; } - $("#language_" + group).append("
" + key + subkey + "
"); + $("#language_" + group).append("
" + key + subkey + "
"); } };'); @@ -1485,8 +1391,7 @@ function add_lang_entry(group) { // Warn them if they try to submit more changes than the server can accept in a single request. // Also make it obvious that they cannot submit changes to both the primary settings and the entries at the same time. - if (!empty(Utils::$context['file_entries'])) - { + if (!empty(Utils::$context['file_entries'])) { Theme::addInlineJavaScript(' max_inputs = ' . Utils::$context['max_inputs'] . '; num_inputs = 0; @@ -1543,8 +1448,7 @@ function add_lang_entry(group) { } // If we saved, redirect. - if ($madeSave) - { + if ($madeSave) { Utils::redirectexit('action=admin;area=languages;sa=editlang;lid=' . $lang_id . (!empty($file_id) ? ';entries;tfid=' . $theme_id . rawurlencode('+') . $file_id : '')); } @@ -1562,8 +1466,9 @@ function add_lang_entry(group) { */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -1583,12 +1488,12 @@ public static function call(): void */ public static function getConfigVars(): array { - $config_vars = array( - 'language' => array('language', Lang::$txt['default_language'], 'file', 'select', array(), null, 'disabled' => !is_writable(SMF_SETTINGS_FILE)), - array('userLanguage', Lang::$txt['userLanguage'], 'db', 'check', null, 'userLanguage'), - ); + $config_vars = [ + 'language' => ['language', Lang::$txt['default_language'], 'file', 'select', [], null, 'disabled' => !is_writable(SMF_SETTINGS_FILE)], + ['userLanguage', Lang::$txt['userLanguage'], 'db', 'check', null, 'userLanguage'], + ]; - IntegrationHook::call('integrate_language_settings', array(&$config_vars)); + IntegrationHook::call('integrate_language_settings', [&$config_vars]); return $config_vars; } @@ -1604,45 +1509,39 @@ public static function list_getLanguagesList(): array // We're going to use this URL. $url = 'https://download.simplemachines.org/fetch_language.php?version=' . urlencode(SMF_VERSION); - $smf_languages = array(); + $smf_languages = []; // Load the class file and stick it into an array. $language_list = new XmlArray(WebFetchApi::fetch($url), true); // Check that the site responded and that the language exists. - if (!$language_list->exists('languages')) - { + if (!$language_list->exists('languages')) { Utils::$context['smf_error'] = 'no_response'; - } - elseif (!$language_list->exists('languages/language')) - { + } elseif (!$language_list->exists('languages/language')) { Utils::$context['smf_error'] = 'no_files'; - } - else - { + } else { $language_list = $language_list->path('languages[0]'); $lang_files = $language_list->set('language'); - foreach ($lang_files as $file) - { + foreach ($lang_files as $file) { // Were we searching? - if (!empty(Utils::$context['smf_search_term']) && strpos($file->fetch('name'), Utils::strtolower(Utils::$context['smf_search_term'])) === false) - { + if (!empty(Utils::$context['smf_search_term']) && strpos($file->fetch('name'), Utils::strtolower(Utils::$context['smf_search_term'])) === false) { continue; } - $smf_languages[] = array( + $smf_languages[] = [ 'id' => $file->fetch('id'), 'name' => Utils::ucwords($file->fetch('name')), 'version' => $file->fetch('version'), 'utf8' => Lang::$txt['yes'], 'description' => $file->fetch('description'), 'install_link' => '' . Lang::$txt['add_language_smf_install'] . '', - ); + ]; } - if (empty($smf_languages)) + if (empty($smf_languages)) { Utils::$context['smf_error'] = 'no_files'; + } } return $smf_languages; @@ -1669,7 +1568,7 @@ public static function list_getNumLanguages() */ public static function list_getLanguages() { - $languages = array(); + $languages = []; // Keep our old entries. $old_txt = Lang::$txt; @@ -1685,51 +1584,47 @@ public static function list_getLanguages() // Put them back. Theme::$current->settings['actual_theme_dir'] = $backup_actual_theme_dir; - if (!empty($backup_base_theme_dir)) - { + if (!empty($backup_base_theme_dir)) { Theme::$current->settings['base_theme_dir'] = $backup_base_theme_dir; - } - else - { + } else { unset(Theme::$current->settings['base_theme_dir']); } // Get the language files and data... - foreach (Utils::$context['languages'] as $lang) - { + foreach (Utils::$context['languages'] as $lang) { // Load the file to get the character set. - require(Theme::$current->settings['default_theme_dir'] . '/languages/index.' . $lang['filename'] . '.php'); + require Theme::$current->settings['default_theme_dir'] . '/languages/index.' . $lang['filename'] . '.php'; - $languages[$lang['filename']] = array( + $languages[$lang['filename']] = [ 'id' => $lang['filename'], 'count' => 0, 'char_set' => Lang::$txt['lang_character_set'], 'default' => Lang::$default == $lang['filename'] || (Lang::$default == '' && $lang['filename'] == 'english'), 'locale' => Lang::$txt['lang_locale'], - 'name' => Utils::ucwords(strtr($lang['filename'], array('_' => ' ', '-utf8' => ''))), - ); + 'name' => Utils::ucwords(strtr($lang['filename'], ['_' => ' ', '-utf8' => ''])), + ]; } // Work out how many people are using each language. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT lngfile, COUNT(*) AS num_users FROM {db_prefix}members GROUP BY lngfile', - array( - ) + [ + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { // Default? - if (empty($row['lngfile']) || !isset($languages[$row['lngfile']])) + if (empty($row['lngfile']) || !isset($languages[$row['lngfile']])) { $row['lngfile'] = Lang::$default; + } - if (!isset($languages[$row['lngfile']]) && isset($languages['english'])) - { + if (!isset($languages[$row['lngfile']]) && isset($languages['english'])) { $languages['english']['count'] += $row['num_users']; - } - elseif (isset($languages[$row['lngfile']])) - { + } elseif (isset($languages[$row['lngfile']])) { $languages[$row['lngfile']]['count'] += $row['num_users']; } } @@ -1770,8 +1665,9 @@ public static function addLanguage(): void */ public static function modifyLanguageSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::getConfigVars(); + } self::load(); self::$obj->subaction = 'settings'; @@ -1814,16 +1710,17 @@ protected function __construct() Utils::$context['sub_template'] = 'show_settings'; // Load up all the tabs... - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['language_configuration'], 'description' => Lang::$txt['language_description'], - ); + ]; - IntegrationHook::call('integrate_manage_languages', array(&self::$subactions)); + IntegrationHook::call('integrate_manage_languages', [&self::$subactions]); // By default we're managing languages. - if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) + if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) { $this->subaction = $_REQUEST['sa']; + } Utils::$context['sub_action'] = $this->subaction; } @@ -1842,27 +1739,24 @@ protected function cleanLangString($string, $to_display = true) // If going to display we make sure it doesn't have any HTML in it - etc. $new_string = ''; - if ($to_display) - { + if ($to_display) { // Are we in a string (0 = no, 1 = single quote, 2 = parsed) $in_string = 0; $is_escape = false; - for ($i = 0; $i < strlen($string); $i++) - { + for ($i = 0; $i < strlen($string); $i++) { // Handle escapes first. - if ($string[$i] == '\\') - { + if ($string[$i] == '\\') { // Toggle the escape. $is_escape = !$is_escape; // If we're now escaped don't add this string. - if ($is_escape) + if ($is_escape) { continue; + } } // Special case - parsed string with line break etc? - elseif (($string[$i] == 'n' || $string[$i] == 't') && $in_string == 2 && $is_escape) - { + elseif (($string[$i] == 'n' || $string[$i] == 't') && $in_string == 2 && $is_escape) { // Put the escape back... $new_string .= $string[$i] == 'n' ? "\n" : "\t"; $is_escape = false; @@ -1870,19 +1764,15 @@ protected function cleanLangString($string, $to_display = true) continue; } // Have we got a single quote? - elseif ($string[$i] == '\'') - { + elseif ($string[$i] == '\'') { // Already in a parsed string, or escaped in a linear string, means we print it - otherwise something special. - if ($in_string != 2 && ($in_string != 1 || !$is_escape)) - { + if ($in_string != 2 && ($in_string != 1 || !$is_escape)) { // Is it the end of a single quote string? - if ($in_string == 1) - { + if ($in_string == 1) { $in_string = 0; } // Otherwise it's the start! - else - { + else { $in_string = 1; } @@ -1891,19 +1781,15 @@ protected function cleanLangString($string, $to_display = true) } } // Otherwise a double quote? - elseif ($string[$i] == '"') - { + elseif ($string[$i] == '"') { // Already in a single quote string, or escaped in a parsed string, means we print it - otherwise something special. - if ($in_string != 1 && ($in_string != 2 || !$is_escape)) - { + if ($in_string != 1 && ($in_string != 2 || !$is_escape)) { // Is it the end of a double quote string? - if ($in_string == 2) - { + if ($in_string == 2) { $in_string = 0; } // Otherwise it's the start! - else - { + else { $in_string = 2; } @@ -1912,18 +1798,15 @@ protected function cleanLangString($string, $to_display = true) } } // A join/space outside of a string is simply removed. - elseif ($in_string == 0 && (empty($string[$i]) || $string[$i] == '.')) - { + elseif ($in_string == 0 && (empty($string[$i]) || $string[$i] == '.')) { continue; } // Start of a variable? - elseif ($in_string == 0 && $string[$i] == '$') - { + elseif ($in_string == 0 && $string[$i] == '$') { // Find the whole of it! - preg_match('~([\$A-Za-z0-9\'\[\]_-]+)~', substr($string, $i), $matches); + preg_match('~([\\$A-Za-z0-9\'\\[\\]_-]+)~', substr($string, $i), $matches); - if (!empty($matches[1])) - { + if (!empty($matches[1])) { // Come up with some pseudo thing to indicate this is a var. $new_string .= '{%' . $matches[1] . '%}'; @@ -1934,8 +1817,7 @@ protected function cleanLangString($string, $to_display = true) continue; } // Right, if we're outside of a string we have DANGER, DANGER! - elseif ($in_string == 0) - { + elseif ($in_string == 0) { continue; } @@ -1948,9 +1830,7 @@ protected function cleanLangString($string, $to_display = true) // Unhtml then rehtml the whole thing! $new_string = Utils::htmlspecialchars(Utils::htmlspecialcharsDecode($new_string)); - } - else - { + } else { $string = Utils::normalize($string); // Keep track of what we're doing... @@ -1959,36 +1839,28 @@ protected function cleanLangString($string, $to_display = true) // This is for deciding whether to HTML a quote. $in_html = false; - for ($i = 0; $i < strlen($string); $i++) - { + for ($i = 0; $i < strlen($string); $i++) { // We don't do parsed strings apart from for breaks. - if ($in_string == 2) - { + if ($in_string == 2) { $in_string = 0; $new_string .= '"'; } // Not in a string yet? - if ($in_string != 1) - { + if ($in_string != 1) { $in_string = 1; $new_string .= ($new_string ? ' . ' : '') . '\''; } // Is this a variable? - if ($string[$i] == '{' && $string[$i + 1] == '%' && $string[$i + 2] == '$') - { + if ($string[$i] == '{' && $string[$i + 1] == '%' && $string[$i + 2] == '$') { // Grab the variable. - preg_match('~\{%([\$A-Za-z0-9\'\[\]_-]+)%\}~', substr($string, $i), $matches); + preg_match('~\\{%([\\$A-Za-z0-9\'\\[\\]_-]+)%\\}~', substr($string, $i), $matches); - if (!empty($matches[1])) - { - if ($in_string == 1) - { + if (!empty($matches[1])) { + if ($in_string == 1) { $new_string .= '\' . '; - } - elseif ($new_string) - { + } elseif ($new_string) { $new_string .= ' . '; } @@ -1999,54 +1871,49 @@ protected function cleanLangString($string, $to_display = true) continue; } + // Is this a lt sign? - elseif ($string[$i] == '<') - { + if ($string[$i] == '<') { // Probably HTML? - if ($string[$i + 1] != ' ') - { + if ($string[$i + 1] != ' ') { $in_html = true; } // Assume we need an entity... - else - { + else { $new_string .= '<'; + continue; } } // What about gt? - elseif ($string[$i] == '>') - { + elseif ($string[$i] == '>') { // Will it be HTML? - if ($in_html) - { + if ($in_html) { $in_html = false; } // Otherwise we need an entity... - else - { + else { $new_string .= '>'; + continue; } } + // Is it a slash? If so escape it... - if ($string[$i] == '\\') - { + if ($string[$i] == '\\') { $new_string .= '\\'; } // The infamous double quote? - elseif ($string[$i] == '"') - { + elseif ($string[$i] == '"') { // If we're in HTML we leave it as a quote - otherwise we entity it. - if (!$in_html) - { + if (!$in_html) { $new_string .= '"'; + continue; } } // A single quote? - elseif ($string[$i] == '\'') - { + elseif ($string[$i] == '\'') { // Must be in a string so escape it. $new_string .= '\\'; } @@ -2056,12 +1923,9 @@ protected function cleanLangString($string, $to_display = true) } // If we ended as a string then close it off. - if ($in_string == 1) - { + if ($in_string == 1) { $new_string .= '\''; - } - elseif ($in_string == 2) - { + } elseif ($in_string == 2) { $new_string .= '"'; } } @@ -2071,7 +1935,8 @@ protected function cleanLangString($string, $to_display = true) } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Languages::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Languages::exportStatic')) { Languages::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Logs.php b/Sources/Actions/Admin/Logs.php index 50e79a71ec..f409534ce7 100644 --- a/Sources/Actions/Admin/Logs.php +++ b/Sources/Actions/Admin/Logs.php @@ -13,9 +13,9 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\Actions\Moderation\Logs as Modlog; +use SMF\BackwardCompatibility; use SMF\Config; use SMF\IntegrationHook; use SMF\Lang; @@ -23,7 +23,6 @@ use SMF\Theme; use SMF\User; use SMF\Utils; -use SMF\Actions\Moderation\Logs as Modlog; /** * Dispatcher to show various kinds of logs. @@ -37,11 +36,11 @@ class Logs implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'adminLogs' => 'AdminLogs', - ), - ); + ], + ]; /******************* * Public properties @@ -66,44 +65,44 @@ class Logs implements ActionInterface * * Format: 'sa' => array('file', 'function', 'disabled' => 'setting_to_check') */ - public static array $subactions = array( - 'errorlog' => array( + public static array $subactions = [ + 'errorlog' => [ '', 'errorlog', // At runtime, will be set to empty(Config::$modSettings['enableErrorLogging']) 'disabled' => 'enableErrorLogging', - ), - 'adminlog' => array( + ], + 'adminlog' => [ '', 'adminlog', // At runtime, will be set to empty(Config::$modSettings['adminlog_enabled']) 'disabled' => 'adminlog_enabled', - ), - 'modlog' => array( + ], + 'modlog' => [ '', 'modlog', // At runtime, will be set to empty(Config::$modSettings['modlog_enabled']) 'disabled' => 'modlog_enabled', - ), - 'banlog' => array( + ], + 'banlog' => [ '', 'banlog', - ), - 'spiderlog' => array( + ], + 'spiderlog' => [ '', 'spiderlog', // At runtime, will be set to empty(Config::$modSettings['spider_mode']) 'disabled' => 'spider_mode', - ), - 'tasklog' => array( + ], + 'tasklog' => [ '', 'tasklog', - ), - 'settings' => array( + ], + 'settings' => [ '', 'settings', - ), - ); + ], + ]; /** * @var array @@ -114,14 +113,14 @@ class Logs implements ActionInterface * 'pruning' option is off, use the integrate_prune_settings hook to add it * to this list. */ - public static array $prune_toggle = array( + public static array $prune_toggle = [ 'pruneErrorLog', 'pruneModLog', 'pruneBanLog', 'pruneReportLog', 'pruneScheduledTaskLog', 'pruneSpiderHitLog', - ); + ]; /**************************** * Internal static properties @@ -145,43 +144,45 @@ class Logs implements ActionInterface public function execute(): void { // Set up some tab stuff. - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['logs'], 'help' => '', 'description' => Lang::$txt['maintain_info'], - 'tabs' => array( - 'errorlog' => array( + 'tabs' => [ + 'errorlog' => [ 'url' => Config::$scripturl . '?action=admin;area=logs;sa=errorlog;desc', 'description' => sprintf(Lang::$txt['errorlog_desc'], Lang::$txt['remove']), - ), - 'adminlog' => array( + ], + 'adminlog' => [ 'description' => Lang::$txt['admin_log_desc'], - ), - 'modlog' => array( + ], + 'modlog' => [ 'description' => Lang::$txt['moderation_log_desc'], - ), - 'banlog' => array( + ], + 'banlog' => [ 'description' => Lang::$txt['ban_log_description'], - ), - 'spiderlog' => array( + ], + 'spiderlog' => [ 'description' => Lang::$txt['spider_log_desc'], - ), - 'tasklog' => array( + ], + 'tasklog' => [ 'description' => Lang::$txt['scheduled_log_desc'], - ), - 'settings' => array( + ], + 'settings' => [ 'description' => Lang::$txt['log_settings_desc'], - ), - ), - ); + ], + ], + ]; - if (!empty(self::$subactions[$this->subaction][0])) - require_once(Config::$sourcedir . '/' . self::$subactions[$this->subaction][0]); + if (!empty(self::$subactions[$this->subaction][0])) { + require_once Config::$sourcedir . '/' . self::$subactions[$this->subaction][0]; + } - $call = method_exists($this, self::$subactions[$this->subaction][1]) ? array($this, self::$subactions[$this->subaction][1]) : Utils::getCallable(self::$subactions[$this->subaction][1]); + $call = method_exists($this, self::$subactions[$this->subaction][1]) ? [$this, self::$subactions[$this->subaction][1]] : Utils::getCallable(self::$subactions[$this->subaction][1]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } /** @@ -261,34 +262,31 @@ function togglePruned() $("#pruningOptions").click(function() { togglePruned(); });', true); // Saving? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { User::$me->checkSession(); // Although the UI presents pruningOptions as a checkbox followed by // several input fields, we save all that data as a single string. $config_vars['pruningOptions'][0] = 'text'; - if (!empty($_POST['pruningOptions'])) - { - $vals = array(); + if (!empty($_POST['pruningOptions'])) { + $vals = []; - foreach ($config_vars as $config_var) - { - if (!is_array($config_var) || !in_array($config_var[1], self::$prune_toggle)) + foreach ($config_vars as $config_var) { + if (!is_array($config_var) || !in_array($config_var[1], self::$prune_toggle)) { continue; + } // Just in case a mod did something stupid... - if ($config_var[1] === 'pruningOptions') + if ($config_var[1] === 'pruningOptions') { continue; + } $vals[] = max(0, (int) ($_POST[$config_var[1]] ?? 0)); } $_POST['pruningOptions'] = implode(',', $vals); - } - else - { + } else { $_POST['pruningOptions'] = ''; } @@ -302,17 +300,16 @@ function togglePruned() Utils::$context['sub_template'] = 'show_settings'; // Get the actual values - if (!empty(Config::$modSettings['pruningOptions'])) - { - foreach (explode(',', Config::$modSettings['pruningOptions']) as $key => $value) + if (!empty(Config::$modSettings['pruningOptions'])) { + foreach (explode(',', Config::$modSettings['pruningOptions']) as $key => $value) { Config::$modSettings[self::$prune_toggle[$key]] = $value; - } - else - { - $defaults = array_pad(array(30, 180, 180, 180, 30, 0), count(self::$prune_toggle), 0); + } + } else { + $defaults = array_pad([30, 180, 180, 180, 30, 0], count(self::$prune_toggle), 0); - foreach (array_combine(self::$prune_toggle, $defaults) as $setting => $default) + foreach (array_combine(self::$prune_toggle, $defaults) as $setting => $default) { Config::$modSettings[$setting] = $default; + } } ACP::prepareDBSettingContext($config_vars); @@ -329,8 +326,9 @@ function togglePruned() */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -350,55 +348,55 @@ public static function call(): void */ public static function getConfigVars(): array { - $config_vars = array( - array('check', 'modlog_enabled', 'help' => 'modlog'), - array('check', 'adminlog_enabled', 'help' => 'adminlog'), - array('check', 'userlog_enabled', 'help' => 'userlog'), + $config_vars = [ + ['check', 'modlog_enabled', 'help' => 'modlog'], + ['check', 'adminlog_enabled', 'help' => 'adminlog'], + ['check', 'userlog_enabled', 'help' => 'userlog'], // The error log is a wonderful thing. - array('title', 'errorlog', 'force_div_id' => 'errorlog'), - array('desc', 'error_log_desc'), - array('check', 'enableErrorLogging'), - array('check', 'enableErrorQueryLogging'), + ['title', 'errorlog', 'force_div_id' => 'errorlog'], + ['desc', 'error_log_desc'], + ['check', 'enableErrorLogging'], + ['check', 'enableErrorQueryLogging'], // The 'mark read' log settings. - array('title', 'markread_title', 'force_div_id' => 'markread_title'), - array('desc', 'mark_read_desc'), - array('int', 'mark_read_beyond', 'step' => 1, 'min' => 0, 'max' => 18000, 'subtext' => Lang::$txt['zero_to_disable']), - array('int', 'mark_read_delete_beyond', 'step' => 1, 'min' => 0, 'max' => 18000, 'subtext' => Lang::$txt['zero_to_disable']), - array('int', 'mark_read_max_users', 'step' => 1, 'min' => 0, 'max' => 20000, 'subtext' => Lang::$txt['zero_to_disable']), + ['title', 'markread_title', 'force_div_id' => 'markread_title'], + ['desc', 'mark_read_desc'], + ['int', 'mark_read_beyond', 'step' => 1, 'min' => 0, 'max' => 18000, 'subtext' => Lang::$txt['zero_to_disable']], + ['int', 'mark_read_delete_beyond', 'step' => 1, 'min' => 0, 'max' => 18000, 'subtext' => Lang::$txt['zero_to_disable']], + ['int', 'mark_read_max_users', 'step' => 1, 'min' => 0, 'max' => 20000, 'subtext' => Lang::$txt['zero_to_disable']], // Even do the pruning? - array('title', 'pruning_title', 'force_div_id' => 'pruning_title'), - array('desc', 'pruning_desc'), + ['title', 'pruning_title', 'force_div_id' => 'pruning_title'], + ['desc', 'pruning_desc'], // The array indexes are there so we can remove/change them before saving. - 'pruningOptions' => array('check', 'pruningOptions'), + 'pruningOptions' => ['check', 'pruningOptions'], '', // Various logs that could be pruned. // Error log. - array('int', 'pruneErrorLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']), + ['int', 'pruneErrorLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']], // Moderation log. - array('int', 'pruneModLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']), + ['int', 'pruneModLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']], // Ban hit log. - array('int', 'pruneBanLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']), + ['int', 'pruneBanLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']], // Report to moderator log. - array('int', 'pruneReportLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']), + ['int', 'pruneReportLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']], // Log of the scheduled tasks and how long they ran. - array('int', 'pruneScheduledTaskLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']), + ['int', 'pruneScheduledTaskLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']], // Log recording when search engines have crawled the forum. - array('int', 'pruneSpiderHitLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']), - ); + ['int', 'pruneSpiderHitLog', 'postinput' => Lang::$txt['days_word'], 'subtext' => Lang::$txt['zero_to_disable']], + ]; // MOD AUTHORS: If you want to add your own logs, use this hook. - IntegrationHook::call('integrate_prune_settings', array(&$config_vars, &self::$prune_toggle, false)); + IntegrationHook::call('integrate_prune_settings', [&$config_vars, &self::$prune_toggle, false]); return $config_vars; } @@ -411,8 +409,9 @@ public static function getConfigVars(): array */ public static function adminLogs($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::getConfigVars(); + } self::load(); self::$obj->execute(); @@ -427,24 +426,26 @@ public static function adminLogs($return_config = false) */ protected function __construct() { - foreach (self::$subactions as &$subaction) - { - if (isset($subaction['disabled'])) + foreach (self::$subactions as &$subaction) { + if (isset($subaction['disabled'])) { $subaction['disabled'] = empty(Config::$modSettings[$subaction['disabled']]); + } } - IntegrationHook::call('integrate_manage_logs', array(&self::$subactions)); + IntegrationHook::call('integrate_manage_logs', [&self::$subactions]); // By default, error log should be shown in descending order. - if (!isset($_REQUEST['sa'])) + if (!isset($_REQUEST['sa'])) { $_REQUEST['desc'] = true; + } - $this->subaction = isset($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]) && empty(self::$subactions[$_REQUEST['sa']]['disabled']) ? $_REQUEST['sa'] : 'errorlog'; + $this->subaction = isset($_REQUEST['sa'], self::$subactions[$_REQUEST['sa']]) && empty(self::$subactions[$_REQUEST['sa']]['disabled']) ? $_REQUEST['sa'] : 'errorlog'; } } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Logs::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Logs::exportStatic')) { Logs::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Mail.php b/Sources/Actions/Admin/Mail.php index 9e0a46431d..ca462768ec 100644 --- a/Sources/Actions/Admin/Mail.php +++ b/Sources/Actions/Admin/Mail.php @@ -13,10 +13,10 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\BackwardCompatibility; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\IntegrationHook; use SMF\ItemList; use SMF\Lang; @@ -24,7 +24,6 @@ use SMF\Theme; use SMF\User; use SMF\Utils; -use SMF\Db\DatabaseApi as Db; /** * Handles mail configuration, as well as reviewing the mail queue. @@ -38,8 +37,8 @@ class Mail implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'ManageMail', 'list_getMailQueue' => 'list_getMailQueue', 'list_getMailQueueSize' => 'list_getMailQueueSize', @@ -48,8 +47,8 @@ class Mail implements ActionInterface 'clearMailQueue' => 'ClearMailQueue', 'modifyMailSettings' => 'ModifyMailSettings', 'testMailSend' => 'TestMailSend', - ), - ); + ], + ]; /******************* * Public properties @@ -72,12 +71,12 @@ class Mail implements ActionInterface * * Available sub-actions. */ - public static array $subactions = array( + public static array $subactions = [ 'browse' => 'browse', 'clear' => 'clear', 'settings' => 'settings', 'test' => 'test', - ); + ]; /********************* * Internal properties @@ -89,7 +88,7 @@ class Mail implements ActionInterface * Processed version of Lang::$txtBirthdayEmails. * This is used internally by the settings() method. */ - protected static array $processedBirthdayEmails = array(); + protected static array $processedBirthdayEmails = []; /**************************** * Internal static properties @@ -112,10 +111,11 @@ class Mail implements ActionInterface */ public function execute(): void { - $call = method_exists($this, self::$subactions[$this->subaction]) ? array($this, self::$subactions[$this->subaction]) : Utils::getCallable(self::$subactions[$this->subaction]); + $call = method_exists($this, self::$subactions[$this->subaction]) ? [$this, self::$subactions[$this->subaction]] : Utils::getCallable(self::$subactions[$this->subaction]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } /** @@ -124,145 +124,144 @@ public function execute(): void public function browse(): void { // First, are we deleting something from the queue? - if (isset($_REQUEST['delete'])) - { + if (isset($_REQUEST['delete'])) { User::$me->checkSession(); - Db::$db->query('', ' + Db::$db->query( + '', + ' DELETE FROM {db_prefix}mail_queue WHERE id_mail IN ({array_int:mail_ids})', - array( + [ 'mail_ids' => $_REQUEST['delete'], - ) + ], ); } // How many items do we have? - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) AS queue_size, MIN(time_sent) AS oldest FROM {db_prefix}mail_queue', - array( - ) + [ + ], ); - list ($mailQueueSize, $mailOldest) = Db::$db->fetch_row($request); + list($mailQueueSize, $mailOldest) = Db::$db->fetch_row($request); Db::$db->free_result($request); Utils::$context['oldest_mail'] = empty($mailOldest) ? Lang::$txt['mailqueue_oldest_not_available'] : self::timeSince(time() - $mailOldest); Utils::$context['mail_queue_size'] = Lang::numberFormat($mailQueueSize); - $listOptions = array( + $listOptions = [ 'id' => 'mail_queue', 'title' => Lang::$txt['mailqueue_browse'], 'items_per_page' => Config::$modSettings['defaultMaxListItems'], 'base_href' => Config::$scripturl . '?action=admin;area=mailqueue', 'default_sort_col' => 'age', 'no_items_label' => Lang::$txt['mailqueue_no_items'], - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::list_getMailQueue', - ), - 'get_count' => array( + ], + 'get_count' => [ 'function' => __CLASS__ . '::list_getMailQueueSize', - ), - 'columns' => array( - 'subject' => array( - 'header' => array( + ], + 'columns' => [ + 'subject' => [ + 'header' => [ 'value' => Lang::$txt['mailqueue_subject'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return Utils::entityStrlen($rowData['subject']) > 50 ? sprintf('%1$s...', Utils::htmlspecialchars(Utils::entitySubstr($rowData['subject'], 0, 47))) : Utils::htmlspecialchars($rowData['subject']); }, 'class' => 'smalltext', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'subject', 'reverse' => 'subject DESC', - ), - ), - 'recipient' => array( - 'header' => array( + ], + ], + 'recipient' => [ + 'header' => [ 'value' => Lang::$txt['mailqueue_recipient'], - ), - 'data' => array( - 'sprintf' => array( + ], + 'data' => [ + 'sprintf' => [ 'format' => '%1$s', - 'params' => array( + 'params' => [ 'recipient' => true, - ), - ), + ], + ], 'class' => 'smalltext', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'recipient', 'reverse' => 'recipient DESC', - ), - ), - 'priority' => array( - 'header' => array( + ], + ], + 'priority' => [ + 'header' => [ 'value' => Lang::$txt['mailqueue_priority'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { // We probably have a text label with your priority. $txtKey = sprintf('mq_mpriority_%1$s', $rowData['priority']); // But if not, revert to priority 0. - return isset(Lang::$txt[$txtKey]) ? Lang::$txt[$txtKey] : Lang::$txt['mq_mpriority_1']; + return Lang::$txt[$txtKey] ?? Lang::$txt['mq_mpriority_1']; }, 'class' => 'smalltext', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'priority', 'reverse' => 'priority DESC', - ), - ), - 'age' => array( - 'header' => array( + ], + ], + 'age' => [ + 'header' => [ 'value' => Lang::$txt['mailqueue_age'], - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return self::timeSince(time() - $rowData['time_sent']); }, 'class' => 'smalltext', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'time_sent', 'reverse' => 'time_sent DESC', - ), - ), - 'check' => array( - 'header' => array( + ], + ], + 'check' => [ + 'header' => [ 'value' => '', - ), - 'data' => array( - 'function' => function($rowData) - { + ], + 'data' => [ + 'function' => function ($rowData) { return ''; }, 'class' => 'smalltext', - ), - ), - ), - 'form' => array( + ], + ], + ], + 'form' => [ 'href' => Config::$scripturl . '?action=admin;area=mailqueue', 'include_start' => true, 'include_sort' => true, - ), - 'additional_rows' => array( - array( + ], + 'additional_rows' => [ + [ 'position' => 'top_of_list', 'value' => '' . Lang::$txt['mailqueue_clear_list'] . ' ', - ), - array( + ], + [ 'position' => 'bottom_of_list', 'value' => '' . Lang::$txt['mailqueue_clear_list'] . ' ', - ), - ), - ); + ], + ], + ]; new ItemList($listOptions); @@ -278,11 +277,9 @@ public function settings(): void $config_vars = self::getConfigVars(); // Saving? - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { // Make the SMTP password a little harder to see in a backup etc. - if (!empty($_POST['smtp_password'][1])) - { + if (!empty($_POST['smtp_password'][1])) { $_POST['smtp_password'][0] = base64_encode($_POST['smtp_password'][0]); $_POST['smtp_password'][1] = base64_encode($_POST['smtp_password'][1]); } @@ -308,8 +305,8 @@ public function settings(): void var bDay = {'; $i = 0; - foreach (self::$processedBirthdayEmails as $index => $email) - { + + foreach (self::$processedBirthdayEmails as $index => $email) { $is_last = ++$i == count(self::$processedBirthdayEmails); Utils::$context['settings_insert_above'] .= ' @@ -338,28 +335,26 @@ public function clear(): void User::$me->checkSession('get'); // If we don't yet have the total to clear, find it. - if (!isset($_GET['te'])) - { + if (!isset($_GET['te'])) { // How many items do we have? - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) AS queue_size FROM {db_prefix}mail_queue', - array( - ) + [ + ], ); - list ($_GET['te']) = Db::$db->fetch_row($request); + list($_GET['te']) = Db::$db->fetch_row($request); Db::$db->free_result($request); - } - else - { + } else { $_GET['te'] = (int) $_GET['te']; } $_GET['sent'] = isset($_GET['sent']) ? (int) $_GET['sent'] : 0; // Send 50 at a time, then go for a break... - while (\SMF\Mail::reduceQueue(50, true, true) === true) - { + while (\SMF\Mail::reduceQueue(50, true, true) === true) { // Sent another 50. $_GET['sent'] += 50; $this->pauseMailQueueClear(); @@ -380,8 +375,7 @@ public function test(): void Utils::$context['post_url'] = Utils::$context['base_url'] . ';save'; // Sending the test message now. - if (isset($_GET['save'])) - { + if (isset($_GET['save'])) { // Send to the current user, no options. $to = User::$me->email; $subject = Utils::htmlspecialchars($_POST['subject']); @@ -392,8 +386,7 @@ public function test(): void } // The result. - if (isset($_GET['result'])) - { + if (isset($_GET['result'])) { Utils::$context['result'] = ($_GET['result'] == 'success' ? 'success' : 'failure'); } } @@ -409,8 +402,9 @@ public function test(): void */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -435,38 +429,38 @@ public static function getConfigVars(): array $body = Lang::$txtBirthdayEmails[(empty(Config::$modSettings['birthday_email']) ? 'happy_birthday' : Config::$modSettings['birthday_email']) . '_body']; $subject = Lang::$txtBirthdayEmails[(empty(Config::$modSettings['birthday_email']) ? 'happy_birthday' : Config::$modSettings['birthday_email']) . '_subject']; - $emails = array(); + $emails = []; - foreach (Lang::$txtBirthdayEmails as $key => $value) - { + foreach (Lang::$txtBirthdayEmails as $key => $value) { $index = substr($key, 0, strrpos($key, '_')); $element = substr($key, strrpos($key, '_') + 1); self::$processedBirthdayEmails[$index][$element] = $value; } - foreach (self::$processedBirthdayEmails as $index => $dummy) + foreach (self::$processedBirthdayEmails as $index => $dummy) { $emails[$index] = $index; + } - $config_vars = array( + $config_vars = [ // Mail queue stuff, this rocks ;) - array('int', 'mail_limit', 'subtext' => Lang::$txt['zero_to_disable']), - array('int', 'mail_quantity'), + ['int', 'mail_limit', 'subtext' => Lang::$txt['zero_to_disable']], + ['int', 'mail_quantity'], '', // SMTP stuff. - array('select', 'mail_type', array(Lang::$txt['mail_type_default'], 'SMTP', 'SMTP - STARTTLS')), - array('text', 'smtp_host'), - array('text', 'smtp_port'), - array('text', 'smtp_username'), - array('password', 'smtp_password'), + ['select', 'mail_type', [Lang::$txt['mail_type_default'], 'SMTP', 'SMTP - STARTTLS']], + ['text', 'smtp_host'], + ['text', 'smtp_port'], + ['text', 'smtp_username'], + ['password', 'smtp_password'], '', - array('select', 'birthday_email', $emails, 'value' => array('subject' => $subject, 'body' => $body), 'javascript' => 'onchange="fetch_birthday_preview()"'), - 'birthday_subject' => array('var_message', 'birthday_subject', 'var_message' => self::$processedBirthdayEmails[empty(Config::$modSettings['birthday_email']) ? 'happy_birthday' : Config::$modSettings['birthday_email']]['subject'], 'disabled' => true, 'size' => strlen($subject) + 3), - 'birthday_body' => array('var_message', 'birthday_body', 'var_message' => nl2br($body), 'disabled' => true, 'size' => ceil(strlen($body) / 25)), - ); + ['select', 'birthday_email', $emails, 'value' => ['subject' => $subject, 'body' => $body], 'javascript' => 'onchange="fetch_birthday_preview()"'], + 'birthday_subject' => ['var_message', 'birthday_subject', 'var_message' => self::$processedBirthdayEmails[empty(Config::$modSettings['birthday_email']) ? 'happy_birthday' : Config::$modSettings['birthday_email']]['subject'], 'disabled' => true, 'size' => strlen($subject) + 3], + 'birthday_body' => ['var_message', 'birthday_body', 'var_message' => nl2br($body), 'disabled' => true, 'size' => ceil(strlen($body) / 25)], + ]; - IntegrationHook::call('integrate_modify_mail_settings', array(&$config_vars)); + IntegrationHook::call('integrate_modify_mail_settings', [&$config_vars]); return $config_vars; } @@ -482,29 +476,28 @@ public static function getConfigVars(): array */ public static function list_getMailQueue($start, $items_per_page, $sort): array { - $mails = array(); + $mails = []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_mail, time_sent, recipient, priority, private, subject FROM {db_prefix}mail_queue ORDER BY {raw:sort} LIMIT {int:start}, {int:items_per_page}', - array( + [ 'start' => $start, 'sort' => $sort, 'items_per_page' => $items_per_page, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { + + while ($row = Db::$db->fetch_assoc($request)) { // Private PM/email subjects and similar shouldn't be shown in the mailbox area. - if (!empty($row['private'])) - { + if (!empty($row['private'])) { $row['subject'] = Lang::$txt['personal_message']; - } - else - { + } else { $row['subject'] = mb_decode_mimeheader($row['subject']); } @@ -524,13 +517,15 @@ public static function list_getMailQueue($start, $items_per_page, $sort): array public static function list_getMailQueueSize(): int { // How many items do we have? - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) AS queue_size FROM {db_prefix}mail_queue', - array( - ) + [ + ], ); - list ($mailQueueSize) = Db::$db->fetch_row($request); + list($mailQueueSize) = Db::$db->fetch_row($request); Db::$db->free_result($request); return $mailQueueSize; @@ -544,27 +539,28 @@ public static function list_getMailQueueSize(): int */ public static function timeSince($time_diff): string { - if ($time_diff < 0) + if ($time_diff < 0) { $time_diff = 0; + } // Just do a bit of an if fest... - if ($time_diff > 86400) - { + if ($time_diff > 86400) { $days = round($time_diff / 86400, 1); + return sprintf($days == 1 ? Lang::$txt['mq_day'] : Lang::$txt['mq_days'], $time_diff / 86400); } // Hours? - if ($time_diff > 3600) - { + if ($time_diff > 3600) { $hours = round($time_diff / 3600, 1); + return sprintf($hours == 1 ? Lang::$txt['mq_hour'] : Lang::$txt['mq_hours'], $hours); } // Minutes? - if ($time_diff > 60) - { + if ($time_diff > 60) { $minutes = (int) ($time_diff / 60); + return sprintf($minutes == 1 ? Lang::$txt['mq_minute'] : Lang::$txt['mq_minutes'], $minutes); } @@ -597,8 +593,9 @@ public static function clearMailQueue(): void */ public static function modifyMailSettings($return_config = false) { - if (!empty($return_config)) + if (!empty($return_config)) { return self::getConfigVars(); + } self::load(); self::$obj->subaction = 'settings'; @@ -633,19 +630,20 @@ protected function __construct() Utils::$context['page_title'] = Lang::$txt['mailqueue_title']; Utils::$context['sub_template'] = 'show_settings'; - IntegrationHook::call('integrate_manage_mail', array(&self::$subactions)); + IntegrationHook::call('integrate_manage_mail', [&self::$subactions]); - if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) + if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) { $this->subaction = $_REQUEST['sa']; + } Utils::$context['sub_action'] = $this->subaction; // Load up all the tabs... - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['mailqueue_title'], 'help' => '', 'description' => Lang::$txt['mailqueue_desc'], - ); + ]; } /** @@ -656,12 +654,14 @@ protected function pauseMailQueueClear(): void // Try get more time... @set_time_limit(600); - if (function_exists('apache_reset_timeout')) + if (function_exists('apache_reset_timeout')) { @apache_reset_timeout(); + } // Have we already used our maximum time? - if ((time() - TIME_START) < 5) + if ((time() - TIME_START) < 5) { return; + } Utils::$context['continue_get_data'] = '?action=admin;area=mailqueue;sa=clear;te=' . $_GET['te'] . ';sent=' . $_GET['sent'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['page_title'] = Lang::$txt['not_done_title']; @@ -683,7 +683,8 @@ protected function pauseMailQueueClear(): void } // Export public static functions and properties to global namespace for backward compatibility. -if (is_callable(__NAMESPACE__ . '\Mail::exportStatic')) +if (is_callable(__NAMESPACE__ . '\\Mail::exportStatic')) { Mail::exportStatic(); +} ?> \ No newline at end of file diff --git a/Sources/Actions/Admin/Maintenance.php b/Sources/Actions/Admin/Maintenance.php index b0b87690f5..7400593d53 100644 --- a/Sources/Actions/Admin/Maintenance.php +++ b/Sources/Actions/Admin/Maintenance.php @@ -13,11 +13,13 @@ namespace SMF\Actions\Admin; -use SMF\BackwardCompatibility; use SMF\Actions\ActionInterface; - +use SMF\Actions\TopicRemove; +use SMF\BackwardCompatibility; +use SMF\Cache\CacheApi; use SMF\Category; use SMF\Config; +use SMF\Db\DatabaseApi as Db; use SMF\Draft; use SMF\ErrorHandler; use SMF\Group; @@ -32,9 +34,6 @@ use SMF\Topic; use SMF\User; use SMF\Utils; -use SMF\Actions\TopicRemove; -use SMF\Cache\CacheApi; -use SMF\Db\DatabaseApi as Db; /** * Forum maintenance. Important stuff. @@ -48,8 +47,8 @@ class Maintenance implements ActionInterface * * BackwardCompatibility settings for this class. */ - private static $backcompat = array( - 'func_names' => array( + private static $backcompat = [ + 'func_names' => [ 'call' => 'ManageMaintenance', 'getIntegrationHooksData' => 'getIntegrationHooksData', 'reattributePosts' => 'reattributePosts', @@ -73,8 +72,8 @@ class Maintenance implements ActionInterface 'maintainMassMoveTopics' => 'MaintainMassMoveTopics', 'maintainRemoveOldPosts' => 'MaintainRemoveOldPosts', 'maintainRemoveOldDrafts' => 'MaintainRemoveOldDrafts', - ), - ); + ], + ]; /***************** * Class constants @@ -111,54 +110,54 @@ class Maintenance implements ActionInterface * * Available sub-actions. */ - public static array $subactions = array( - 'routine' => array( + public static array $subactions = [ + 'routine' => [ 'function' => 'routine', 'template' => 'maintain_routine', - 'activities' => array( + 'activities' => [ 'version' => 'version', 'repair' => 'repair', 'recount' => 'recountBoards', 'rebuild_settings' => 'rebuildSettings', 'logs' => 'emptyLogs', 'cleancache' => 'cleanCache', - ), - ), - 'database' => array( + ], + ], + 'database' => [ 'function' => 'database', 'template' => 'maintain_database', - 'activities' => array( + 'activities' => [ 'optimize' => 'optimize', 'convertentities' => 'entitiesToUnicode', 'convertmsgbody' => 'changeMsgBodyLength', - ), - ), - 'members' => array( + ], + ], + 'members' => [ 'function' => 'members', 'template' => 'maintain_members', - 'activities' => array( + 'activities' => [ 'reattribute' => 'reattribute', 'purgeinactive' => 'purgeInactiveMembers', 'recountposts' => 'recountPosts', - ), - ), - 'topics' => array( + ], + ], + 'topics' => [ 'function' => 'topics', 'template' => 'maintain_topics', - 'activities' => array( + 'activities' => [ 'massmove' => 'massMove', 'pruneold' => 'prunePosts', 'olddrafts' => 'pruneDrafts', - ), - ), - 'hooks' => array( + ], + ], + 'hooks' => [ 'function' => 'hooks', - ), - 'destroy' => array( + ], + 'destroy' => [ 'function' => 'destroy', - 'activities' => array(), - ), - ); + 'activities' => [], + ], + ]; /********************* * Internal properties @@ -187,18 +186,19 @@ class Maintenance implements ActionInterface */ public function execute(): void { - $call = method_exists($this, self::$subactions[$this->subaction]['function']) ? array($this, self::$subactions[$this->subaction]['function']) : Utils::getCallable(self::$subactions[$this->subaction]['function']); + $call = method_exists($this, self::$subactions[$this->subaction]['function']) ? [$this, self::$subactions[$this->subaction]['function']] : Utils::getCallable(self::$subactions[$this->subaction]['function']); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } // Any special activity? - if (!empty($this->activity)) - { - $call = method_exists($this, self::$subactions[$this->subaction]['activities'][$this->activity]) ? array($this, self::$subactions[$this->subaction]['activities'][$this->activity]) : Utils::getCallable(self::$subactions[$this->subaction]['activities'][$this->activity]); + if (!empty($this->activity)) { + $call = method_exists($this, self::$subactions[$this->subaction]['activities'][$this->activity]) ? [$this, self::$subactions[$this->subaction]['activities'][$this->activity]] : Utils::getCallable(self::$subactions[$this->subaction]['activities'][$this->activity]); - if (!empty($call)) + if (!empty($call)) { call_user_func($call); + } } // Create a maintenance token. Kinda hard to do it any other way. @@ -210,8 +210,7 @@ public function execute(): void */ public function routine(): void { - if (isset($_GET['done']) && in_array($_GET['done'], array('recount', 'rebuild_settings'))) - { + if (isset($_GET['done']) && in_array($_GET['done'], ['recount', 'rebuild_settings'])) { Utils::$context['maintenance_finished'] = Lang::$txt['maintain_' . $_GET['done']]; } } @@ -224,14 +223,13 @@ public function database(): void // Show some conversion options? Utils::$context['convert_entities'] = isset(Config::$modSettings['global_character_set']) && Config::$modSettings['global_character_set'] === 'UTF-8'; - if (Config::$db_type == 'mysql') - { + if (Config::$db_type == 'mysql') { $colData = Db::$db->list_columns('{db_prefix}messages', true); - foreach ($colData as $column) - { - if ($column['name'] == 'body') + foreach ($colData as $column) { + if ($column['name'] == 'body') { $body_type = $column['type']; + } } Utils::$context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text'; @@ -239,8 +237,7 @@ public function database(): void Utils::$context['convert_to_suggest'] = ($body_type != 'text' && !empty(Config::$modSettings['max_messageLength']) && Config::$modSettings['max_messageLength'] < 65536); } - if (isset($_GET['done']) && $_GET['done'] == 'convertentities') - { + if (isset($_GET['done']) && $_GET['done'] == 'convertentities') { Utils::$context['maintenance_finished'] = Lang::$txt['entity_convert_title']; } } @@ -252,16 +249,15 @@ public function members(): void { // Get membergroups - for deleting members and the like. Utils::$context['membergroups'] = array_merge( - array(new Group(Group::REGULAR, array('name' => Lang::$txt['maintain_members_ungrouped']))), + [new Group(Group::REGULAR, ['name' => Lang::$txt['maintain_members_ungrouped']])], Group::load(), ); - if (isset($_GET['done']) && $_GET['done'] == 'recountposts') - { + if (isset($_GET['done']) && $_GET['done'] == 'recountposts') { Utils::$context['maintenance_finished'] = Lang::$txt['maintain_recountposts']; } - Theme::loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest'); + Theme::loadJavaScriptFile('suggest.js', ['defer' => false, 'minimize' => true], 'smf_suggest'); } /** @@ -270,44 +266,42 @@ public function members(): void public function topics(): void { // Let's load up the boards in case they are useful. - Utils::$context['categories'] = array(); + Utils::$context['categories'] = []; - $result = Db::$db->query('order_by_board_order', ' + $result = Db::$db->query( + 'order_by_board_order', + ' SELECT b.id_board, b.name, b.child_level, c.name AS cat_name, c.id_cat FROM {db_prefix}boards AS b LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat) WHERE {query_see_board} AND redirect = {string:blank_redirect}', - array( + [ 'blank_redirect' => '', - ) + ], ); - while ($row = Db::$db->fetch_assoc($result)) - { - if (!isset(Utils::$context['categories'][$row['id_cat']])) - { - Utils::$context['categories'][$row['id_cat']] = array( + + while ($row = Db::$db->fetch_assoc($result)) { + if (!isset(Utils::$context['categories'][$row['id_cat']])) { + Utils::$context['categories'][$row['id_cat']] = [ 'name' => $row['cat_name'], - 'boards' => array() - ); + 'boards' => [], + ]; } - Utils::$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array( + Utils::$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = [ 'id' => $row['id_board'], 'name' => $row['name'], - 'child_level' => $row['child_level'] - ); + 'child_level' => $row['child_level'], + ]; } Db::$db->free_result($result); Category::sort(Utils::$context['categories']); - if (isset($_GET['done']) && $_GET['done'] == 'purgeold') - { + if (isset($_GET['done']) && $_GET['done'] == 'purgeold') { Utils::$context['maintenance_finished'] = Lang::$txt['maintain_old']; - } - elseif (isset($_GET['done']) && $_GET['done'] == 'massmove') - { + } elseif (isset($_GET['done']) && $_GET['done'] == 'massmove') { Utils::$context['maintenance_finished'] = Lang::$txt['move_topics_maintenance']; } } @@ -342,23 +336,23 @@ public function version(): void User::$me->isAllowedTo('admin_forum'); // Call the function that'll get all the version info we need. - $versionOptions = array( + $versionOptions = [ 'include_ssi' => true, 'include_subscriptions' => true, 'include_tasks' => true, 'sort_results' => true, - ); + ]; $version_info = ACP::getFileVersions($versionOptions); // Add the new info to the template context. - Utils::$context += array( + Utils::$context += [ 'file_versions' => $version_info['file_versions'], 'default_template_versions' => $version_info['default_template_versions'], 'template_versions' => $version_info['template_versions'], 'default_language_versions' => $version_info['default_language_versions'], 'default_known_languages' => array_keys($version_info['default_language_versions']), 'tasks_versions' => $version_info['tasks_versions'], - ); + ]; // Make it easier to manage for the template. Utils::$context['forum_version'] = SMF_FULL_VERSION; @@ -413,30 +407,34 @@ public function recountBoards(): void @set_time_limit(600); // Step the number of topics at a time so things don't time out... - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT MAX(id_topic) FROM {db_prefix}topics', - array( - ) + [ + ], ); - list ($max_topics) = Db::$db->fetch_row($request); + list($max_topics) = Db::$db->fetch_row($request); Db::$db->free_result($request); $increment = min(max(50, ceil($max_topics / 4)), 2000); - if (empty($_REQUEST['start'])) + + if (empty($_REQUEST['start'])) { $_REQUEST['start'] = 0; + } $total_steps = 8; // Get each topic with a wrong reply count and fix it - let's just do some at a time, though. - if (empty($_REQUEST['step'])) - { + if (empty($_REQUEST['step'])) { $_REQUEST['step'] = 0; - while ($_REQUEST['start'] < $max_topics) - { + while ($_REQUEST['start'] < $max_topics) { // Recount approved messages - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT t.id_topic, MAX(t.num_replies) AS num_replies, GREATEST(COUNT(ma.id_msg) - 1, 0) AS real_num_replies FROM {db_prefix}topics AS t @@ -445,26 +443,32 @@ public function recountBoards(): void AND t.id_topic <= {int:max_id} GROUP BY t.id_topic HAVING GREATEST(COUNT(ma.id_msg) - 1, 0) != MAX(t.num_replies)', - array( + [ 'is_approved' => 1, 'start' => $_REQUEST['start'], 'max_id' => $_REQUEST['start'] + $increment, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - Db::$db->query('', ' + + while ($row = Db::$db->fetch_assoc($request)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}topics SET num_replies = {int:num_replies} WHERE id_topic = {int:id_topic}', - array( + [ 'num_replies' => $row['real_num_replies'], 'id_topic' => $row['id_topic'], - ) + ], ); + } Db::$db->free_result($request); // Recount unapproved messages - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT t.id_topic, MAX(t.unapproved_posts) AS unapproved_posts, COUNT(mu.id_msg) AS real_unapproved_posts FROM {db_prefix}topics AS t @@ -473,28 +477,31 @@ public function recountBoards(): void AND t.id_topic <= {int:max_id} GROUP BY t.id_topic HAVING COUNT(mu.id_msg) != MAX(t.unapproved_posts)', - array( + [ 'not_approved' => 0, 'start' => $_REQUEST['start'], 'max_id' => $_REQUEST['start'] + $increment, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - Db::$db->query('', ' + + while ($row = Db::$db->fetch_assoc($request)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}topics SET unapproved_posts = {int:unapproved_posts} WHERE id_topic = {int:id_topic}', - array( + [ 'unapproved_posts' => $row['real_unapproved_posts'], 'id_topic' => $row['id_topic'], - ) + ], ); + } Db::$db->free_result($request); $_REQUEST['start'] += $increment; - if (microtime(true) - TIME_START > 3) - { + if (microtime(true) - TIME_START > 3) { Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=0;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['continue_percent'] = round((100 * $_REQUEST['start'] / $max_topics) / $total_steps); @@ -506,50 +513,56 @@ public function recountBoards(): void } // Update the post count of each board. - if ($_REQUEST['step'] <= 1) - { - if (empty($_REQUEST['start'])) - Db::$db->query('', ' + if ($_REQUEST['step'] <= 1) { + if (empty($_REQUEST['start'])) { + Db::$db->query( + '', + ' UPDATE {db_prefix}boards SET num_posts = {int:num_posts} WHERE redirect = {string:redirect}', - array( + [ 'num_posts' => 0, 'redirect' => '', - ) + ], ); + } - while ($_REQUEST['start'] < $max_topics) - { - $request = Db::$db->query('', ' + while ($_REQUEST['start'] < $max_topics) { + $request = Db::$db->query( + '', + ' SELECT m.id_board, COUNT(*) AS real_num_posts FROM {db_prefix}messages AS m WHERE m.id_topic > {int:id_topic_min} AND m.id_topic <= {int:id_topic_max} AND m.approved = {int:is_approved} GROUP BY m.id_board', - array( + [ 'id_topic_min' => $_REQUEST['start'], 'id_topic_max' => $_REQUEST['start'] + $increment, 'is_approved' => 1, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - Db::$db->query('', ' + + while ($row = Db::$db->fetch_assoc($request)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}boards SET num_posts = num_posts + {int:real_num_posts} WHERE id_board = {int:id_board}', - array( + [ 'id_board' => $row['id_board'], 'real_num_posts' => $row['real_num_posts'], - ) + ], ); + } Db::$db->free_result($request); $_REQUEST['start'] += $increment; - if (microtime(true) - TIME_START > 3) - { + if (microtime(true) - TIME_START > 3) { Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=1;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['continue_percent'] = round((200 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps); @@ -561,48 +574,54 @@ public function recountBoards(): void } // Update the topic count of each board. - if ($_REQUEST['step'] <= 2) - { - if (empty($_REQUEST['start'])) - Db::$db->query('', ' + if ($_REQUEST['step'] <= 2) { + if (empty($_REQUEST['start'])) { + Db::$db->query( + '', + ' UPDATE {db_prefix}boards SET num_topics = {int:num_topics}', - array( + [ 'num_topics' => 0, - ) + ], ); + } - while ($_REQUEST['start'] < $max_topics) - { - $request = Db::$db->query('', ' + while ($_REQUEST['start'] < $max_topics) { + $request = Db::$db->query( + '', + ' SELECT t.id_board, COUNT(*) AS real_num_topics FROM {db_prefix}topics AS t WHERE t.approved = {int:is_approved} AND t.id_topic > {int:id_topic_min} AND t.id_topic <= {int:id_topic_max} GROUP BY t.id_board', - array( + [ 'is_approved' => 1, 'id_topic_min' => $_REQUEST['start'], 'id_topic_max' => $_REQUEST['start'] + $increment, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - Db::$db->query('', ' + + while ($row = Db::$db->fetch_assoc($request)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}boards SET num_topics = num_topics + {int:real_num_topics} WHERE id_board = {int:id_board}', - array( + [ 'id_board' => $row['id_board'], 'real_num_topics' => $row['real_num_topics'], - ) + ], ); + } Db::$db->free_result($request); $_REQUEST['start'] += $increment; - if (microtime(true) - TIME_START > 3) - { + if (microtime(true) - TIME_START > 3) { Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=2;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['continue_percent'] = round((300 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps); @@ -614,48 +633,54 @@ public function recountBoards(): void } // Update the unapproved post count of each board. - if ($_REQUEST['step'] <= 3) - { - if (empty($_REQUEST['start'])) - Db::$db->query('', ' + if ($_REQUEST['step'] <= 3) { + if (empty($_REQUEST['start'])) { + Db::$db->query( + '', + ' UPDATE {db_prefix}boards SET unapproved_posts = {int:unapproved_posts}', - array( + [ 'unapproved_posts' => 0, - ) + ], ); + } - while ($_REQUEST['start'] < $max_topics) - { - $request = Db::$db->query('', ' + while ($_REQUEST['start'] < $max_topics) { + $request = Db::$db->query( + '', + ' SELECT m.id_board, COUNT(*) AS real_unapproved_posts FROM {db_prefix}messages AS m WHERE m.id_topic > {int:id_topic_min} AND m.id_topic <= {int:id_topic_max} AND m.approved = {int:is_approved} GROUP BY m.id_board', - array( + [ 'id_topic_min' => $_REQUEST['start'], 'id_topic_max' => $_REQUEST['start'] + $increment, 'is_approved' => 0, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - Db::$db->query('', ' + + while ($row = Db::$db->fetch_assoc($request)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}boards SET unapproved_posts = unapproved_posts + {int:unapproved_posts} WHERE id_board = {int:id_board}', - array( + [ 'id_board' => $row['id_board'], 'unapproved_posts' => $row['real_unapproved_posts'], - ) + ], ); + } Db::$db->free_result($request); $_REQUEST['start'] += $increment; - if (microtime(true) - TIME_START > 3) - { + if (microtime(true) - TIME_START > 3) { Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=3;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['continue_percent'] = round((400 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps); @@ -667,48 +692,54 @@ public function recountBoards(): void } // Update the unapproved topic count of each board. - if ($_REQUEST['step'] <= 4) - { - if (empty($_REQUEST['start'])) - Db::$db->query('', ' + if ($_REQUEST['step'] <= 4) { + if (empty($_REQUEST['start'])) { + Db::$db->query( + '', + ' UPDATE {db_prefix}boards SET unapproved_topics = {int:unapproved_topics}', - array( + [ 'unapproved_topics' => 0, - ) + ], ); + } - while ($_REQUEST['start'] < $max_topics) - { - $request = Db::$db->query('', ' + while ($_REQUEST['start'] < $max_topics) { + $request = Db::$db->query( + '', + ' SELECT t.id_board, COUNT(*) AS real_unapproved_topics FROM {db_prefix}topics AS t WHERE t.approved = {int:is_approved} AND t.id_topic > {int:id_topic_min} AND t.id_topic <= {int:id_topic_max} GROUP BY t.id_board', - array( + [ 'is_approved' => 0, 'id_topic_min' => $_REQUEST['start'], 'id_topic_max' => $_REQUEST['start'] + $increment, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - Db::$db->query('', ' + + while ($row = Db::$db->fetch_assoc($request)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}boards SET unapproved_topics = unapproved_topics + {int:real_unapproved_topics} WHERE id_board = {int:id_board}', - array( + [ 'id_board' => $row['id_board'], 'real_unapproved_topics' => $row['real_unapproved_topics'], - ) + ], ); + } Db::$db->free_result($request); $_REQUEST['start'] += $increment; - if (microtime(true) - TIME_START > 3) - { + if (microtime(true) - TIME_START > 3) { Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=4;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['continue_percent'] = round((500 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps); @@ -720,41 +751,47 @@ public function recountBoards(): void } // Get all members with wrong number of personal messages. - if ($_REQUEST['step'] <= 5) - { - $request = Db::$db->query('', ' + if ($_REQUEST['step'] <= 5) { + $request = Db::$db->query( + '', + ' SELECT mem.id_member, COUNT(pmr.id_pm) AS real_num, MAX(mem.instant_messages) AS instant_messages FROM {db_prefix}members AS mem LEFT JOIN {db_prefix}pm_recipients AS pmr ON (mem.id_member = pmr.id_member AND pmr.deleted = {int:is_not_deleted}) GROUP BY mem.id_member HAVING COUNT(pmr.id_pm) != MAX(mem.instant_messages)', - array( + [ 'is_not_deleted' => 0, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - User::updateMemberData($row['id_member'], array('instant_messages' => $row['real_num'])); + + while ($row = Db::$db->fetch_assoc($request)) { + User::updateMemberData($row['id_member'], ['instant_messages' => $row['real_num']]); + } Db::$db->free_result($request); - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT mem.id_member, COUNT(pmr.id_pm) AS real_num, MAX(mem.unread_messages) AS unread_messages FROM {db_prefix}members AS mem LEFT JOIN {db_prefix}pm_recipients AS pmr ON (mem.id_member = pmr.id_member AND pmr.deleted = {int:is_not_deleted} AND pmr.is_read = {int:is_not_read}) GROUP BY mem.id_member HAVING COUNT(pmr.id_pm) != MAX(mem.unread_messages)', - array( + [ 'is_not_deleted' => 0, 'is_not_read' => 0, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - User::updateMemberData($row['id_member'], array('unread_messages' => $row['real_num'])); + + while ($row = Db::$db->fetch_assoc($request)) { + User::updateMemberData($row['id_member'], ['unread_messages' => $row['real_num']]); + } Db::$db->free_result($request); - if (microtime(true) - TIME_START > 3) - { + if (microtime(true) - TIME_START > 3) { Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=0;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['continue_percent'] = round(700 / $total_steps); @@ -763,42 +800,46 @@ public function recountBoards(): void } // Any messages pointing to the wrong board? - if ($_REQUEST['step'] <= 6) - { - while ($_REQUEST['start'] < Config::$modSettings['maxMsgID']) - { - $request = Db::$db->query('', ' + if ($_REQUEST['step'] <= 6) { + while ($_REQUEST['start'] < Config::$modSettings['maxMsgID']) { + $request = Db::$db->query( + '', + ' SELECT t.id_board, m.id_msg FROM {db_prefix}messages AS m INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic AND t.id_board != m.id_board) WHERE m.id_msg > {int:id_msg_min} AND m.id_msg <= {int:id_msg_max}', - array( + [ 'id_msg_min' => $_REQUEST['start'], 'id_msg_max' => $_REQUEST['start'] + $increment, - ) + ], ); - $boards = array(); - while ($row = Db::$db->fetch_assoc($request)) + $boards = []; + + while ($row = Db::$db->fetch_assoc($request)) { $boards[$row['id_board']][] = $row['id_msg']; + } Db::$db->free_result($request); - foreach ($boards as $board_id => $messages) - Db::$db->query('', ' + foreach ($boards as $board_id => $messages) { + Db::$db->query( + '', + ' UPDATE {db_prefix}messages SET id_board = {int:id_board} WHERE id_msg IN ({array_int:id_msg_array})', - array( + [ 'id_msg_array' => $messages, 'id_board' => $board_id, - ) + ], ); + } $_REQUEST['start'] += $increment; - if (microtime(true) - TIME_START > 3) - { + if (microtime(true) - TIME_START > 3) { Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['continue_percent'] = round((700 + 100 * $_REQUEST['start'] / Config::$modSettings['maxMsgID']) / $total_steps); @@ -810,65 +851,77 @@ public function recountBoards(): void } // Update the latest message of each board. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT m.id_board, MAX(m.id_msg) AS local_last_msg FROM {db_prefix}messages AS m WHERE m.approved = {int:is_approved} GROUP BY m.id_board', - array( + [ 'is_approved' => 1, - ) + ], ); - $realBoardCounts = array(); - while ($row = Db::$db->fetch_assoc($request)) + $realBoardCounts = []; + + while ($row = Db::$db->fetch_assoc($request)) { $realBoardCounts[$row['id_board']] = $row['local_last_msg']; + } Db::$db->free_result($request); - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_board, id_parent, id_last_msg, child_level, id_msg_updated FROM {db_prefix}boards', - array( - ) + [ + ], ); - $resort_me = array(); - while ($row = Db::$db->fetch_assoc($request)) - { - $row['local_last_msg'] = isset($realBoardCounts[$row['id_board']]) ? $realBoardCounts[$row['id_board']] : 0; + $resort_me = []; + + while ($row = Db::$db->fetch_assoc($request)) { + $row['local_last_msg'] = $realBoardCounts[$row['id_board']] ?? 0; $resort_me[$row['child_level']][] = $row; } Db::$db->free_result($request); krsort($resort_me); - $lastModifiedMsg = array(); - foreach ($resort_me as $rows) - foreach ($rows as $row) - { + $lastModifiedMsg = []; + + foreach ($resort_me as $rows) { + foreach ($rows as $row) { // The latest message is the latest of the current board and its children. - if (isset($lastModifiedMsg[$row['id_board']])) + if (isset($lastModifiedMsg[$row['id_board']])) { $curLastModifiedMsg = max($row['local_last_msg'], $lastModifiedMsg[$row['id_board']]); - else + } else { $curLastModifiedMsg = $row['local_last_msg']; + } // If what is and what should be the latest message differ, an update is necessary. - if ($row['local_last_msg'] != $row['id_last_msg'] || $curLastModifiedMsg != $row['id_msg_updated']) - Db::$db->query('', ' + if ($row['local_last_msg'] != $row['id_last_msg'] || $curLastModifiedMsg != $row['id_msg_updated']) { + Db::$db->query( + '', + ' UPDATE {db_prefix}boards SET id_last_msg = {int:id_last_msg}, id_msg_updated = {int:id_msg_updated} WHERE id_board = {int:id_board}', - array( + [ 'id_last_msg' => $row['local_last_msg'], 'id_msg_updated' => $curLastModifiedMsg, 'id_board' => $row['id_board'], - ) + ], ); + } // Parent boards inherit the latest modified message of their children. - if (isset($lastModifiedMsg[$row['id_parent']])) + if (isset($lastModifiedMsg[$row['id_parent']])) { $lastModifiedMsg[$row['id_parent']] = max($row['local_last_msg'], $lastModifiedMsg[$row['id_parent']]); - else + } else { $lastModifiedMsg[$row['id_parent']] = $row['local_last_msg']; + } } + } // Update all the basic statistics. Logging::updateStats('member'); @@ -888,7 +941,7 @@ public function rebuildSettings(): void { User::$me->isAllowedTo('admin_forum'); - Config::updateSettingsFile(array(), false, true); + Config::updateSettingsFile([], false, true); Utils::redirectexit('action=admin;area=maintain;sa=routine;done=rebuild_settings'); } @@ -927,7 +980,7 @@ public function emptyLogs(): void Db::$db->query('truncate_table', ' TRUNCATE {db_prefix}log_search_results'); - Config::updateModSettings(array('search_pointer' => 0)); + Config::updateModSettings(['search_pointer' => 0]); Utils::$context['maintenance_finished'] = Lang::$txt['maintain_logs']; } @@ -961,10 +1014,11 @@ public function optimize(): void User::$me->checkSession('request'); - if (!isset($_SESSION['optimized_tables'])) + if (!isset($_SESSION['optimized_tables'])) { SecurityToken::validate('admin-maint'); - else + } else { SecurityToken::validate('admin-optimize', 'post', false); + } ignore_user_abort(true); @@ -978,14 +1032,18 @@ public function optimize(): void // Get a list of tables, as well as how many there are. $temp_tables = Db::$db->list_tables(false, $real_prefix . '%'); - $tables = array(); - foreach ($temp_tables as $table) - $tables[] = array('table_name' => $table); + $tables = []; + + foreach ($temp_tables as $table) { + $tables[] = ['table_name' => $table]; + } // If there aren't any tables then I believe that would mean the world has exploded... Utils::$context['num_tables'] = count($tables); - if (Utils::$context['num_tables'] == 0) + + if (Utils::$context['num_tables'] == 0) { ErrorHandler::fatal('You appear to be running SMF in a flat file mode... fantastic!', false); + } $_REQUEST['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start']; @@ -993,15 +1051,15 @@ public function optimize(): void @set_time_limit(100); // For each table.... - $_SESSION['optimized_tables'] = !empty($_SESSION['optimized_tables']) ? $_SESSION['optimized_tables'] : array(); - for ($key = $_REQUEST['start']; Utils::$context['num_tables'] - 1; $key++) - { - if (empty($tables[$key])) + $_SESSION['optimized_tables'] = !empty($_SESSION['optimized_tables']) ? $_SESSION['optimized_tables'] : []; + + for ($key = $_REQUEST['start']; Utils::$context['num_tables'] - 1; $key++) { + if (empty($tables[$key])) { break; + } // Continue? - if (microtime(true) - TIME_START > 10) - { + if (microtime(true) - TIME_START > 10) { $_REQUEST['start'] = $key; Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=optimize;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['continue_percent'] = round(100 * $_REQUEST['start'] / Utils::$context['num_tables']); @@ -1011,8 +1069,9 @@ public function optimize(): void SecurityToken::create('admin-optimize'); Utils::$context['continue_post_data'] = ''; - if (function_exists('apache_reset_timeout')) + if (function_exists('apache_reset_timeout')) { apache_reset_timeout(); + } return; } @@ -1020,11 +1079,12 @@ public function optimize(): void // Optimize the table! We use backticks here because it might be a custom table. $data_freed = Db::$db->optimize_table($tables[$key]['table_name']); - if ($data_freed > 0) - $_SESSION['optimized_tables'][] = array( + if ($data_freed > 0) { + $_SESSION['optimized_tables'][] = [ 'name' => $tables[$key]['table_name'], 'data_freed' => $data_freed, - ); + ]; + } } // Number of tables, etc... @@ -1050,8 +1110,9 @@ public function entitiesToUnicode(): void User::$me->isAllowedTo('admin_forum'); // Check to see if UTF-8 is currently the default character set. - if (Config::$modSettings['global_character_set'] !== 'UTF-8') + if (Config::$modSettings['global_character_set'] !== 'UTF-8') { ErrorHandler::fatalLang('entity_convert_only_utf8'); + } // Some starting values. Utils::$context['table'] = empty($_REQUEST['table']) ? 0 : (int) $_REQUEST['table']; @@ -1063,12 +1124,12 @@ public function entitiesToUnicode(): void Utils::$context['last_step'] = false; // The first step is just a text screen with some explanation. - if (Utils::$context['first_step']) - { + if (Utils::$context['first_step']) { SecurityToken::validate('admin-maint'); SecurityToken::create('admin-maint'); Utils::$context['sub_template'] = 'convert_entities'; + return; } // Otherwise use the generic "not done" template. @@ -1083,7 +1144,7 @@ public function entitiesToUnicode(): void Utils::$context['not_done_token'] = 'admin-maint'; // A list of tables ready for conversion. - $tables = array( + $tables = [ 'ban_groups', 'ban_items', 'boards', @@ -1103,71 +1164,85 @@ public function entitiesToUnicode(): void 'poll_choices', 'smileys', 'themes', - ); + ]; Utils::$context['num_tables'] = count($tables); // Loop through all tables that need converting. - for (; Utils::$context['table'] < Utils::$context['num_tables']; Utils::$context['table']++) - { + for (; Utils::$context['table'] < Utils::$context['num_tables']; Utils::$context['table']++) { $cur_table = $tables[Utils::$context['table']]; $primary_key = ''; // Make sure we keep stuff unique! - $primary_keys = array(); + $primary_keys = []; - if (function_exists('apache_reset_timeout')) + if (function_exists('apache_reset_timeout')) { @apache_reset_timeout(); + } // Get a list of text columns. - $columns = array(); - if (Config::$db_type == 'postgresql') - $request = Db::$db->query('', ' + $columns = []; + + if (Config::$db_type == 'postgresql') { + $request = Db::$db->query( + '', + ' SELECT column_name "Field", data_type "Type" FROM information_schema.columns WHERE table_name = {string:cur_table} AND (data_type = \'character varying\' or data_type = \'text\')', - array( + [ 'cur_table' => Db::$db->prefix . $cur_table, - ) + ], ); - else - $request = Db::$db->query('', ' + } else { + $request = Db::$db->query( + '', + ' SHOW FULL COLUMNS FROM {db_prefix}{raw:cur_table}', - array( + [ 'cur_table' => $cur_table, - ) + ], ); - while ($column_info = Db::$db->fetch_assoc($request)) - if (strpos($column_info['Type'], 'text') !== false || strpos($column_info['Type'], 'char') !== false) + } + + while ($column_info = Db::$db->fetch_assoc($request)) { + if (strpos($column_info['Type'], 'text') !== false || strpos($column_info['Type'], 'char') !== false) { $columns[] = strtolower($column_info['Field']); + } + } // Get the column with the (first) primary key. - if (Config::$db_type == 'postgresql') - $request = Db::$db->query('', ' + if (Config::$db_type == 'postgresql') { + $request = Db::$db->query( + '', + ' SELECT a.attname "Column_name", \'PRIMARY\' "Key_name", attnum "Seq_in_index" FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) WHERE i.indrelid = {string:cur_table}::regclass AND i.indisprimary', - array( + [ 'cur_table' => Db::$db->prefix . $cur_table, - ) + ], ); - else - $request = Db::$db->query('', ' + } else { + $request = Db::$db->query( + '', + ' SHOW KEYS FROM {db_prefix}{raw:cur_table}', - array( + [ 'cur_table' => $cur_table, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { - if ($row['Key_name'] === 'PRIMARY') - { - if ((empty($primary_key) || $row['Seq_in_index'] == 1) && !in_array(strtolower($row['Column_name']), $columns)) + } + + while ($row = Db::$db->fetch_assoc($request)) { + if ($row['Key_name'] === 'PRIMARY') { + if ((empty($primary_key) || $row['Seq_in_index'] == 1) && !in_array(strtolower($row['Column_name']), $columns)) { $primary_key = $row['Column_name']; + } $primary_keys[] = $row['Column_name']; } @@ -1176,80 +1251,89 @@ public function entitiesToUnicode(): void // No primary key, no glory. // Same for columns. Just to be sure we've work to do! - if (empty($primary_key) || empty($columns)) + if (empty($primary_key) || empty($columns)) { continue; + } // Get the maximum value for the primary key. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT MAX({identifier:key}) FROM {db_prefix}{raw:cur_table}', - array( + [ 'key' => $primary_key, 'cur_table' => $cur_table, - ) + ], ); list($max_value) = Db::$db->fetch_row($request); Db::$db->free_result($request); - if (empty($max_value)) + if (empty($max_value)) { continue; + } - while (Utils::$context['start'] <= $max_value) - { + while (Utils::$context['start'] <= $max_value) { // Retrieve a list of rows that has at least one entity to convert. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT {raw:primary_keys}, {raw:columns} FROM {db_prefix}{raw:cur_table} WHERE {raw:primary_key} BETWEEN {int:start} AND {int:start} + 499 AND {raw:like_compare} LIMIT 500', - array( + [ 'primary_keys' => implode(', ', $primary_keys), 'columns' => implode(', ', $columns), 'cur_table' => $cur_table, 'primary_key' => $primary_key, 'start' => Utils::$context['start'], 'like_compare' => '(' . implode(' LIKE \'%&#%\' OR ', $columns) . ' LIKE \'%&#%\')', - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) - { - $insertion_variables = array(); - $changes = array(); - foreach ($row as $column_name => $column_value) - if ($column_name !== $primary_key && strpos($column_value, '&#') !== false) - { + + while ($row = Db::$db->fetch_assoc($request)) { + $insertion_variables = []; + $changes = []; + + foreach ($row as $column_name => $column_value) { + if ($column_name !== $primary_key && strpos($column_value, '&#') !== false) { $changes[] = $column_name . ' = {string:changes_' . $column_name . '}'; $insertion_variables['changes_' . $column_name] = Utils::entityDecode($column_value); } + } - $where = array(); - foreach ($primary_keys as $key) - { + $where = []; + + foreach ($primary_keys as $key) { $where[] = $key . ' = {string:where_' . $key . '}'; $insertion_variables['where_' . $key] = $row[$key]; } // Update the row. - if (!empty($changes)) - Db::$db->query('', ' + if (!empty($changes)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}' . $cur_table . ' SET ' . implode(', ', $changes) . ' WHERE ' . implode(' AND ', $where), - $insertion_variables + $insertion_variables, ); + } } Db::$db->free_result($request); Utils::$context['start'] += 500; // After ten seconds interrupt. - if (time() - Utils::$context['start_time'] > 10) - { + if (time() - Utils::$context['start_time'] > 10) { // Calculate an approximation of the percentage done. Utils::$context['continue_percent'] = round(100 * (Utils::$context['table'] + (Utils::$context['start'] / $max_value)) / Utils::$context['num_tables'], 1); Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=convertentities;table=' . Utils::$context['table'] . ';start=' . Utils::$context['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; + return; } } @@ -1278,35 +1362,43 @@ public function changeMsgBodyLength(): void // Show me your badge! User::$me->isAllowedTo('admin_forum'); - if (Config::$db_type != 'mysql') + if (Config::$db_type != 'mysql') { return; + } $colData = Db::$db->list_columns('{db_prefix}messages', true); - foreach ($colData as $column) - if ($column['name'] == 'body') + + foreach ($colData as $column) { + if ($column['name'] == 'body') { $body_type = $column['type']; + } + } Utils::$context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text'; - if ($body_type == 'text' || ($body_type != 'text' && isset($_POST['do_conversion']))) - { + if ($body_type == 'text' || ($body_type != 'text' && isset($_POST['do_conversion']))) { User::$me->checkSession(); SecurityToken::validate('admin-maint'); // Make it longer so we can do their limit. - if ($body_type == 'text') - Db::$db->change_column('{db_prefix}messages', 'body', array('type' => 'mediumtext')); + if ($body_type == 'text') { + Db::$db->change_column('{db_prefix}messages', 'body', ['type' => 'mediumtext']); + } // Shorten the column so we can have a bit (literally per record) less space occupied - else - Db::$db->change_column('{db_prefix}messages', 'body', array('type' => 'text')); + else { + Db::$db->change_column('{db_prefix}messages', 'body', ['type' => 'text']); + } // 3rd party integrations may be interested in knowning about this. - IntegrationHook::call('integrate_convert_msgbody', array($body_type)); + IntegrationHook::call('integrate_convert_msgbody', [$body_type]); $colData = Db::$db->list_columns('{db_prefix}messages', true); - foreach ($colData as $column) - if ($column['name'] == 'body') + + foreach ($colData as $column) { + if ($column['name'] == 'body') { $body_type = $column['type']; + } + } Utils::$context['maintenance_finished'] = Lang::$txt[Utils::$context['convert_to'] . '_title']; Utils::$context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text'; @@ -1314,25 +1406,29 @@ public function changeMsgBodyLength(): void return; } - elseif ($body_type != 'text' && (!isset($_POST['do_conversion']) || isset($_POST['cont']))) - { + + if ($body_type != 'text' && (!isset($_POST['do_conversion']) || isset($_POST['cont']))) { User::$me->checkSession(); - if (empty($_REQUEST['start'])) + + if (empty($_REQUEST['start'])) { SecurityToken::validate('admin-maint'); - else + } else { SecurityToken::validate('admin-convertMsg'); + } Utils::$context['page_title'] = Lang::$txt['not_done_title']; Utils::$context['continue_post_data'] = ''; Utils::$context['continue_countdown'] = 3; Utils::$context['sub_template'] = 'not_done'; $increment = 500; - $id_msg_exceeding = isset($_POST['id_msg_exceeding']) ? explode(',', $_POST['id_msg_exceeding']) : array(); + $id_msg_exceeding = isset($_POST['id_msg_exceeding']) ? explode(',', $_POST['id_msg_exceeding']) : []; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) as count FROM {db_prefix}messages', - array() + [], ); list($max_msgs) = Db::$db->fetch_row($request); Db::$db->free_result($request); @@ -1340,26 +1436,28 @@ public function changeMsgBodyLength(): void // Try for as much time as possible. @set_time_limit(600); - while ($_REQUEST['start'] < $max_msgs) - { - $request = Db::$db->query('', ' + while ($_REQUEST['start'] < $max_msgs) { + $request = Db::$db->query( + '', + ' SELECT id_msg FROM {db_prefix}messages WHERE id_msg BETWEEN {int:start} AND {int:start} + {int:increment} AND LENGTH(body) > 65535', - array( + [ 'start' => $_REQUEST['start'], 'increment' => $increment - 1, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) + + while ($row = Db::$db->fetch_assoc($request)) { $id_msg_exceeding[] = $row['id_msg']; + } Db::$db->free_result($request); $_REQUEST['start'] += $increment; - if (microtime(true) - TIME_START > 3) - { + if (microtime(true) - TIME_START > 3) { SecurityToken::create('admin-convertMsg'); Utils::$context['continue_post_data'] = ' @@ -1376,27 +1474,29 @@ public function changeMsgBodyLength(): void Utils::$context['page_title'] = Lang::$txt[Utils::$context['convert_to'] . '_title']; Utils::$context['sub_template'] = 'convert_msgbody'; - if (!empty($id_msg_exceeding)) - { - if (count($id_msg_exceeding) > 100) - { + if (!empty($id_msg_exceeding)) { + if (count($id_msg_exceeding) > 100) { $query_msg = array_slice($id_msg_exceeding, 0, 100); Utils::$context['exceeding_messages_morethan'] = sprintf(Lang::$txt['exceeding_messages_morethan'], count($id_msg_exceeding)); - } - else + } else { $query_msg = $id_msg_exceeding; + } - Utils::$context['exceeding_messages'] = array(); - $request = Db::$db->query('', ' + Utils::$context['exceeding_messages'] = []; + $request = Db::$db->query( + '', + ' SELECT id_msg, id_topic, subject FROM {db_prefix}messages WHERE id_msg IN ({array_int:messages})', - array( + [ 'messages' => $query_msg, - ) + ], ); - while ($row = Db::$db->fetch_assoc($request)) + + while ($row = Db::$db->fetch_assoc($request)) { Utils::$context['exceeding_messages'][] = '' . $row['subject'] . ''; + } Db::$db->free_result($request); } } @@ -1412,8 +1512,9 @@ public function reattribute(): void // Find the member. $members = User::find($_POST['to']); - if (empty($members)) + if (empty($members)) { ErrorHandler::fatalLang('reattribute_cannot_find_member'); + } $memID = array_shift($members); $memID = $memID['id']; @@ -1435,40 +1536,37 @@ public function reattribute(): void public function purgeInactiveMembers(): void { $_POST['maxdays'] = empty($_POST['maxdays']) ? 0 : (int) $_POST['maxdays']; - if (!empty($_POST['groups']) && $_POST['maxdays'] > 0) - { + + if (!empty($_POST['groups']) && $_POST['maxdays'] > 0) { User::$me->checkSession(); SecurityToken::validate('admin-maint'); - $groups = array(); - foreach ($_POST['groups'] as $id => $dummy) + $groups = []; + + foreach ($_POST['groups'] as $id => $dummy) { $groups[] = (int) $id; + } $time_limit = (time() - ($_POST['maxdays'] * 24 * 3600)); - $where_vars = array( + $where_vars = [ 'time_limit' => $time_limit, - ); - if ($_POST['del_type'] == 'activated') - { + ]; + + if ($_POST['del_type'] == 'activated') { $where = 'mem.date_registered < {int:time_limit} AND mem.is_activated = {int:is_activated}'; $where_vars['is_activated'] = 0; - } - else + } else { $where = 'mem.last_login < {int:time_limit} AND (mem.last_login != 0 OR mem.date_registered < {int:time_limit})'; + } // Need to get all groups then work out which (if any) we avoid. - foreach (Group::loadSimple(Group::LOAD_BOTH, array(Group::GUEST, Group::MOD)) as $group) - { + foreach (Group::loadSimple(Group::LOAD_BOTH, [Group::GUEST, Group::MOD]) as $group) { // Avoid this one? - if (!in_array($group->id, $groups)) - { + if (!in_array($group->id, $groups)) { // Post group? - if ($group->min_posts != -1) - { + if ($group->min_posts != -1) { $where .= ' AND mem.id_post_group != {int:id_post_group_' . $group->id . '}'; $where_vars['id_post_group_' . $group->id] = $group->id; - } - else - { + } else { $where .= ' AND mem.id_group != {int:id_group_' . $group->id . '} AND FIND_IN_SET({int:id_group_' . $group->id . '}, mem.additional_groups) = 0'; $where_vars['id_group_' . $group->id] = $group->id; } @@ -1476,25 +1574,27 @@ public function purgeInactiveMembers(): void } // If we have ungrouped unselected we need to avoid those guys. - if (!in_array(0, $groups)) - { + if (!in_array(0, $groups)) { $where .= ' AND (mem.id_group != 0 OR mem.additional_groups != {string:blank_add_groups})'; $where_vars['blank_add_groups'] = ''; } // Select all the members we're about to murder/remove... - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT mem.id_member, COALESCE(m.id_member, 0) AS is_mod FROM {db_prefix}members AS mem LEFT JOIN {db_prefix}moderators AS m ON (m.id_member = mem.id_member) WHERE ' . $where, - $where_vars + $where_vars, ); - $members = array(); - while ($row = Db::$db->fetch_assoc($request)) - { - if (!$row['is_mod'] || !in_array(3, $groups)) + $members = []; + + while ($row = Db::$db->fetch_assoc($request)) { + if (!$row['is_mod'] || !in_array(3, $groups)) { $members[] = $row['id_member']; + } } Db::$db->free_result($request); @@ -1540,29 +1640,32 @@ public function recountPosts(): void @set_time_limit(600); // Only run this query if we don't have the total number of members that have posted - if (!isset($_SESSION['total_members'])) - { + if (!isset($_SESSION['total_members'])) { SecurityToken::validate('admin-maint'); - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(DISTINCT m.id_member) FROM {db_prefix}messages AS m JOIN {db_prefix}boards AS b on m.id_board = b.id_board WHERE m.id_member != 0 AND b.count_posts = 0', - array( - ) + [ + ], ); // save it so we don't do this again for this task - list ($_SESSION['total_members']) = Db::$db->fetch_row($request); + list($_SESSION['total_members']) = Db::$db->fetch_row($request); Db::$db->free_result($request); - } - else + } else { SecurityToken::validate('admin-recountposts'); + } // Lets get a group of members and determine their post count (from the boards that have post count enabled of course). - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT m.id_member, COUNT(*) AS posts FROM {db_prefix}messages AS m INNER JOIN {db_prefix}boards AS b ON m.id_board = b.id_board @@ -1571,33 +1674,33 @@ public function recountPosts(): void ' . (!empty(Config::$modSettings['recycle_enable']) ? ' AND b.id_board != {int:recycle}' : '') . ' GROUP BY m.id_member LIMIT {int:start}, {int:number}', - array( + [ 'start' => $_REQUEST['start'], 'number' => $increment, 'recycle' => Config::$modSettings['recycle_board'], 'zero' => 0, - ) + ], ); $total_rows = Db::$db->num_rows($request); // Update the post count for this group - while ($row = Db::$db->fetch_assoc($request)) - { - Db::$db->query('', ' + while ($row = Db::$db->fetch_assoc($request)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}members SET posts = {int:posts} WHERE id_member = {int:row}', - array( + [ 'row' => $row['id_member'], 'posts' => $row['posts'], - ) + ], ); } Db::$db->free_result($request); // Continue? - if ($total_rows == $increment) - { + if ($total_rows == $increment) { $_REQUEST['start'] += $increment; Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=members;activity=recountposts;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; Utils::$context['continue_percent'] = round(100 * $_REQUEST['start'] / $_SESSION['total_members']); @@ -1605,14 +1708,18 @@ public function recountPosts(): void SecurityToken::create('admin-recountposts'); Utils::$context['continue_post_data'] = ''; - if (function_exists('apache_reset_timeout')) + if (function_exists('apache_reset_timeout')) { apache_reset_timeout(); + } + return; } // final steps ... made more difficult since we don't yet support sub-selects on joins // place all members who have posts in the message table in a temp table - $createTemporary = Db::$db->query('', ' + $createTemporary = Db::$db->query( + '', + ' CREATE TEMPORARY TABLE {db_prefix}tmp_maint_recountposts ( id_member mediumint(8) unsigned NOT NULL default {string:string_zero}, PRIMARY KEY (id_member) @@ -1624,40 +1731,42 @@ public function recountPosts(): void AND b.count_posts = {int:zero} ' . (!empty(Config::$modSettings['recycle_enable']) ? ' AND b.id_board != {int:recycle}' : '') . ' GROUP BY m.id_member', - array( + [ 'zero' => 0, 'string_zero' => '0', 'db_error_skip' => true, 'recycle' => !empty(Config::$modSettings['recycle_board']) ? Config::$modSettings['recycle_board'] : 0, - ) + ], ) !== false; - if ($createTemporary) - { + if ($createTemporary) { // outer join the members table on the temporary table finding the members that have a post count but no posts in the message table - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT mem.id_member, mem.posts FROM {db_prefix}members AS mem LEFT OUTER JOIN {db_prefix}tmp_maint_recountposts AS res ON res.id_member = mem.id_member WHERE res.id_member IS null AND mem.posts != {int:zero}', - array( + [ 'zero' => 0, - ) + ], ); // set the post count to zero for any delinquents we may have found - while ($row = Db::$db->fetch_assoc($request)) - { - Db::$db->query('', ' + while ($row = Db::$db->fetch_assoc($request)) { + Db::$db->query( + '', + ' UPDATE {db_prefix}members SET posts = {int:zero} WHERE id_member = {int:row}', - array( + [ 'row' => $row['id_member'], 'zero' => 0, - ) + ], ); } Db::$db->free_result($request); @@ -1699,93 +1808,95 @@ public function massMove(): void $sticky = isset($_POST['move_type_sticky']) || isset($_GET['sticky']); // No boards then this is your stop. - if (empty($id_board_from) || empty($id_board_to)) + if (empty($id_board_from) || empty($id_board_to)) { return; + } // The big WHERE clause $conditions = 'WHERE t.id_board = {int:id_board_from} AND m.icon != {string:moved}'; // DB parameters - $params = array( + $params = [ 'id_board_from' => $id_board_from, 'moved' => 'moved', - ); + ]; // Only moving topics not posted in for x days? - if (!empty($max_days)) - { + if (!empty($max_days)) { $conditions .= ' AND m.poster_time < {int:poster_time}'; $params['poster_time'] = time() - 3600 * 24 * $max_days; } // Moving locked topics? - if ($locked) - { + if ($locked) { $conditions .= ' AND t.locked = {int:locked}'; $params['locked'] = 1; } // What about sticky topics? - if ($sticky) - { + if ($sticky) { $conditions .= ' AND t.is_sticky = {int:sticky}'; $params['sticky'] = 1; } // How many topics are we converting? - if (!isset($_REQUEST['totaltopics'])) - { - $request = Db::$db->query('', ' + if (!isset($_REQUEST['totaltopics'])) { + $request = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}topics AS t INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_last_msg)' . $conditions, - $params + $params, ); - list ($total_topics) = Db::$db->fetch_row($request); + list($total_topics) = Db::$db->fetch_row($request); Db::$db->free_result($request); - } - else + } else { $total_topics = (int) $_REQUEST['totaltopics']; + } // Seems like we need this here. Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=topics;activity=massmove;id_board_from=' . $id_board_from . ';id_board_to=' . $id_board_to . ';totaltopics=' . $total_topics . ';max_days=' . $max_days; - if ($locked) + if ($locked) { Utils::$context['continue_get_data'] .= ';locked'; + } - if ($sticky) + if ($sticky) { Utils::$context['continue_get_data'] .= ';sticky'; + } Utils::$context['continue_get_data'] .= ';start=' . Utils::$context['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; // We have topics to move so start the process. - if (!empty($total_topics)) - { - while (Utils::$context['start'] <= $total_topics) - { + if (!empty($total_topics)) { + while (Utils::$context['start'] <= $total_topics) { // Lets get the topics. - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT t.id_topic FROM {db_prefix}topics AS t INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_last_msg) ' . $conditions . ' LIMIT 10', - $params + $params, ); // Get the ids. - $topics = array(); - while ($row = Db::$db->fetch_assoc($request)) + $topics = []; + + while ($row = Db::$db->fetch_assoc($request)) { $topics[] = $row['id_topic']; + } // Just return if we don't have any topics left to move. - if (empty($topics)) - { + if (empty($topics)) { CacheApi::put('board-' . $id_board_from, null, 120); CacheApi::put('board-' . $id_board_to, null, 120); Utils::redirectexit('action=admin;area=maintain;sa=topics;done=massmove'); @@ -1798,8 +1909,7 @@ public function massMove(): void Utils::$context['start'] += 10; // Lets wait a while. - if (time() - Utils::$context['start_time'] > 3) - { + if (time() - Utils::$context['start_time'] > 3) { // What's the percent? Utils::$context['continue_percent'] = round(100 * (Utils::$context['start'] / $total_topics), 1); Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=topics;activity=massmove;id_board_from=' . $id_board_from . ';id_board_to=' . $id_board_to . ';totaltopics=' . $total_topics . ';start=' . Utils::$context['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']; @@ -1835,25 +1945,29 @@ public function pruneDrafts(): void { SecurityToken::validate('admin-maint'); - $drafts = array(); + $drafts = []; // Find all of the old drafts - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT id_draft FROM {db_prefix}user_drafts WHERE poster_time <= {int:poster_time_old}', - array( + [ 'poster_time_old' => time() - (86400 * $_POST['draftdays']), - ) + ], ); - while ($row = Db::$db->fetch_row($request)) + while ($row = Db::$db->fetch_row($request)) { $drafts[] = (int) $row[0]; + } Db::$db->free_result($request); // If we have old drafts, remove them - if (count($drafts) > 0) + if (count($drafts) > 0) { Draft::delete($drafts, false); + } } /** @@ -1866,44 +1980,40 @@ public function hooks(): void $filter_url = ''; $current_filter = ''; $hooks = $this->getIntegrationHooks(); - $hooks_filters = array(); + $hooks_filters = []; - if (isset($_GET['filter'], $hooks[$_GET['filter']])) - { + if (isset($_GET['filter'], $hooks[$_GET['filter']])) { $filter_url = ';filter=' . $_GET['filter']; $current_filter = $_GET['filter']; } $filtered_hooks = array_filter( $hooks, - function($hook) use ($current_filter) - { + function ($hook) use ($current_filter) { return $current_filter == '' || $current_filter == $hook; }, - ARRAY_FILTER_USE_KEY + ARRAY_FILTER_USE_KEY, ); ksort($hooks); - foreach ($hooks as $hook => $functions) + foreach ($hooks as $hook => $functions) { $hooks_filters[] = '' . $hook . ''; + } - if (!empty($hooks_filters)) + if (!empty($hooks_filters)) { Utils::$context['insert_after_template'] .= ' '; + } - if (!empty($_REQUEST['do']) && isset($_REQUEST['hook']) && isset($_REQUEST['function'])) - { + if (!empty($_REQUEST['do']) && isset($_REQUEST['hook'], $_REQUEST['function'])) { User::$me->checkSession('request'); SecurityToken::validate('admin-hook', 'request'); - if ($_REQUEST['do'] == 'remove') - { + if ($_REQUEST['do'] == 'remove') { IntegrationHook::remove($_REQUEST['hook'], urldecode($_REQUEST['function'])); - } - else - { + } else { // Disable/enable logic; always remove exactly what was passed $function_remove = urldecode($_REQUEST['function']); $function_add = urldecode(rtrim($_REQUEST['function'], '!')) . (($_REQUEST['do'] == 'disable') ? '!' : ''); @@ -1917,117 +2027,113 @@ function($hook) use ($current_filter) SecurityToken::create('admin-hook', 'request'); - $list_options = array( + $list_options = [ 'id' => 'list_integration_hooks', 'title' => Lang::$txt['hooks_title_list'], 'items_per_page' => 20, 'base_href' => Config::$scripturl . '?action=admin;area=maintain;sa=hooks' . $filter_url . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'], 'default_sort_col' => 'hook_name', - 'get_items' => array( + 'get_items' => [ 'function' => __CLASS__ . '::getIntegrationHooksData', - 'params' => array( + 'params' => [ $filtered_hooks, strtr(Config::$boarddir, '\\', '/'), strtr(Config::$sourcedir, '\\', '/'), - ), - ), - 'get_count' => array( + ], + ], + 'get_count' => [ 'value' => array_reduce( $filtered_hooks, - function($accumulator, $functions) - { + function ($accumulator, $functions) { return $accumulator + count($functions); }, - 0 + 0, ), - ), + ], 'no_items_label' => Lang::$txt['hooks_no_hooks'], - 'columns' => array( - 'hook_name' => array( - 'header' => array( + 'columns' => [ + 'hook_name' => [ + 'header' => [ 'value' => Lang::$txt['hooks_field_hook_name'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'hook_name', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'hook_name', 'reverse' => 'hook_name DESC', - ), - ), - 'function_name' => array( - 'header' => array( + ], + ], + 'function_name' => [ + 'header' => [ 'value' => Lang::$txt['hooks_field_function_name'], - ), - 'data' => array( - 'function' => function($data) - { + ], + 'data' => [ + 'function' => function ($data) { // Show a nice icon to indicate this is an instance. $instance = (!empty($data['instance']) ? ' ' : ''); - if (!empty($data['included_file']) && !empty($data['real_function'])) + if (!empty($data['included_file']) && !empty($data['real_function'])) { return $instance . Lang::$txt['hooks_field_function'] . ': ' . $data['real_function'] . '
' . Lang::$txt['hooks_field_included_file'] . ': ' . $data['included_file']; + } + - else - return $instance . $data['real_function']; + return $instance . $data['real_function']; }, 'class' => 'word_break', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'function_name', 'reverse' => 'function_name DESC', - ), - ), - 'file_name' => array( - 'header' => array( + ], + ], + 'file_name' => [ + 'header' => [ 'value' => Lang::$txt['hooks_field_file_name'], - ), - 'data' => array( + ], + 'data' => [ 'db' => 'file_name', 'class' => 'word_break', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'file_name', 'reverse' => 'file_name DESC', - ), - ), - 'status' => array( - 'header' => array( + ], + ], + 'status' => [ + 'header' => [ 'value' => Lang::$txt['hooks_field_hook_exists'], 'style' => 'width:3%;', - ), - 'data' => array( - 'function' => function($data) use ($filter_url) - { + ], + 'data' => [ + 'function' => function ($data) use ($filter_url) { // Cannot update temp hooks in any way, really. Just show the appropriate icon. - if ($data['status'] == 'temp') - { + if ($data['status'] == 'temp') { return ''; } - else - { - $change_status = array('before' => '', 'after' => ''); - - // Can only enable/disable if it exists... - if ($data['hook_exists']) - { - $change_status['before'] = ''; - $change_status['after'] = ''; - } - - return $change_status['before'] . '' . $change_status['after']; + + + $change_status = ['before' => '', 'after' => '']; + + // Can only enable/disable if it exists... + if ($data['hook_exists']) { + $change_status['before'] = ''; + $change_status['after'] = ''; } + + return $change_status['before'] . '' . $change_status['after']; + }, 'class' => 'centertext', - ), - 'sort' => array( + ], + 'sort' => [ 'default' => 'status', 'reverse' => 'status DESC', - ), - ), - ), - 'additional_rows' => array( - array( + ], + ], + ], + 'additional_rows' => [ + [ 'position' => 'after_title', 'value' => Lang::$txt['hooks_disable_instructions'] . '
' . Lang::$txt['hooks_disable_legend'] . ': @@ -2037,33 +2143,33 @@ function($accumulator, $functions)
  • ' . Lang::$txt['hooks_disable_legend_missing'] . '
  • ' . Lang::$txt['hooks_disable_legend_temp'] . '
  • ' . Lang::$txt['hooks_disable_legend_temp_missing'] . '
  • - ' - ), - ), - ); + ', + ], + ], + ]; - $list_options['columns']['remove'] = array( - 'header' => array( + $list_options['columns']['remove'] = [ + 'header' => [ 'value' => Lang::$txt['hooks_button_remove'], 'style' => 'width:3%', - ), - 'data' => array( - 'function' => function($data) use ($filter_url) - { + ], + 'data' => [ + 'function' => function ($data) use ($filter_url) { // Note: Cannot remove temp hooks via the UI... - if (!$data['hook_exists'] && $data['status'] != 'temp') + if (!$data['hook_exists'] && $data['status'] != 'temp') { return ' '; + } }, 'class' => 'centertext', - ), - ); - $list_options['form'] = array( + ], + ]; + $list_options['form'] = [ 'href' => Config::$scripturl . '?action=admin;area=maintain;sa=hooks' . $filter_url . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'], 'name' => 'list_integration_hooks', - ); + ]; new ItemList($list_options); @@ -2083,8 +2189,9 @@ function($accumulator, $functions) */ public static function load(): object { - if (!isset(self::$obj)) + if (!isset(self::$obj)) { self::$obj = new self(); + } return self::$obj; } @@ -2108,35 +2215,38 @@ public static function call(): void */ public static function getIntegrationHooksData($start, $per_page, $sort, $filtered_hooks, $normalized_boarddir, $normalized_sourcedir): array { - $function_list = $sort_array = $temp_data = array(); + $function_list = $sort_array = $temp_data = []; $files = self::getFileRecursive($normalized_sourcedir); - foreach ($files as $currentFile => $fileInfo) - $function_list += self::getDefinedFunctionsInFile($currentFile); - $sort_types = array( - 'hook_name' => array('hook_name', SORT_ASC), - 'hook_name DESC' => array('hook_name', SORT_DESC), - 'function_name' => array('function_name', SORT_ASC), - 'function_name DESC' => array('function_name', SORT_DESC), - 'file_name' => array('file_name', SORT_ASC), - 'file_name DESC' => array('file_name', SORT_DESC), - 'status' => array('status', SORT_ASC), - 'status DESC' => array('status', SORT_DESC), - ); + foreach ($files as $currentFile => $fileInfo) { + $function_list += self::getDefinedFunctionsInFile($currentFile); + } - foreach ($filtered_hooks as $hook => $functions) - foreach ($functions as $rawFunc) - { + $sort_types = [ + 'hook_name' => ['hook_name', SORT_ASC], + 'hook_name DESC' => ['hook_name', SORT_DESC], + 'function_name' => ['function_name', SORT_ASC], + 'function_name DESC' => ['function_name', SORT_DESC], + 'file_name' => ['file_name', SORT_ASC], + 'file_name DESC' => ['file_name', SORT_DESC], + 'status' => ['status', SORT_ASC], + 'status DESC' => ['status', SORT_DESC], + ]; + + foreach ($filtered_hooks as $hook => $functions) { + foreach ($functions as $rawFunc) { $hookParsedData = self::parseIntegrationHook($hook, $rawFunc); // Handle hooks pointing outside the sources directory. $absPath_clean = rtrim($hookParsedData['absPath'], '!'); - if ($absPath_clean != '' && !isset($files[$absPath_clean]) && file_exists($absPath_clean)) + + if ($absPath_clean != '' && !isset($files[$absPath_clean]) && file_exists($absPath_clean)) { $function_list += self::getDefinedFunctionsInFile($absPath_clean); + } $hook_exists = isset($function_list[$hookParsedData['call']]) || (substr($hook, -8) === '_include' && isset($files[$absPath_clean])); $hook_temp = !empty(Utils::$context['integration_hooks_temporary'][$hook][$hookParsedData['rawData']]); - $temp = array( + $temp = [ 'hook_name' => $hook, 'function_name' => $hookParsedData['rawData'], 'real_function' => $hookParsedData['call'], @@ -2147,10 +2257,11 @@ public static function getIntegrationHooksData($start, $per_page, $sort, $filter 'status' => ($hook_temp ? 'temp' : ($hook_exists ? ($hookParsedData['enabled'] ? 'allow' : 'moderate') : 'deny')), 'img_text' => Lang::$txt['hooks_' . ($hook_exists ? ($hook_temp ? 'temp' : ($hookParsedData['enabled'] ? 'active' : 'disabled')) : 'missing')], 'enabled' => $hookParsedData['enabled'], - ); + ]; $sort_array[] = $temp[$sort_types[$sort][0]]; $temp_data[] = $temp; } + } array_multisort($sort_array, $sort_types[$sort][1], $temp_data); @@ -2169,36 +2280,38 @@ public static function getIntegrationHooksData($start, $per_page, $sort, $filter * @param bool $post_count Whether to adjust post counts. * @return array The numbers of messages, topics, and reports updated. */ - public static function reattributePosts(int $memID, string $email = null, string $membername = null, bool $post_count = false) + public static function reattributePosts(int $memID, ?string $email = null, ?string $membername = null, bool $post_count = false) { - $updated = array( + $updated = [ 'messages' => 0, 'topics' => 0, 'reports' => 0, - ); + ]; // Firstly, if email and username aren't passed find out the members email address and name. - if ($email === null && $membername === null) - { - $request = Db::$db->query('', ' + if ($email === null && $membername === null) { + $request = Db::$db->query( + '', + ' SELECT email_address, member_name FROM {db_prefix}members WHERE id_member = {int:memID} LIMIT 1', - array( + [ 'memID' => $memID, - ) + ], ); list($email, $membername) = Db::$db->fetch_row($request); Db::$db->free_result($request); } // If they want the post count restored then we need to do some research. - if ($post_count) - { + if ($post_count) { $recycle_board = !empty(Config::$modSettings['recycle_enable']) && !empty(Config::$modSettings['recycle_board']) ? (int) Config::$modSettings['recycle_board'] : 0; - $request = Db::$db->query('', ' + $request = Db::$db->query( + '', + ' SELECT COUNT(*) FROM {db_prefix}messages AS m INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND b.count_posts = {int:count_posts}) @@ -2207,49 +2320,54 @@ public static function reattributePosts(int $memID, string $email = null, string AND m.id_board != {int:recycled_board}' : '') . (empty($email) ? '' : ' AND m.poster_email = {string:email_address}') . (empty($membername) ? '' : ' AND m.poster_name = {string:member_name}'), - array( + [ 'count_posts' => 0, 'guest_id' => 0, 'email_address' => $email, 'member_name' => $membername, 'is_approved' => 1, 'recycled_board' => $recycle_board, - ) + ], ); list($messageCount) = Db::$db->fetch_row($request); Db::$db->free_result($request); - User::updateMemberData($memID, array('posts' => 'posts + ' . $messageCount)); + User::updateMemberData($memID, ['posts' => 'posts + ' . $messageCount]); } - $query_parts = array(); + $query_parts = []; - if (!empty($email)) + if (!empty($email)) { $query_parts[] = 'poster_email = {string:email_address}'; + } - if (!empty($membername)) + if (!empty($membername)) { $query_parts[] = 'poster_name = {string:member_name}'; + } $query = implode(' AND ', $query_parts); // Finally, update the posts themselves! - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}messages SET id_member = {int:memID} WHERE ' . $query, - array( + [ 'memID' => $memID, 'email_address' => $email, 'member_name' => $membername, - ) + ], ); $updated['messages'] = Db::$db->affected_rows(); // Did we update any messages? - if ($updated['messages'] > 0) - { + if ($updated['messages'] > 0) { // First, check for updated topics. - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}topics AS t SET id_member_started = {int:memID} WHERE t.id_first_msg = ( @@ -2259,16 +2377,18 @@ public static function reattributePosts(int $memID, string $email = null, string AND m.id_msg = t.id_first_msg AND ' . $query . ' )', - array( + [ 'memID' => $memID, 'email_address' => $email, 'member_name' => $membername, - ) + ], ); $updated['topics'] = Db::$db->affected_rows(); // Second, check for updated reports. - Db::$db->query('', ' + Db::$db->query( + '', + ' UPDATE {db_prefix}log_reported AS lr SET id_member = {int:memID} WHERE lr.id_msg = ( @@ -2278,17 +2398,17 @@ public static function reattributePosts(int $memID, string $email = null, string AND m.id_msg = lr.id_msg AND ' . $query . ' )', - array( + [ 'memID' => $memID, 'email_address' => $email, 'member_name' => $membername, - ) + ], ); $updated['reports'] = Db::$db->affected_rows(); } // Allow mods with their own post tables to reattribute posts as well :) - IntegrationHook::call('integrate_reattribute_posts', array($memID, $email, $membername, $post_count, &$updated)); + IntegrationHook::call('integrate_reattribute_posts', [$memID, $email, $membername, $post_count, &$updated]); return $updated; } @@ -2525,25 +2645,25 @@ protected function __construct() Theme::loadTemplate('ManageMaintenance'); // This uses admin tabs - as it should! - Menu::$loaded['admin']->tab_data = array( + Menu::$loaded['admin']->tab_data = [ 'title' => Lang::$txt['maintain_title'], 'description' => Lang::$txt['maintain_info'], - 'tabs' => array( - 'routine' => array(), - 'database' => array(), - 'members' => array(), - 'topics' => array(), - ), - ); + 'tabs' => [ + 'routine' => [], + 'database' => [], + 'members' => [], + 'topics' => [], + ], + ]; - IntegrationHook::call('integrate_manage_maintenance', array(&self::$subactions)); + IntegrationHook::call('integrate_manage_maintenance', [&self::$subactions]); - if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) + if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) { $this->subaction = $_REQUEST['sa']; + } // Doing something special? - if (isset($_REQUEST['activity']) && isset(self::$subactions[$this->subaction]['activities'][$_REQUEST['activity']])) - { + if (isset($_REQUEST['activity'], self::$subactions[$this->subaction]['activities'][$_REQUEST['activity']])) { $this->activity = $_REQUEST['activity']; } @@ -2562,13 +2682,13 @@ protected function getIntegrationHooks(): array { static $integration_hooks; - if (!isset($integration_hooks)) - { - $integration_hooks = array(); - foreach (Config::$modSettings as $key => $value) - { - if (!empty($value) && substr($key, 0, 10) === 'integrate_') + if (!isset($integration_hooks)) { + $integration_hooks = []; + + foreach (Config::$modSettings as $key => $value) { + if (!empty($value) && substr($key, 0, 10) === 'integrate_') { $integration_hooks[$key] = explode(',', $value); + } } } @@ -2591,16 +2711,16 @@ protected static function getFileRecursive(string $dirname): array new \RecursiveIteratorIterator( new \RecursiveCallbackFilterIterator( new \RecursiveDirectoryIterator($dirname, \FilesystemIterator::UNIX_PATHS), - function ($fileInfo, $currentFile, $iterator) - { + function ($fileInfo, $currentFile, $iterator) { // Allow recursion - if ($iterator->hasChildren()) + if ($iterator->hasChildren()) { return true; + } return $fileInfo->getExtension() == 'php'; - } - ) - ) + }, + ), + ), ); } @@ -2614,7 +2734,7 @@ function ($fileInfo, $currentFile, $iterator) protected static function parseIntegrationHook(string $hook, string $rawData): array { // A single string can hold tons of info! - $hookData = array( + $hookData = [ 'object' => false, 'enabled' => true, 'absPath' => '', @@ -2624,48 +2744,46 @@ protected static function parseIntegrationHook(string $hook, string $rawData): a 'class' => '', 'call' => '', 'rawData' => $rawData, - ); + ]; // Meh... - if (empty($rawData)) + if (empty($rawData)) { return $hookData; + } $modFunc = $rawData; // Any files? - if (substr($hook, -8) === '_include') + if (substr($hook, -8) === '_include') { $modFunc = $modFunc . '|'; - if (strpos($modFunc, '|') !== false) - { - list ($hookData['hookFile'], $modFunc) = explode('|', $modFunc); - $hookData['absPath'] = strtr(strtr(trim($hookData['hookFile']), array('$boarddir' => Config::$boarddir, '$sourcedir' => Config::$sourcedir, '$themedir' => Theme::$current->settings['theme_dir'] ?? '')), '\\', '/'); + } + + if (strpos($modFunc, '|') !== false) { + list($hookData['hookFile'], $modFunc) = explode('|', $modFunc); + $hookData['absPath'] = strtr(strtr(trim($hookData['hookFile']), ['$boarddir' => Config::$boarddir, '$sourcedir' => Config::$sourcedir, '$themedir' => Theme::$current->settings['theme_dir'] ?? '']), '\\', '/'); } // Hook is an instance. - if (strpos($modFunc, '#') !== false) - { + if (strpos($modFunc, '#') !== false) { $modFunc = str_replace('#', '', $modFunc); $hookData['object'] = true; } // Hook is "disabled" // May need to inspect $rawData here for includes... - if ((strpos($modFunc, '!') !== false) || (empty($modFunc) && (strpos($rawData, '!') !== false))) - { + if ((strpos($modFunc, '!') !== false) || (empty($modFunc) && (strpos($rawData, '!') !== false))) { $modFunc = str_replace('!', '', $modFunc); $hookData['enabled'] = false; } // Handling methods? - if (strpos($modFunc, '::') !== false) - { - list ($hookData['class'], $hookData['method']) = explode('::', $modFunc); + if (strpos($modFunc, '::') !== false) { + list($hookData['class'], $hookData['method']) = explode('::', $modFunc); $hookData['pureFunc'] = $hookData['method']; $hookData['call'] = $modFunc; - } - - else + } else { $hookData['call'] = $hookData['pureFunc'] = $modFunc; + } return $hookData; } @@ -2674,20 +2792,20 @@ protected static function getDefinedFunctionsInFile(string $file): array { $source = file_get_contents($file); // token_get_all() is too slow so use a nice little regex instead. - preg_match_all('/\bnamespace\s++((?P>label)(?:\\\(?P>label))*+)\s*+;|\bclass\s++((?P>label))[\w\s]*+{|\bfunction\s++((?P>label))\s*+\(.*\)[:\|\w\s]*+{(?(DEFINE)(?