"));
+ $info_lines = explode("\n", strip_tags($info_lines, ''));
ob_end_clean();
// Remove things that could be considered sensitive.
$remove = '_COOKIE|Cookie|_GET|_REQUEST|REQUEST_URI|QUERY_STRING|REQUEST_URL|HTTP_REFERER';
// Put all of it into an array.
- foreach ($info_lines as $line)
- {
- if (preg_match('~(' . $remove . ')~', $line))
+ foreach ($info_lines as $line) {
+ if (preg_match('~(' . $remove . ')~', $line)) {
continue;
+ }
// New category?
- if (strpos($line, '') !== false)
- {
+ if (strpos($line, '') !== false) {
$category = preg_match('~(.*)~', $line, $title) ? $category = $title[1] : $category;
}
// Load it as setting => value or the old setting local master.
- if (preg_match('~]+>([^<]*) | ]+>([^<]*) | ~', $line, $val))
- {
+ if (preg_match('~]+>([^<]*) | ]+>([^<]*) | ~', $line, $val)) {
$pinfo[$category][$val[1]] = $val[2];
- }
- elseif (preg_match('~]+>([^<]*) | ]+>([^<]*) | ]+>([^<]*) | ~', $line, $val))
- {
- $pinfo[$category][$val[1]] = array(Lang::$txt['phpinfo_localsettings'] => $val[2], Lang::$txt['phpinfo_defaultsettings'] => $val[3]);
+ } elseif (preg_match('~]+>([^<]*) | ]+>([^<]*) | ]+>([^<]*) | ~', $line, $val)) {
+ $pinfo[$category][$val[1]] = [Lang::$txt['phpinfo_localsettings'] => $val[2], Lang::$txt['phpinfo_defaultsettings'] => $val[3]];
}
}
@@ -734,8 +712,9 @@ public function phpinfo(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -763,27 +742,27 @@ public static function generalConfigVars(): array
OR an empty string for a horizontal rule.
OR a string for a titled section.
*/
- $config_vars = array(
- array('mbname', Lang::$txt['admin_title'], 'file', 'text', 30),
+ $config_vars = [
+ ['mbname', Lang::$txt['admin_title'], 'file', 'text', 30],
'',
- array('maintenance', Lang::$txt['admin_maintain'], 'file', 'check'),
- array('mtitle', Lang::$txt['maintenance_subject'], 'file', 'text', 36),
- array('mmessage', Lang::$txt['maintenance_message'], 'file', 'text', 36),
+ ['maintenance', Lang::$txt['admin_maintain'], 'file', 'check'],
+ ['mtitle', Lang::$txt['maintenance_subject'], 'file', 'text', 36],
+ ['mmessage', Lang::$txt['maintenance_message'], 'file', 'text', 36],
'',
- array('webmaster_email', Lang::$txt['admin_webmaster_email'], 'file', 'text', 30),
+ ['webmaster_email', Lang::$txt['admin_webmaster_email'], 'file', 'text', 30],
'',
- array('enableCompressedOutput', Lang::$txt['enableCompressedOutput'], 'db', 'check', null, 'enableCompressedOutput'),
- array('disableHostnameLookup', Lang::$txt['disableHostnameLookup'], 'db', 'check', null, 'disableHostnameLookup'),
+ ['enableCompressedOutput', Lang::$txt['enableCompressedOutput'], 'db', 'check', null, 'enableCompressedOutput'],
+ ['disableHostnameLookup', Lang::$txt['disableHostnameLookup'], 'db', 'check', null, 'disableHostnameLookup'],
'',
- 'force_ssl' => array('force_ssl', Lang::$txt['force_ssl'], 'db', 'select', array(Lang::$txt['force_ssl_off'], Lang::$txt['force_ssl_complete']), 'force_ssl'),
- array('image_proxy_enabled', Lang::$txt['image_proxy_enabled'], 'file', 'check', null, 'image_proxy_enabled'),
- array('image_proxy_secret', Lang::$txt['image_proxy_secret'], 'file', 'text', 30, 'image_proxy_secret'),
- array('image_proxy_maxsize', Lang::$txt['image_proxy_maxsize'], 'file', 'int', null, 'image_proxy_maxsize'),
+ 'force_ssl' => ['force_ssl', Lang::$txt['force_ssl'], 'db', 'select', [Lang::$txt['force_ssl_off'], Lang::$txt['force_ssl_complete']], 'force_ssl'],
+ ['image_proxy_enabled', Lang::$txt['image_proxy_enabled'], 'file', 'check', null, 'image_proxy_enabled'],
+ ['image_proxy_secret', Lang::$txt['image_proxy_secret'], 'file', 'text', 30, 'image_proxy_secret'],
+ ['image_proxy_maxsize', Lang::$txt['image_proxy_maxsize'], 'file', 'int', null, 'image_proxy_maxsize'],
'',
- array('enable_sm_stats', Lang::$txt['enable_sm_stats'], 'db', 'check', null, 'enable_sm_stats'),
- );
+ ['enable_sm_stats', Lang::$txt['enable_sm_stats'], 'db', 'check', null, 'enable_sm_stats'],
+ ];
- IntegrationHook::call('integrate_general_settings', array(&$config_vars));
+ IntegrationHook::call('integrate_general_settings', [&$config_vars]);
return $config_vars;
}
@@ -803,38 +782,40 @@ public static function databaseConfigVars(): array
OR an empty string for a horizontal rule.
OR a string for a titled section.
*/
- $config_vars = array(
- array('db_persist', Lang::$txt['db_persist'], 'file', 'check', null, 'db_persist'),
- array('db_error_send', Lang::$txt['db_error_send'], 'file', 'check'),
- array('ssi_db_user', Lang::$txt['ssi_db_user'], 'file', 'text', null, 'ssi_db_user'),
- array('ssi_db_passwd', Lang::$txt['ssi_db_passwd'], 'file', 'password'),
+ $config_vars = [
+ ['db_persist', Lang::$txt['db_persist'], 'file', 'check', null, 'db_persist'],
+ ['db_error_send', Lang::$txt['db_error_send'], 'file', 'check'],
+ ['ssi_db_user', Lang::$txt['ssi_db_user'], 'file', 'text', null, 'ssi_db_user'],
+ ['ssi_db_passwd', Lang::$txt['ssi_db_passwd'], 'file', 'password'],
'',
- array('autoFixDatabase', Lang::$txt['autoFixDatabase'], 'db', 'check', false, 'autoFixDatabase')
- );
+ ['autoFixDatabase', Lang::$txt['autoFixDatabase'], 'db', 'check', false, 'autoFixDatabase'],
+ ];
// Add PG Stuff
- if (Db::$db->title === POSTGRE_TITLE)
- {
- $fts_language = array();
+ if (Db::$db->title === POSTGRE_TITLE) {
+ $fts_language = [];
- $request = Db::$db->query('',
+ $request = Db::$db->query(
+ '',
'SELECT cfgname FROM pg_ts_config',
- array()
+ [],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$fts_language[$row['cfgname']] = $row['cfgname'];
}
Db::$db->free_result($request);
- $config_vars = array_merge($config_vars, array(
+ $config_vars = array_merge(
+ $config_vars,
+ [
'',
- array('search_language', Lang::$txt['search_language'], 'db', 'select', $fts_language, 'pgFulltextSearch')
- )
+ ['search_language', Lang::$txt['search_language'], 'db', 'select', $fts_language, 'pgFulltextSearch'],
+ ],
);
}
- IntegrationHook::call('integrate_database_settings', array(&$config_vars));
+ IntegrationHook::call('integrate_database_settings', [&$config_vars]);
return $config_vars;
}
@@ -846,47 +827,46 @@ public static function databaseConfigVars(): array
*/
public static function cookieConfigVars(): array
{
- $config_vars = array(
+ $config_vars = [
// Cookies...
- array('cookiename', Lang::$txt['cookie_name'], 'file', 'text', 20),
- array('cookieTime', Lang::$txt['cookieTime'], 'db', 'select', array_filter(array_map(
- function ($str)
- {
- return isset(Lang::$txt[$str]) ? Lang::$txt[$str] : '';
+ ['cookiename', Lang::$txt['cookie_name'], 'file', 'text', 20],
+ ['cookieTime', Lang::$txt['cookieTime'], 'db', 'select', array_filter(array_map(
+ function ($str) {
+ return Lang::$txt[$str] ?? '';
},
- Utils::$context['login_cookie_times']
- ))),
- array('localCookies', Lang::$txt['localCookies'], 'db', 'check', false, 'localCookies'),
- array('globalCookies', Lang::$txt['globalCookies'], 'db', 'check', false, 'globalCookies'),
- array('globalCookiesDomain', Lang::$txt['globalCookiesDomain'], 'db', 'text', false, 'globalCookiesDomain'),
- array('secureCookies', Lang::$txt['secureCookies'], 'db', 'check', false, 'secureCookies', 'disabled' => !Config::httpsOn()),
- array('httponlyCookies', Lang::$txt['httponlyCookies'], 'db', 'check', false, 'httponlyCookies'),
- array('samesiteCookies', Lang::$txt['samesiteCookies'], 'db', 'select', array(
- 'none' => Lang::$txt['samesiteNone'],
- 'lax' => Lang::$txt['samesiteLax'],
- 'strict' => Lang::$txt['samesiteStrict']
- ),
- 'samesiteCookies'),
+ Utils::$context['login_cookie_times'],
+ ))],
+ ['localCookies', Lang::$txt['localCookies'], 'db', 'check', false, 'localCookies'],
+ ['globalCookies', Lang::$txt['globalCookies'], 'db', 'check', false, 'globalCookies'],
+ ['globalCookiesDomain', Lang::$txt['globalCookiesDomain'], 'db', 'text', false, 'globalCookiesDomain'],
+ ['secureCookies', Lang::$txt['secureCookies'], 'db', 'check', false, 'secureCookies', 'disabled' => !Config::httpsOn()],
+ ['httponlyCookies', Lang::$txt['httponlyCookies'], 'db', 'check', false, 'httponlyCookies'],
+ ['samesiteCookies', Lang::$txt['samesiteCookies'], 'db', 'select', [
+ 'none' => Lang::$txt['samesiteNone'],
+ 'lax' => Lang::$txt['samesiteLax'],
+ 'strict' => Lang::$txt['samesiteStrict'],
+ ],
+ 'samesiteCookies'],
'',
// Sessions
- array('databaseSession_enable', Lang::$txt['databaseSession_enable'], 'db', 'check', false, 'databaseSession_enable'),
- array('databaseSession_loose', Lang::$txt['databaseSession_loose'], 'db', 'check', false, 'databaseSession_loose'),
- array('databaseSession_lifetime', Lang::$txt['databaseSession_lifetime'], 'db', 'int', false, 'databaseSession_lifetime', 'postinput' => Lang::$txt['seconds']),
+ ['databaseSession_enable', Lang::$txt['databaseSession_enable'], 'db', 'check', false, 'databaseSession_enable'],
+ ['databaseSession_loose', Lang::$txt['databaseSession_loose'], 'db', 'check', false, 'databaseSession_loose'],
+ ['databaseSession_lifetime', Lang::$txt['databaseSession_lifetime'], 'db', 'int', false, 'databaseSession_lifetime', 'postinput' => Lang::$txt['seconds']],
'',
// 2FA
- array('tfa_mode', Lang::$txt['tfa_mode'], 'db', 'select', array(
+ ['tfa_mode', Lang::$txt['tfa_mode'], 'db', 'select', [
0 => Lang::$txt['tfa_mode_disabled'],
1 => Lang::$txt['tfa_mode_enabled'],
- ) + (empty(User::$me->tfa_secret) ? array() : array(
+ ] + (empty(User::$me->tfa_secret) ? [] : [
2 => Lang::$txt['tfa_mode_forced'],
- )) + (empty(User::$me->tfa_secret) ? array() : array(
+ ]) + (empty(User::$me->tfa_secret) ? [] : [
3 => Lang::$txt['tfa_mode_forcedall'],
- )), 'subtext' => Lang::$txt['tfa_mode_subtext'] . (empty(User::$me->tfa_secret) ? ' ' . Lang::$txt['tfa_mode_forced_help'] . '' : ''), 'tfa_mode'),
- );
+ ]), 'subtext' => Lang::$txt['tfa_mode_subtext'] . (empty(User::$me->tfa_secret) ? ' ' . Lang::$txt['tfa_mode_forced_help'] . '' : ''), 'tfa_mode'],
+ ];
- IntegrationHook::call('integrate_cookie_settings', array(&$config_vars));
+ IntegrationHook::call('integrate_cookie_settings', [&$config_vars]);
return $config_vars;
}
@@ -898,70 +878,70 @@ function ($str)
*/
public static function securityConfigVars(): array
{
- $config_vars = array(
- array('int', 'failed_login_threshold'),
- array('int', 'loginHistoryDays', 'subtext' => Lang::$txt['zero_to_disable']),
+ $config_vars = [
+ ['int', 'failed_login_threshold'],
+ ['int', 'loginHistoryDays', 'subtext' => Lang::$txt['zero_to_disable']],
'',
- array('check', 'securityDisable'),
- array('check', 'securityDisable_moderate'),
+ ['check', 'securityDisable'],
+ ['check', 'securityDisable_moderate'],
'',
// Reactive on email, and approve on delete
- array('check', 'send_validation_onChange'),
- array('check', 'approveAccountDeletion'),
+ ['check', 'send_validation_onChange'],
+ ['check', 'approveAccountDeletion'],
'',
// Password strength.
- array(
+ [
'select',
'password_strength',
- array(
+ [
Lang::$txt['setting_password_strength_low'],
Lang::$txt['setting_password_strength_medium'],
- Lang::$txt['setting_password_strength_high']
- )
- ),
- array('check', 'enable_password_conversion'),
+ Lang::$txt['setting_password_strength_high'],
+ ],
+ ],
+ ['check', 'enable_password_conversion'],
'',
// Reporting of personal messages?
- array('check', 'enableReportPM'),
+ ['check', 'enableReportPM'],
'',
- array('check', 'allow_cors'),
- array('check', 'allow_cors_credentials'),
- array('text', 'cors_domains'),
- array('text', 'cors_headers'),
+ ['check', 'allow_cors'],
+ ['check', 'allow_cors_credentials'],
+ ['text', 'cors_domains'],
+ ['text', 'cors_headers'],
'',
- array(
+ [
'select',
'frame_security',
- array(
+ [
'SAMEORIGIN' => Lang::$txt['setting_frame_security_SAMEORIGIN'],
'DENY' => Lang::$txt['setting_frame_security_DENY'],
- 'DISABLE' => Lang::$txt['setting_frame_security_DISABLE']
- )
- ),
+ 'DISABLE' => Lang::$txt['setting_frame_security_DISABLE'],
+ ],
+ ],
'',
- array(
+ [
'select',
'proxy_ip_header',
- array(
+ [
'disabled' => Lang::$txt['setting_proxy_ip_header_disabled'],
'autodetect' => Lang::$txt['setting_proxy_ip_header_autodetect'],
'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For',
'HTTP_CLIENT_IP' => 'Client-IP',
'HTTP_X_REAL_IP' => 'X-Real-IP',
- 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP'
- )
- ),
- array('text', 'proxy_ip_servers'),
- );
+ 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP',
+ ],
+ ],
+ ['text', 'proxy_ip_servers'],
+ ];
- IntegrationHook::call('integrate_general_security_settings', array(&$config_vars));
+ IntegrationHook::call('integrate_general_security_settings', [&$config_vars]);
return $config_vars;
}
@@ -975,37 +955,32 @@ public static function cacheConfigVars(): array
{
// Detect all available optimizers
$detectedCacheApis = CacheApi::detect();
- $apis_names = array();
+ $apis_names = [];
- foreach ($detectedCacheApis as $class_name => $cache_api)
- {
+ foreach ($detectedCacheApis as $class_name => $cache_api) {
$class_name_txt_key = strtolower($cache_api->getImplementationClassKeyName());
- $apis_names[$class_name] = isset(Lang::$txt[$class_name_txt_key . '_cache']) ?
- Lang::$txt[$class_name_txt_key . '_cache'] : $class_name;
+ $apis_names[$class_name] = Lang::$txt[$class_name_txt_key . '_cache'] ?? $class_name;
}
// Set our values to show what, if anything, we found.
- if (empty($detectedCacheApis))
- {
+ if (empty($detectedCacheApis)) {
Lang::$txt['cache_settings_message'] = '' . Lang::$txt['detected_no_caching'] . '';
- $cache_level = array(Lang::$txt['cache_off']);
+ $cache_level = [Lang::$txt['cache_off']];
$apis_names['none'] = Lang::$txt['cache_off'];
- }
- else
- {
+ } else {
Lang::$txt['cache_settings_message'] = '' . sprintf(Lang::$txt['detected_accelerators'], implode(', ', $apis_names)) . '';
- $cache_level = array(Lang::$txt['cache_off'], Lang::$txt['cache_level1'], Lang::$txt['cache_level2'], Lang::$txt['cache_level3']);
+ $cache_level = [Lang::$txt['cache_off'], Lang::$txt['cache_level1'], Lang::$txt['cache_level2'], Lang::$txt['cache_level3']];
}
// Define the variables we want to edit.
- $config_vars = array(
- array('', Lang::$txt['cache_settings_message'], '', 'desc'),
- array('cache_enable', Lang::$txt['cache_enable'], 'file', 'select', $cache_level, 'cache_enable'),
- array('cache_accelerator', Lang::$txt['cache_accelerator'], 'file', 'select', $apis_names),
- );
+ $config_vars = [
+ ['', Lang::$txt['cache_settings_message'], '', 'desc'],
+ ['cache_enable', Lang::$txt['cache_enable'], 'file', 'select', $cache_level, 'cache_enable'],
+ ['cache_accelerator', Lang::$txt['cache_accelerator'], 'file', 'select', $apis_names],
+ ];
// Some javascript to enable/disable certain settings if the option is not selected.
Utils::$context['settings_post_javascript'] = '
@@ -1013,15 +988,14 @@ public static function cacheConfigVars(): array
$("#cache_accelerator").change();
});';
- IntegrationHook::call('integrate_modify_cache_settings', array(&$config_vars));
+ IntegrationHook::call('integrate_modify_cache_settings', [&$config_vars]);
// Maybe we have some additional settings from the selected accelerator.
- if (!empty($detectedCacheApis))
- {
- foreach ($detectedCacheApis as $class_name_txt_key => $cache_api)
- {
- if (is_callable(array($cache_api, 'cacheSettings')))
+ if (!empty($detectedCacheApis)) {
+ foreach ($detectedCacheApis as $class_name_txt_key => $cache_api) {
+ if (is_callable([$cache_api, 'cacheSettings'])) {
$cache_api->cacheSettings($config_vars);
+ }
}
}
@@ -1036,8 +1010,7 @@ public static function cacheConfigVars(): array
public static function exportConfigVars(): array
{
// Fill in a default value for this if it is missing.
- if (empty(Config::$modSettings['export_dir']))
- {
+ if (empty(Config::$modSettings['export_dir'])) {
Config::$modSettings['export_dir'] = Config::$boarddir . DIRECTORY_SEPARATOR . 'exports';
}
@@ -1053,14 +1026,14 @@ public static function exportConfigVars(): array
*/
$diskspace_disabled = (!function_exists('disk_free_space') || !function_exists('disk_total_space') || intval(@disk_total_space(file_exists(Config::$modSettings['export_dir']) ? Config::$modSettings['export_dir'] : Config::$boarddir)) < 1440);
- $config_vars = array(
- array('text', 'export_dir', 40),
- array('int', 'export_expiry', 'subtext' => Lang::$txt['zero_to_disable'], 'postinput' => Lang::$txt['days_word']),
- array('int', 'export_min_diskspace_pct', 'postinput' => '%', 'max' => 80, 'disabled' => $diskspace_disabled),
- array('int', 'export_rate', 'min' => 5, 'max' => 500, 'step' => 5, 'subtext' => Lang::$txt['export_rate_desc']),
- );
+ $config_vars = [
+ ['text', 'export_dir', 40],
+ ['int', 'export_expiry', 'subtext' => Lang::$txt['zero_to_disable'], 'postinput' => Lang::$txt['days_word']],
+ ['int', 'export_min_diskspace_pct', 'postinput' => '%', 'max' => 80, 'disabled' => $diskspace_disabled],
+ ['int', 'export_rate', 'min' => 5, 'max' => 500, 'step' => 5, 'subtext' => Lang::$txt['export_rate_desc']],
+ ];
- IntegrationHook::call('integrate_export_settings', array(&$config_vars));
+ IntegrationHook::call('integrate_export_settings', [&$config_vars]);
return $config_vars;
}
@@ -1073,20 +1046,19 @@ public static function exportConfigVars(): array
public static function loadBalancingConfigVars(): array
{
// Start with a simple checkbox.
- $config_vars = array(
- array('check', 'loadavg_enable', 'disabled' => self::getLoadAverageDisabled()),
- );
+ $config_vars = [
+ ['check', 'loadavg_enable', 'disabled' => self::getLoadAverageDisabled()],
+ ];
// Loop through the settings.
- foreach (self::LOADAVG_DEFAULT_VALUES as $name => $value)
- {
+ foreach (self::LOADAVG_DEFAULT_VALUES as $name => $value) {
// Use the default value if the setting isn't set yet.
$value = !isset(Config::$modSettings[$name]) ? $value : Config::$modSettings[$name];
- $config_vars[] = array('float', $name, 'value' => $value, 'disabled' => self::getLoadAverageDisabled());
+ $config_vars[] = ['float', $name, 'value' => $value, 'disabled' => self::getLoadAverageDisabled()];
}
- IntegrationHook::call('integrate_loadavg_settings', array(&$config_vars));
+ IntegrationHook::call('integrate_loadavg_settings', [&$config_vars]);
return $config_vars;
}
@@ -1098,36 +1070,34 @@ public static function loadBalancingConfigVars(): array
*/
public static function getLoadAverageDisabled(): bool
{
- if (isset(self::$loadAverageDisabled))
+ if (isset(self::$loadAverageDisabled)) {
return self::$loadAverageDisabled;
+ }
// Assume we can't until proven otherwise.
self::$loadAverageDisabled = true;
// Windows, so we can't.
- if (DIRECTORY_SEPARATOR === '\\')
+ if (DIRECTORY_SEPARATOR === '\\') {
return self::$loadAverageDisabled;
+ }
// Most Linux distros offer a nice file that we can read.
Config::$modSettings['load_average'] = @file_get_contents('/proc/loadavg');
- if (!empty(Config::$modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', Config::$modSettings['load_average'], $matches) !== 0)
- {
+ if (!empty(Config::$modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', Config::$modSettings['load_average'], $matches) !== 0) {
Config::$modSettings['load_average'] = (float) $matches[1];
}
// On both Linux and Unix (e.g. macOS), we can we can check shell_exec('uptime').
- elseif ((Config::$modSettings['load_average'] = @shell_exec('uptime')) !== null && preg_match('~load averages?: (\d+\.\d+)~i', Config::$modSettings['load_average'], $matches) !== 0)
- {
+ elseif ((Config::$modSettings['load_average'] = @shell_exec('uptime')) !== null && preg_match('~load averages?: (\d+\.\d+)~i', Config::$modSettings['load_average'], $matches) !== 0) {
Config::$modSettings['load_average'] = (float) $matches[1];
}
// No shell_exec('uptime') and no /proc/loadavg, so we can't check.
- else
- {
+ else {
unset(Config::$modSettings['load_average']);
}
- if (!empty(Config::$modSettings['load_average']) || (isset(Config::$modSettings['load_average']) && Config::$modSettings['load_average'] === 0.0))
- {
+ if (!empty(Config::$modSettings['load_average']) || (isset(Config::$modSettings['load_average']) && Config::$modSettings['load_average'] === 0.0)) {
self::$loadAverageDisabled = false;
}
@@ -1159,39 +1129,30 @@ public static function getLoadAverageDisabled(): bool
*/
public static function prepareServerSettingsContext(&$config_vars)
{
- if (!empty(Utils::$context['settings_not_writable']))
- {
- Utils::$context['settings_message'] = array(
+ if (!empty(Utils::$context['settings_not_writable'])) {
+ Utils::$context['settings_message'] = [
'label' => Lang::$txt['settings_not_writable'],
'tag' => 'div',
- 'class' => 'centertext strong'
- );
+ 'class' => 'centertext strong',
+ ];
}
- 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();
+ Utils::$context['config_vars'] = [];
- foreach ($config_vars as $identifier => $config_var)
- {
- if (!is_array($config_var) || !isset($config_var[1]))
- {
+ foreach ($config_vars as $identifier => $config_var) {
+ if (!is_array($config_var) || !isset($config_var[1])) {
Utils::$context['config_vars'][] = $config_var;
- }
- else
- {
+ } else {
$varname = $config_var[0];
global $$varname;
@@ -1200,67 +1161,55 @@ public static function prepareServerSettingsContext(&$config_vars)
$divPos = strpos($config_var[1], ']*>~', '', substr($config_var[1], $divPos));
$config_var[1] = substr($config_var[1], 0, $divPos);
}
- Utils::$context['config_vars'][$config_var[0]] = array(
+ Utils::$context['config_vars'][$config_var[0]] = [
'label' => $config_var[1],
- 'help' => isset($config_var[5]) ? $config_var[5] : '',
+ 'help' => $config_var[5] ?? '',
'type' => $config_var[3],
'size' => !empty($config_var[4]) && !is_array($config_var[4]) ? $config_var[4] : 0,
- 'data' => isset($config_var[4]) && is_array($config_var[4]) && $config_var[3] != 'select' ? $config_var[4] : array(),
+ 'data' => isset($config_var[4]) && is_array($config_var[4]) && $config_var[3] != 'select' ? $config_var[4] : [],
'name' => $config_var[0],
- 'value' => $config_var[2] == 'file' ? Utils::htmlspecialchars($$varname) : (isset(Config::$modSettings[$config_var[0]]) ? Utils::htmlspecialchars(Config::$modSettings[$config_var[0]]) : (in_array($config_var[3], array('int', 'float')) ? 0 : '')),
+ 'value' => $config_var[2] == 'file' ? Utils::htmlspecialchars($$varname) : (isset(Config::$modSettings[$config_var[0]]) ? Utils::htmlspecialchars(Config::$modSettings[$config_var[0]]) : (in_array($config_var[3], ['int', 'float']) ? 0 : '')),
'disabled' => !empty(Utils::$context['settings_not_writable']) || !empty($config_var['disabled']),
'invalid' => false,
'subtext' => !empty($config_var['subtext']) ? $config_var['subtext'] : $subtext,
'javascript' => '',
'preinput' => !empty($config_var['preinput']) ? $config_var['preinput'] : '',
'postinput' => !empty($config_var['postinput']) ? $config_var['postinput'] : '',
- );
+ ];
// Handle min/max/step if necessary
- if ($config_var[3] == 'int' || $config_var[3] == 'float')
- {
+ if ($config_var[3] == 'int' || $config_var[3] == '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[0]]['min'] = $config_var['min'];
- }
- else
- {
+ } else {
Utils::$context['config_vars'][$config_var[0]]['min'] = 0;
}
- if (isset($config_var['max']))
- {
+ if (isset($config_var['max'])) {
Utils::$context['config_vars'][$config_var[0]]['max'] = $config_var['max'];
}
- if (isset($config_var['step']))
- {
+ if (isset($config_var['step'])) {
Utils::$context['config_vars'][$config_var[0]]['step'] = $config_var['step'];
}
}
// If this is a select box handle any data.
- if (!empty($config_var[4]) && is_array($config_var[4]))
- {
+ if (!empty($config_var[4]) && is_array($config_var[4])) {
// If it's associative
$config_values = array_values($config_var[4]);
- if (isset($config_values[0]) && is_array($config_values[0]))
- {
+ if (isset($config_values[0]) && is_array($config_values[0])) {
Utils::$context['config_vars'][$config_var[0]]['data'] = $config_var[4];
- }
- else
- {
- foreach ($config_var[4] as $key => $item)
- {
- Utils::$context['config_vars'][$config_var[0]]['data'][] = array($key, $item);
+ } else {
+ foreach ($config_var[4] as $key => $item) {
+ Utils::$context['config_vars'][$config_var[0]]['data'][] = [$key, $item];
}
}
}
@@ -1283,11 +1232,13 @@ public static function checkSettingsFileWriteSafe(): bool
{
self::$settings_not_writable = !is_writable(SMF_SETTINGS_FILE);
- if (self::$settings_not_writable)
+ if (self::$settings_not_writable) {
return false;
+ }
- if (!file_exists(SMF_SETTINGS_BACKUP_FILE))
+ if (!file_exists(SMF_SETTINGS_BACKUP_FILE)) {
@touch(SMF_SETTINGS_BACKUP_FILE);
+ }
self::$settings_backup_fail = !is_writable(SMF_SETTINGS_BACKUP_FILE);
@@ -1302,8 +1253,9 @@ public static function checkSettingsFileWriteSafe(): bool
*/
public static function modifyGeneralSettings($return_config = false)
{
- if (!empty($return_config))
+ if (!empty($return_config)) {
return self::generalConfigVars();
+ }
self::load();
self::$obj->subaction = 'general';
@@ -1318,8 +1270,9 @@ public static function modifyGeneralSettings($return_config = false)
*/
public static function modifyDatabaseSettings($return_config = false)
{
- if (!empty($return_config))
+ if (!empty($return_config)) {
return self::databaseConfigVars();
+ }
self::load();
self::$obj->subaction = 'database';
@@ -1334,8 +1287,9 @@ public static function modifyDatabaseSettings($return_config = false)
*/
public static function modifyCookieSettings($return_config = false)
{
- if (!empty($return_config))
+ if (!empty($return_config)) {
return self::cookieConfigVars();
+ }
self::load();
self::$obj->subaction = 'cookie';
@@ -1350,8 +1304,9 @@ public static function modifyCookieSettings($return_config = false)
*/
public static function modifyGeneralSecuritySettings($return_config = false)
{
- if (!empty($return_config))
+ if (!empty($return_config)) {
return self::securityConfigVars();
+ }
self::load();
self::$obj->subaction = 'security';
@@ -1366,8 +1321,9 @@ public static function modifyGeneralSecuritySettings($return_config = false)
*/
public static function modifyCacheSettings($return_config = false)
{
- if (!empty($return_config))
+ if (!empty($return_config)) {
return self::cacheConfigVars();
+ }
self::load();
self::$obj->subaction = 'cache';
@@ -1382,8 +1338,9 @@ public static function modifyCacheSettings($return_config = false)
*/
public static function modifyExportSettings($return_config = false)
{
- if (!empty($return_config))
+ if (!empty($return_config)) {
return self::exportConfigVars();
+ }
self::load();
self::$obj->subaction = 'export';
@@ -1398,8 +1355,9 @@ public static function modifyExportSettings($return_config = false)
*/
public static function modifyLoadBalancingSettings($return_config = false)
{
- if (!empty($return_config))
+ if (!empty($return_config)) {
return self::loadBalancingConfigVars();
+ }
self::load();
self::$obj->subaction = 'loads';
@@ -1428,16 +1386,17 @@ protected function __construct()
Lang::load('ManageSettings');
// Load up all the tabs...
- Menu::$loaded['admin']->tab_data = array(
+ Menu::$loaded['admin']->tab_data = [
'title' => Lang::$txt['admin_server_settings'],
'help' => 'serversettings',
'description' => Lang::$txt['admin_basic_settings'],
- );
+ ];
- IntegrationHook::call('integrate_server_settings', array(&self::$subactions));
+ IntegrationHook::call('integrate_server_settings', [&self::$subactions]);
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
+ }
}
/**
@@ -1463,49 +1422,37 @@ protected function __construct()
* just brute force overwrite them based on force_ssl.
*
* @param int $new_force_ssl is the current force_ssl setting.
- * @return void Returns nothing, just does its job
*/
protected function alignURLsWithSSLSetting($new_force_ssl = 0)
{
// Check Config::$boardurl
- if (!empty($new_force_ssl))
- {
- $newval = strtr(Config::$boardurl, array('http://' => 'https://'));
- }
- else
- {
- $newval = strtr(Config::$boardurl, array('https://' => 'http://'));
+ if (!empty($new_force_ssl)) {
+ $newval = strtr(Config::$boardurl, ['http://' => 'https://']);
+ } else {
+ $newval = strtr(Config::$boardurl, ['https://' => 'http://']);
}
- Config::updateSettingsFile(array('boardurl' => $newval));
+ Config::updateSettingsFile(['boardurl' => $newval]);
- $new_settings = array();
+ $new_settings = [];
// Check $smileys_url, but only if it points to a subfolder of Config::$boardurl
- if ($this->boardurlMatch(Config::$modSettings['smileys_url']))
- {
- if (!empty($new_force_ssl))
- {
- $newval = strtr(Config::$modSettings['smileys_url'], array('http://' => 'https://'));
- }
- else
- {
- $newval = strtr(Config::$modSettings['smileys_url'], array('https://' => 'http://'));
+ if ($this->boardurlMatch(Config::$modSettings['smileys_url'])) {
+ if (!empty($new_force_ssl)) {
+ $newval = strtr(Config::$modSettings['smileys_url'], ['http://' => 'https://']);
+ } else {
+ $newval = strtr(Config::$modSettings['smileys_url'], ['https://' => 'http://']);
}
$new_settings['smileys_url'] = $newval;
}
// Check $avatar_url, but only if it points to a subfolder of Config::$boardurl
- if ($this->boardurlMatch(Config::$modSettings['avatar_url']))
- {
- if (!empty($new_force_ssl))
- {
- $newval = strtr(Config::$modSettings['avatar_url'], array('http://' => 'https://'));
- }
- else
- {
- $newval = strtr(Config::$modSettings['avatar_url'], array('https://' => 'http://'));
+ if ($this->boardurlMatch(Config::$modSettings['avatar_url'])) {
+ if (!empty($new_force_ssl)) {
+ $newval = strtr(Config::$modSettings['avatar_url'], ['http://' => 'https://']);
+ } else {
+ $newval = strtr(Config::$modSettings['avatar_url'], ['https://' => 'http://']);
}
$new_settings['avatar_url'] = $newval;
@@ -1513,63 +1460,58 @@ protected function alignURLsWithSSLSetting($new_force_ssl = 0)
// Check $custom_avatar_url, but only if it points to a subfolder of Config::$boardurl
// This one had been optional in the past, make sure it is set first
- if (isset(Config::$modSettings['custom_avatar_url']) && $this->boardurlMatch(Config::$modSettings['custom_avatar_url']))
- {
- if (!empty($new_force_ssl))
- {
- $newval = strtr(Config::$modSettings['custom_avatar_url'], array('http://' => 'https://'));
- }
- else
- {
- $newval = strtr(Config::$modSettings['custom_avatar_url'], array('https://' => 'http://'));
+ if (isset(Config::$modSettings['custom_avatar_url']) && $this->boardurlMatch(Config::$modSettings['custom_avatar_url'])) {
+ if (!empty($new_force_ssl)) {
+ $newval = strtr(Config::$modSettings['custom_avatar_url'], ['http://' => 'https://']);
+ } else {
+ $newval = strtr(Config::$modSettings['custom_avatar_url'], ['https://' => 'http://']);
}
$new_settings['custom_avatar_url'] = $newval;
}
// Save updates to the settings table
- if (!empty($new_settings))
+ if (!empty($new_settings)) {
Config::updateModSettings($new_settings, true);
+ }
// Now we move onto the themes.
// First, get a list of theme URLs...
- $request = Db::$db->query('', '
- SELECT id_theme, variable, value
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_theme, variable, value
FROM {db_prefix}themes
WHERE variable in ({string:themeurl}, {string:imagesurl})
AND id_member = {int:zero}',
- array(
+ [
'themeurl' => 'theme_url',
'imagesurl' => 'images_url',
'zero' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// First check to see if it points to a subfolder of Config::$boardurl
- if ($this->boardurlMatch($row['value']))
- {
- if (!empty($new_force_ssl))
- {
- $newval = strtr($row['value'], array('http://' => 'https://'));
- }
- else
- {
- $newval = strtr($row['value'], array('https://' => 'http://'));
+ if ($this->boardurlMatch($row['value'])) {
+ if (!empty($new_force_ssl)) {
+ $newval = strtr($row['value'], ['http://' => 'https://']);
+ } else {
+ $newval = strtr($row['value'], ['https://' => 'http://']);
}
- Db::$db->query('', '
- UPDATE {db_prefix}themes
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}themes
SET value = {string:theme_val}
WHERE variable = {string:theme_var}
AND id_theme = {string:theme_id}
AND id_member = {int:zero}',
- array(
+ [
'theme_val' => $newval,
'theme_var' => $row['variable'],
'theme_id' => $row['id_theme'],
'zero' => 0,
- )
+ ],
);
}
}
@@ -1590,8 +1532,8 @@ protected function alignURLsWithSSLSetting($new_force_ssl = 0)
protected function boardurlMatch($url = ''): bool
{
// Strip the schemes
- $urlpath = strtr($url, array('http://' => '', 'https://' => ''));
- $boardurlpath = strtr(Config::$boardurl, array('http://' => '', 'https://' => ''));
+ $urlpath = strtr($url, ['http://' => '', 'https://' => '']);
+ $boardurlpath = strtr(Config::$boardurl, ['http://' => '', 'https://' => '']);
// If leftmost portion of path matches boardurl, return true
$result = strpos($urlpath, $boardurlpath);
@@ -1611,16 +1553,17 @@ protected function boardurlMatch($url = ''): bool
protected function registerSMStats()
{
// Already have a key? Can't register again.
- if (!empty(Config::$modSettings['sm_stats_key']))
+ if (!empty(Config::$modSettings['sm_stats_key'])) {
return true;
+ }
$fp = @fsockopen('www.simplemachines.org', 443, $errno, $errstr);
- if (!$fp)
+ if (!$fp) {
$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
+ }
- if ($fp)
- {
+ if ($fp) {
$out = 'GET /smf/stats/register_stats.php?site=' . base64_encode(Config::$boardurl) . ' HTTP/1.1' . "\r\n";
$out .= 'Host: www.simplemachines.org' . "\r\n";
$out .= 'Connection: Close' . "\r\n\r\n";
@@ -1628,21 +1571,22 @@ protected function registerSMStats()
$return_data = '';
- while (!feof($fp))
+ while (!feof($fp)) {
$return_data .= fgets($fp, 128);
+ }
fclose($fp);
// Get the unique site ID.
preg_match('~SITE-ID:\s(\w{10})~', $return_data, $ID);
- if (!empty($ID[1]))
- {
- Db::$db->insert('replace',
+ if (!empty($ID[1])) {
+ Db::$db->insert(
+ 'replace',
'{db_prefix}settings',
- array('variable' => 'string', 'value' => 'string'),
- array('sm_stats_key', $ID[1]),
- array('variable')
+ ['variable' => 'string', 'value' => 'string'],
+ ['sm_stats_key', $ID[1]],
+ ['variable'],
);
return true;
@@ -1654,7 +1598,8 @@ protected function registerSMStats()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Server::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Server::exportStatic')) {
Server::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Admin/Smileys.php b/Sources/Actions/Admin/Smileys.php
index 06fc4a4292..e39ad42c85 100644
--- a/Sources/Actions/Admin/Smileys.php
+++ b/Sources/Actions/Admin/Smileys.php
@@ -15,11 +15,13 @@
namespace SMF\Actions\Admin;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\Actions\MessageIndex;
+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\ItemList;
@@ -27,14 +29,11 @@
use SMF\Logging;
use SMF\Menu;
use SMF\Msg;
+use SMF\PackageManager\SubsPackage;
use SMF\SecurityToken;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Actions\MessageIndex;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
-use SMF\PackageManager\SubsPackage;
use SMF\WebFetch\WebFetchApi;
/**
@@ -49,13 +48,21 @@ class Smileys implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ManageSmileys',
- 'getConfigVars' => false,
- ),
- );
+ 'list_getSmileySets' => 'list_getSmileySets',
+ 'list_getNumSmileySets' => 'list_getNumSmileySets',
+ 'list_getSmileys' => 'list_getSmileys',
+ 'list_getNumSmileys' => 'list_getNumSmileys',
+ 'list_getMessageIcons' => 'list_getMessageIcons',
+ 'addSmiley' => 'AddSmiley',
+ 'editSmileys' => 'EditSmileys',
+ 'editSmileyOrder' => 'EditSmileyOrder',
+ 'installSmileySet' => 'InstallSmileySet',
+ 'editMessageIcons' => 'EditMessageIcons',
+ ],
+ ];
/*****************
* Class constants
@@ -84,7 +91,7 @@ class Smileys implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'editsets' => 'editSets',
'import' => 'editSets',
'modifyset' => 'editSets',
@@ -96,34 +103,34 @@ class Smileys implements ActionInterface
'editicon' => 'editIcon',
'editicons' => 'editIcon',
'settings' => 'settings',
- );
+ ];
/**
* @var array
*
* Allowed file extensions for smiley images.
*/
- public static array $allowed_extenions = array(
+ public static array $allowed_extenions = [
'gif',
'png',
'jpg',
'jpeg',
'tiff',
'svg',
- );
+ ];
/**
* @var array
*
* Allowed MIME types for smiley images.
*/
- public static array $allowed_mime_types = array(
+ public static array $allowed_mime_types = [
'image/gif',
'image/png',
'image/jpeg',
'image/tiff',
'image/svg+xml',
- );
+ ];
/**
* @var array
@@ -131,7 +138,7 @@ class Smileys implements ActionInterface
* Forbidden file names.
* Uploading a smiley image with one of these names will give a fatal error.
*/
- public static array $illegal_files = array(
+ public static array $illegal_files = [
'con',
'com1',
'com2',
@@ -142,14 +149,14 @@ class Smileys implements ActionInterface
'lpt1',
'.htaccess',
'index.php',
- );
+ ];
/**
* @var array
*
* Info about all known smiley sets.
*/
- public static array $smiley_sets = array();
+ public static array $smiley_sets = [];
/**
* @var string
@@ -193,10 +200,11 @@ class Smileys 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);
+ }
}
/**
@@ -208,31 +216,31 @@ public function editSets()
Menu::$loaded['admin']['current_subsection'] = 'editsets';
// They must have submitted a form.
- if (isset($_POST['smiley_save']))
- {
+ if (isset($_POST['smiley_save'])) {
User::$me->checkSession();
SecurityToken::validate('admin-mss', 'request');
// Delete selected smiley sets.
- if (!empty($_POST['delete']) && !empty($_POST['smiley_set']))
- {
- foreach ($_POST['smiley_set'] as $id => $val)
- {
+ if (!empty($_POST['delete']) && !empty($_POST['smiley_set'])) {
+ foreach ($_POST['smiley_set'] as $id => $val) {
// Can't delete sets that don't exist.
- if (!isset(self::$smiley_sets[$id]))
+ if (!isset(self::$smiley_sets[$id])) {
continue;
+ }
// Can't the default set or the only one remaining.
- if (self::$smiley_sets[$id]['is_default'] || count(self::$smiley_sets) < 2)
+ if (self::$smiley_sets[$id]['is_default'] || count(self::$smiley_sets) < 2) {
continue;
+ }
// Delete this set's entries from the smiley_files table
- Db::$db->query('', '
- DELETE FROM {db_prefix}smiley_files
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}smiley_files
WHERE smiley_set = {string:smiley_set}',
- array(
+ [
'smiley_set' => $id,
- )
+ ],
);
// Remove this set from our lists
@@ -242,76 +250,76 @@ public function editSets()
self::saveSets();
}
// Add a new smiley set.
- elseif (!empty($_POST['add']))
- {
+ elseif (!empty($_POST['add'])) {
$this->subaction = 'modifyset';
}
// Create or modify a smiley set.
- elseif (isset($_POST['set']))
- {
+ elseif (isset($_POST['set'])) {
// @todo Needs a more precise error message.
- if (!isset($_POST['smiley_sets_name']))
+ if (!isset($_POST['smiley_sets_name'])) {
ErrorHandler::fatalLang('smiley_set_not_found', false);
+ }
$_POST['smiley_sets_name'] = self::sanitizeString($_POST['smiley_sets_name']);
// No spaces or weirdness allowed in the directory name.
- if (!isset($_POST['smiley_sets_path']) || $_POST['smiley_sets_path'] !== self::sanitizeFileName($_POST['smiley_sets_path']))
- {
+ if (!isset($_POST['smiley_sets_path']) || $_POST['smiley_sets_path'] !== self::sanitizeFileName($_POST['smiley_sets_path'])) {
ErrorHandler::fatalLang('smiley_set_dir_not_found', false, Utils::htmlspecialchars($_POST['smiley_sets_name']));
}
// Create a new smiley set.
- if ($_POST['set'] == -1 && isset($_POST['smiley_sets_path']))
- {
- if (isset(self::$smiley_sets[$_POST['smiley_sets_path']]))
+ if ($_POST['set'] == -1 && isset($_POST['smiley_sets_path'])) {
+ if (isset(self::$smiley_sets[$_POST['smiley_sets_path']])) {
ErrorHandler::fatalLang('smiley_set_already_exists', false);
+ }
- if (!is_dir(self::$smileys_dir . '/' . $_POST['smiley_sets_path']))
+ if (!is_dir(self::$smileys_dir . '/' . $_POST['smiley_sets_path'])) {
$this->createDir($_POST['smiley_sets_path'], $_POST['smiley_sets_name']);
+ }
- if (!empty($_POST['smiley_sets_default']))
- {
- foreach (self::$smiley_sets as $id => $set)
+ if (!empty($_POST['smiley_sets_default'])) {
+ foreach (self::$smiley_sets as $id => $set) {
self::$smiley_sets[$id]['is_default'] = false;
+ }
}
- self::$smiley_sets[$_POST['smiley_sets_path']] = array(
- 'id' => max(array_map(fn($set) => $set['id'], self::$smiley_sets)) + 1,
+ self::$smiley_sets[$_POST['smiley_sets_path']] = [
+ 'id' => max(array_map(fn ($set) => $set['id'], self::$smiley_sets)) + 1,
'raw_path' => $_POST['smiley_sets_path'],
'raw_name' => $_POST['smiley_sets_name'],
'path' => Utils::htmlspecialchars($_POST['smiley_sets_path']),
'name' => Utils::htmlspecialchars($_POST['smiley_sets_name']),
'is_default' => !empty($_POST['smiley_sets_default']),
'is_new' => true,
- );
+ ];
self::saveSets();
}
// Modify an existing smiley set.
- else
- {
+ else {
// Make sure the smiley set exists.
- if (!isset(self::$smiley_sets[$_POST['set']]))
+ if (!isset(self::$smiley_sets[$_POST['set']])) {
ErrorHandler::fatalLang('smiley_set_not_found', false);
+ }
// Make sure the path is not yet used by another smiley set.
- foreach (self::$smiley_sets as $id => $set)
- {
- if ($id === $_POST['set'])
+ foreach (self::$smiley_sets as $id => $set) {
+ if ($id === $_POST['set']) {
continue;
+ }
- if ($set['raw_path'] === $_POST['smiley_sets_path'])
+ if ($set['raw_path'] === $_POST['smiley_sets_path']) {
ErrorHandler::fatalLang('smiley_set_path_already_used', false);
+ }
}
self::$smiley_sets[$_POST['set']]['raw_path'] = $_POST['smiley_sets_path'];
self::$smiley_sets[$_POST['set']]['raw_name'] = $_POST['smiley_sets_name'];
- if (!empty($_POST['smiley_sets_default']))
- {
- foreach (self::$smiley_sets as $id => $set)
+ if (!empty($_POST['smiley_sets_default'])) {
+ foreach (self::$smiley_sets as $id => $set) {
self::$smiley_sets[$id]['is_default'] = $id === $_POST['set'];
+ }
}
self::saveSets();
@@ -325,14 +333,14 @@ public function editSets()
}
// Importing any smileys from an existing set?
- if ($this->subaction == 'import')
- {
+ if ($this->subaction == 'import') {
User::$me->checkSession('get');
SecurityToken::validate('admin-mss', 'request');
// Sanity check - then import.
- if (isset(self::$smiley_sets[$_GET['set']]))
+ if (isset(self::$smiley_sets[$_GET['set']])) {
$this->import(self::$smiley_sets[$_GET['set']]['raw_path'], true);
+ }
// Force the process to continue.
$this->subaction = 'modifyset';
@@ -340,13 +348,11 @@ public function editSets()
}
// If we're modifying or adding a smiley set, some context info needs to be set.
- if ($this->subaction == 'modifyset')
- {
+ if ($this->subaction == 'modifyset') {
$_GET['set'] = !isset($_GET['set']) ? -1 : $_GET['set'];
- if ($_GET['set'] == -1 || !isset(self::$smiley_sets[$_GET['set']]))
- {
- Utils::$context['current_set'] = array(
+ if ($_GET['set'] == -1 || !isset(self::$smiley_sets[$_GET['set']])) {
+ Utils::$context['current_set'] = [
'id' => '-1',
'raw_path' => '',
'raw_name' => '',
@@ -354,10 +360,8 @@ public function editSets()
'name' => '',
'is_default' => false,
'is_new' => true,
- );
- }
- else
- {
+ ];
+ } else {
Utils::$context['current_set'] = &self::$smiley_sets[$_GET['set']];
Utils::$context['current_set']['is_new'] = false;
@@ -366,47 +370,46 @@ public function editSets()
!empty(Config::$modSettings['smiley_enable'])
&& !empty(self::$smileys_dir)
&& is_dir(self::$smileys_dir . '/' . Utils::$context['current_set']['path'])
- )
- {
- $smileys = array();
+ ) {
+ $smileys = [];
$dir = dir(self::$smileys_dir . '/' . Utils::$context['current_set']['path']);
- while ($entry = $dir->read())
- {
+ while ($entry = $dir->read()) {
$pathinfo = pathinfo($entry);
- if (empty($pathinfo['filename']) || empty($pathinfo['extension']))
+ if (empty($pathinfo['filename']) || empty($pathinfo['extension'])) {
continue;
+ }
- if (in_array($pathinfo['extension'], self::$allowed_extenions) && $pathinfo['filename'] != 'blank')
- {
+ if (in_array($pathinfo['extension'], self::$allowed_extenions) && $pathinfo['filename'] != 'blank') {
$smileys[Utils::convertCase($entry, 'fold')] = $entry;
}
}
$dir->close();
- if (empty($smileys))
- {
- ErrorHandler::fatalLang('smiley_set_dir_not_found', false, array(Utils::$context['current_set']['name']));
+ if (empty($smileys)) {
+ ErrorHandler::fatalLang('smiley_set_dir_not_found', false, [Utils::$context['current_set']['name']]);
}
// Exclude the smileys that are already in the database.
- $request = Db::$db->query('', '
- SELECT filename
+ $request = Db::$db->query(
+ '',
+ 'SELECT filename
FROM {db_prefix}smiley_files
WHERE filename IN ({array_string:smiley_list})
AND smiley_set = {string:smiley_set}',
- array(
+ [
'smiley_list' => $smileys,
'smiley_set' => Utils::$context['current_set']['path'],
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (isset($smileys[Utils::convertCase($row['filename'], 'fold')]))
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (isset($smileys[Utils::convertCase($row['filename'], 'fold')])) {
unset($smileys[Utils::convertCase($row['filename'], 'fold')]);
+ }
}
Db::$db->free_result($request);
@@ -417,22 +420,19 @@ public function editSets()
}
// Retrieve all potential smiley set directories.
- Utils::$context['smiley_set_dirs'] = array();
+ Utils::$context['smiley_set_dirs'] = [];
- if (self::$smileys_dir_found)
- {
+ if (self::$smileys_dir_found) {
$dir = dir(self::$smileys_dir);
- while ($entry = $dir->read())
- {
- if (!in_array($entry, array('.', '..')) && is_dir(self::$smileys_dir . '/' . $entry))
- {
- Utils::$context['smiley_set_dirs'][] = array(
+ while ($entry = $dir->read()) {
+ if (!in_array($entry, ['.', '..']) && is_dir(self::$smileys_dir . '/' . $entry)) {
+ Utils::$context['smiley_set_dirs'][] = [
'id' => $entry,
'path' => self::$smileys_dir . '/' . $entry,
'selectable' => $entry == Utils::$context['current_set']['path'] || !in_array($entry, explode(',', Config::$modSettings['smiley_sets_known'])),
'current' => $entry == Utils::$context['current_set']['path'],
- );
+ ];
}
}
@@ -440,9 +440,8 @@ public function editSets()
// Creating a new set, but there are no available directories.
// Therefore, show the UI for making a new directory.
- if (Utils::$context['current_set']['is_new'])
- {
- Utils::$context['make_new'] = array_filter(Utils::$context['smiley_set_dirs'], fn($dir) => $dir['selectable']) === array();
+ if (Utils::$context['current_set']['is_new']) {
+ Utils::$context['make_new'] = array_filter(Utils::$context['smiley_set_dirs'], fn ($dir) => $dir['selectable']) === [];
}
}
}
@@ -451,116 +450,113 @@ public function editSets()
SecurityToken::create('admin-mss', 'request');
// In case we need to import smileys, we need to add the token in now.
- if (isset(Utils::$context['current_set']['import_url']))
- {
+ if (isset(Utils::$context['current_set']['import_url'])) {
Utils::$context['current_set']['import_url'] .= ';' . Utils::$context['admin-mss_token_var'] . '=' . Utils::$context['admin-mss_token'];
Utils::$context['smiley_set_unused_message'] = sprintf(Lang::$txt['smiley_set_unused'], Config::$scripturl . '?action=admin;area=smileys;sa=editsmileys', Config::$scripturl . '?action=admin;area=smileys;sa=addsmiley', Utils::$context['current_set']['import_url']);
}
- $listOptions = array(
+ $listOptions = [
'id' => 'smiley_set_list',
'title' => Lang::$txt['smiley_sets'],
'no_items_label' => Lang::$txt['smiley_sets_none'],
'base_href' => Config::$scripturl . '?action=admin;area=smileys;sa=editsets',
'default_sort_col' => 'name',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getSmileySets',
- ),
- 'get_count' => array(
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getNumSmileySets',
- ),
- 'columns' => array(
- 'default' => array(
- 'header' => array(
+ ],
+ 'columns' => [
+ 'default' => [
+ 'header' => [
'value' => Lang::$txt['smiley_sets_default'],
'class' => 'centercol',
- ),
- 'data' => array(
- 'function' => function($rowData)
- {
+ ],
+ 'data' => [
+ 'function' => function ($rowData) {
return $rowData['is_default'] ? ' ' : '';
},
'class' => 'centercol',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'is_default',
'reverse' => 'is_default DESC',
- ),
- ),
- 'name' => array(
- 'header' => array(
+ ],
+ ],
+ 'name' => [
+ 'header' => [
'value' => Lang::$txt['smiley_sets_name'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db_htmlsafe' => 'name',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'name',
'reverse' => 'name DESC',
- ),
- ),
- 'url' => array(
- 'header' => array(
+ ],
+ ],
+ 'url' => [
+ 'header' => [
'value' => Lang::$txt['smiley_sets_url'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => Config::$modSettings['smileys_url'] . '/ %1$s/...',
- 'params' => array(
+ 'params' => [
'path' => true,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'path',
'reverse' => 'path DESC',
- ),
- ),
- 'modify' => array(
- 'header' => array(
+ ],
+ ],
+ 'modify' => [
+ 'header' => [
'value' => Lang::$txt['smiley_set_modify'],
'class' => 'centercol',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' ' . Lang::$txt['smiley_set_modify'] . '',
- 'params' => array(
+ 'params' => [
'path' => true,
- ),
- ),
+ ],
+ ],
'class' => 'centercol',
- ),
- ),
- 'check' => array(
- 'header' => array(
+ ],
+ ],
+ 'check' => [
+ 'header' => [
'value' => ' ',
'class' => 'centercol',
- ),
- 'data' => array(
- 'function' => function($rowData)
- {
+ ],
+ 'data' => [
+ 'function' => function ($rowData) {
return $rowData['is_default'] ? '' : sprintf(' ', $rowData['path']);
},
'class' => 'centercol',
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . '?action=admin;area=smileys;sa=editsets',
'token' => 'admin-mss',
- ),
- 'additional_rows' => array(
- array(
+ ],
+ 'additional_rows' => [
+ [
'position' => 'above_column_headers',
'value' => ' ' . Lang::$txt['smiley_sets_add'] . ' ',
- ),
- array(
+ ],
+ [
'position' => 'below_table_data',
'value' => ' ' . Lang::$txt['smiley_sets_add'] . ' ',
- ),
- ),
- );
+ ],
+ ],
+ ];
new ItemList($listOptions);
}
@@ -571,15 +567,15 @@ public function editSets()
public function add()
{
// This will hold the names of the added files for each set
- $filename_array = array();
+ $filename_array = [];
// Submitting a form?
- if (isset($_POST[Utils::$context['session_var']], $_POST['smiley_code']))
- {
+ if (isset($_POST[Utils::$context['session_var']], $_POST['smiley_code'])) {
User::$me->checkSession();
- foreach (array('smiley_code', 'smiley_filename', 'smiley_description') as $key)
+ foreach (['smiley_code', 'smiley_filename', 'smiley_description'] as $key) {
$_POST[$key] = Utils::normalize($_POST[$key]);
+ }
$_POST['smiley_code'] = Utils::htmlTrim($_POST['smiley_code']);
@@ -588,116 +584,107 @@ public function add()
$_POST['smiley_filename'] = Utils::htmlTrim($_POST['smiley_filename']);
// Make sure some code was entered.
- if (empty($_POST['smiley_code']))
+ if (empty($_POST['smiley_code'])) {
ErrorHandler::fatalLang('smiley_has_no_code', false);
+ }
// Check whether the new code has duplicates. It should be unique.
- $request = Db::$db->query('', '
- SELECT id_smiley
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_smiley
FROM {db_prefix}smileys
WHERE code = {raw:mysql_binary_statement} {string:smiley_code}',
- array(
+ [
'mysql_binary_statement' => Db::$db->title == MYSQL_TITLE ? 'BINARY' : '',
'smiley_code' => $_POST['smiley_code'],
- )
+ ],
);
- if (Db::$db->num_rows($request) > 0)
- {
+
+ if (Db::$db->num_rows($request) > 0) {
ErrorHandler::fatalLang('smiley_not_unique', false);
}
Db::$db->free_result($request);
// If we are uploading - check all the smiley sets are writable!
- if ($_POST['method'] != 'existing')
- {
- $writeErrors = array();
+ if ($_POST['method'] != 'existing') {
+ $writeErrors = [];
- foreach (self::$smiley_sets as $set)
- {
- if (!is_writable(self::$smileys_dir . '/' . $set['raw_path']))
+ foreach (self::$smiley_sets as $set) {
+ if (!is_writable(self::$smileys_dir . '/' . $set['raw_path'])) {
$writeErrors[] = $set['path'];
+ }
}
- if (!empty($writeErrors))
- {
- ErrorHandler::fatalLang('smileys_upload_error_notwritable', false, array(implode(', ', $writeErrors)));
+ if (!empty($writeErrors)) {
+ ErrorHandler::fatalLang('smileys_upload_error_notwritable', false, [implode(', ', $writeErrors)]);
}
}
// Uploading just one smiley for all of them?
- if (isset($_POST['sameall']) && isset($_FILES['uploadSmiley']['name']) && $_FILES['uploadSmiley']['name'] != '')
- {
- $filename_array = array_merge($filename_array, $this->moveImageIntoPlace($_FILES['uploadSmiley']['name'], $_FILES['uploadSmiley']['tmp_name'], array_map(fn($set) => $set['raw_path'], self::$smiley_sets)));
+ if (isset($_POST['sameall'], $_FILES['uploadSmiley']['name']) && $_FILES['uploadSmiley']['name'] != '') {
+ $filename_array = array_merge($filename_array, $this->moveImageIntoPlace($_FILES['uploadSmiley']['name'], $_FILES['uploadSmiley']['tmp_name'], array_map(fn ($set) => $set['raw_path'], self::$smiley_sets)));
}
// What about uploading several files?
- elseif ($_POST['method'] != 'existing')
- {
- foreach ($_FILES as $name => $data)
- {
- if ($_FILES[$name]['name'] == '')
+ elseif ($_POST['method'] != 'existing') {
+ foreach ($_FILES as $name => $data) {
+ if ($_FILES[$name]['name'] == '') {
ErrorHandler::fatalLang('smileys_upload_error_blank', false);
+ }
}
- foreach (self::$smiley_sets as $set => $smiley_set)
- {
- $filename_array = array_merge($filename_array, $this->moveImageIntoPlace($_FILES['individual_' . $smiley_set['raw_path']]['name'], $_FILES['individual_' . $smiley_set['raw_path']]['tmp_name'], array($smiley_set['raw_path'])));
+ foreach (self::$smiley_sets as $set => $smiley_set) {
+ $filename_array = array_merge($filename_array, $this->moveImageIntoPlace($_FILES['individual_' . $smiley_set['raw_path']]['name'], $_FILES['individual_' . $smiley_set['raw_path']]['tmp_name'], [$smiley_set['raw_path']]));
}
}
// Re-using an existing image
- else
- {
+ else {
// Make sure a filename was given
- if (empty($_POST['smiley_filename']))
+ if (empty($_POST['smiley_filename'])) {
ErrorHandler::fatalLang('smiley_has_no_filename', false);
+ }
// And make sure it is legitimate
$pathinfo = pathinfo($_POST['smiley_filename']);
- if (!in_array($pathinfo['extension'], self::$allowed_extenions))
- {
- ErrorHandler::fatalLang('smileys_upload_error_types', false, array(implode(', ', self::$allowed_extenions)));
+ if (!in_array($pathinfo['extension'], self::$allowed_extenions)) {
+ ErrorHandler::fatalLang('smileys_upload_error_types', false, [implode(', ', self::$allowed_extenions)]);
}
- if (strpos($pathinfo['filename'], '.') !== false)
- {
+ if (strpos($pathinfo['filename'], '.') !== false) {
ErrorHandler::fatalLang('smileys_upload_error_illegal', false);
}
- if (!isset(self::$smiley_sets[$pathinfo['dirname']]))
- {
+ if (!isset(self::$smiley_sets[$pathinfo['dirname']])) {
ErrorHandler::fatalLang('smiley_set_not_found', false);
}
- if (!file_exists(self::$smileys_dir . '/' . $pathinfo['dirname'] . '/' . $pathinfo['basename']))
- {
+ if (!file_exists(self::$smileys_dir . '/' . $pathinfo['dirname'] . '/' . $pathinfo['basename'])) {
ErrorHandler::fatalLang('smiley_not_found', false);
}
// Now ensure every set has a file to use for this smiley
- foreach (self::$smiley_sets as $set => $smiley_set)
- {
+ foreach (self::$smiley_sets as $set => $smiley_set) {
unset($basename);
// Check whether any similarly named files exist in the other set's directory
$similar_files = glob(self::$smileys_dir . '/' . $set . '/' . $pathinfo['filename'] . '.{' . implode(',', self::$allowed_extenions) . '}', GLOB_BRACE);
// If there's a similarly named file already there, use it.
- if (!empty($similar_files))
- {
+ if (!empty($similar_files)) {
// Prefer an exact match if there is one.
- foreach ($similar_files as $similar_file)
- {
- if (basename($similar_file) == $pathinfo['basename'])
+ foreach ($similar_files as $similar_file) {
+ if (basename($similar_file) == $pathinfo['basename']) {
$basename = $pathinfo['basename'];
+ }
}
// Same name, different extension.
- if (empty($basename))
+ if (empty($basename)) {
$basename = basename(reset($similar_files));
+ }
}
// Otherwise, copy the image to the other set's directory
- else
- {
+ else {
copy(self::$smileys_dir . '/' . $pathinfo['dirname'] . '/' . $pathinfo['basename'], self::$smileys_dir . '/' . $set . '/' . $pathinfo['basename']);
Utils::makeWritable(self::$smileys_dir . '/' . $set . '/' . $pathinfo['basename'], 0644);
@@ -706,8 +693,7 @@ public function add()
}
// Double-check that everything went as expected
- if (empty($basename) || !file_exists(self::$smileys_dir . '/' . $set . '/' . $basename))
- {
+ if (empty($basename) || !file_exists(self::$smileys_dir . '/' . $set . '/' . $basename)) {
ErrorHandler::fatalLang('smiley_not_found', false);
}
@@ -719,51 +705,55 @@ public function add()
// Find the position on the right.
$smiley_order = '0';
- if ($_POST['smiley_location'] != 1)
- {
- $request = Db::$db->query('', '
- SELECT MAX(smiley_order) + 1
+ if ($_POST['smiley_location'] != 1) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT MAX(smiley_order) + 1
FROM {db_prefix}smileys
WHERE hidden = {int:smiley_location}
AND smiley_row = {int:first_row}',
- array(
+ [
'smiley_location' => $_POST['smiley_location'],
'first_row' => 0,
- )
+ ],
);
- list ($smiley_order) = Db::$db->fetch_row($request);
+ list($smiley_order) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- if (empty($smiley_order))
+ if (empty($smiley_order)) {
$smiley_order = '0';
+ }
}
// Add the new smiley to the main smileys table
- $new_id_smiley = Db::$db->insert('',
+ $new_id_smiley = Db::$db->insert(
+ '',
'{db_prefix}smileys',
- array(
+ [
'code' => 'string-30', 'description' => 'string-80', 'hidden' => 'int', 'smiley_order' => 'int',
- ),
- array(
+ ],
+ [
$_POST['smiley_code'], $_POST['smiley_description'], $_POST['smiley_location'], $smiley_order,
- ),
- array('id_smiley'),
- 1
+ ],
+ ['id_smiley'],
+ 1,
);
// Add the filename info to the smiley_files table
- $inserts = array();
+ $inserts = [];
- foreach ($filename_array as $set => $basename)
- $inserts[] = array($new_id_smiley, $set, $basename);
+ foreach ($filename_array as $set => $basename) {
+ $inserts[] = [$new_id_smiley, $set, $basename];
+ }
- Db::$db->insert('ignore',
+ Db::$db->insert(
+ 'ignore',
'{db_prefix}smiley_files',
- array(
+ [
'id_smiley' => 'int', 'smiley_set' => 'string-48', 'filename' => 'string-48',
- ),
+ ],
$inserts,
- array('id_smiley', 'smiley_set')
+ ['id_smiley', 'smiley_set'],
);
self::resetCache();
@@ -775,30 +765,28 @@ public function add()
Utils::$context['selected_set'] = Config::$modSettings['smiley_sets_default'];
// Get all possible filenames for the smileys.
- Utils::$context['filenames'] = array();
+ Utils::$context['filenames'] = [];
- if (self::$smileys_dir_found)
- {
- foreach (self::$smiley_sets as $smiley_set)
- {
- if (!file_exists(self::$smileys_dir . '/' . $smiley_set['raw_path']))
+ if (self::$smileys_dir_found) {
+ foreach (self::$smiley_sets as $smiley_set) {
+ if (!file_exists(self::$smileys_dir . '/' . $smiley_set['raw_path'])) {
continue;
+ }
$dir = dir(self::$smileys_dir . '/' . $smiley_set['raw_path']);
- while ($entry = $dir->read())
- {
+ while ($entry = $dir->read()) {
$entry_info = pathinfo($entry);
- if (empty($entry_info['filename']) || empty($entry_info['extension']))
+ if (empty($entry_info['filename']) || empty($entry_info['extension'])) {
continue;
+ }
- if (empty(Utils::$context['filenames'][$smiley_set['path']][self::sanitizeFileName($entry_info['filename'])]) && in_array(strtolower($entry_info['extension']), self::$allowed_extenions))
- {
- Utils::$context['filenames'][$smiley_set['path']][self::sanitizeFileName($entry_info['filename'])] = array(
+ if (empty(Utils::$context['filenames'][$smiley_set['path']][self::sanitizeFileName($entry_info['filename'])]) && in_array(strtolower($entry_info['extension']), self::$allowed_extenions)) {
+ Utils::$context['filenames'][$smiley_set['path']][self::sanitizeFileName($entry_info['filename'])] = [
'id' => Utils::htmlspecialchars($entry),
'selected' => $entry_info['filename'] == 'smiley' && $smiley_set['path'] == Utils::$context['selected_set'],
- );
+ ];
}
}
@@ -811,14 +799,14 @@ public function add()
}
// Create a new smiley from scratch.
- Utils::$context['current_smiley'] = array(
+ Utils::$context['current_smiley'] = [
'id' => 0,
'code' => '',
'filename' => Utils::$context['filenames'][Utils::$context['selected_set']]['smiley']['id'],
'description' => Lang::$txt['smileys_default_description'],
'location' => 0,
'is_new' => true,
- );
+ ];
}
/**
@@ -830,204 +818,203 @@ public function edit()
Menu::$loaded['admin']['current_subsection'] = 'editsmileys';
// Submitting a form?
- if (isset($_POST['smiley_save']) || isset($_POST['smiley_action']) || isset($_POST['deletesmiley']))
- {
+ if (isset($_POST['smiley_save']) || isset($_POST['smiley_action']) || isset($_POST['deletesmiley'])) {
User::$me->checkSession();
// Changing the selected smileys?
- if (isset($_POST['smiley_action']) && !empty($_POST['checked_smileys']))
- {
- foreach ($_POST['checked_smileys'] as $id => $smiley_id)
+ if (isset($_POST['smiley_action']) && !empty($_POST['checked_smileys'])) {
+ foreach ($_POST['checked_smileys'] as $id => $smiley_id) {
$_POST['checked_smileys'][$id] = (int) $smiley_id;
+ }
- if ($_POST['smiley_action'] == 'delete')
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}smileys
+ if ($_POST['smiley_action'] == 'delete') {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}smileys
WHERE id_smiley IN ({array_int:checked_smileys})',
- array(
+ [
'checked_smileys' => $_POST['checked_smileys'],
- )
+ ],
);
- Db::$db->query('', '
- DELETE FROM {db_prefix}smiley_files
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}smiley_files
WHERE id_smiley IN ({array_int:checked_smileys})',
- array(
+ [
'checked_smileys' => $_POST['checked_smileys'],
- )
+ ],
);
}
// Changing the status of the smiley?
- else
- {
+ else {
// Check it's a valid type.
- $displayTypes = array(
+ $displayTypes = [
'post' => 0,
'hidden' => 1,
- 'popup' => 2
- );
+ 'popup' => 2,
+ ];
- if (isset($displayTypes[$_POST['smiley_action']]))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}smileys
+ if (isset($displayTypes[$_POST['smiley_action']])) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}smileys
SET hidden = {int:display_type}
WHERE id_smiley IN ({array_int:checked_smileys})',
- array(
+ [
'checked_smileys' => $_POST['checked_smileys'],
'display_type' => $displayTypes[$_POST['smiley_action']],
- )
+ ],
);
}
}
}
// Create/modify a smiley.
- elseif (isset($_POST['smiley']))
- {
+ elseif (isset($_POST['smiley'])) {
// Is it a delete?
- if (!empty($_POST['deletesmiley']) && $_POST['smiley'] == (int) $_POST['smiley'])
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}smileys
+ if (!empty($_POST['deletesmiley']) && $_POST['smiley'] == (int) $_POST['smiley']) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}smileys
WHERE id_smiley = {int:current_smiley}',
- array(
+ [
'current_smiley' => $_POST['smiley'],
- )
+ ],
);
- Db::$db->query('', '
- DELETE FROM {db_prefix}smiley_files
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}smiley_files
WHERE id_smiley = {int:current_smiley}',
- array(
+ [
'current_smiley' => $_POST['smiley'],
- )
+ ],
);
}
// Otherwise an edit.
- else
- {
- foreach (array('smiley_code', 'smiley_description') as $key)
+ else {
+ foreach (['smiley_code', 'smiley_description'] as $key) {
$_POST[$key] = Utils::normalize($_POST[$key]);
+ }
$_POST['smiley'] = (int) $_POST['smiley'];
$_POST['smiley_code'] = Utils::htmlTrimRecursive($_POST['smiley_code']);
$_POST['smiley_location'] = empty($_POST['smiley_location']) || $_POST['smiley_location'] > 2 || $_POST['smiley_location'] < 0 ? 0 : (int) $_POST['smiley_location'];
// Make sure some code was entered.
- if (empty($_POST['smiley_code']))
+ if (empty($_POST['smiley_code'])) {
ErrorHandler::fatalLang('smiley_has_no_code', false);
+ }
// If upload a new smiley image, check that smiley set folders are writable for the sets with new images.
- $writeErrors = array();
+ $writeErrors = [];
- foreach ($_FILES['smiley_upload']['name'] as $set => $name)
- {
- if (!empty($name) && !is_writable(self::$smileys_dir . '/' . $set))
+ foreach ($_FILES['smiley_upload']['name'] as $set => $name) {
+ if (!empty($name) && !is_writable(self::$smileys_dir . '/' . $set)) {
$writeErrors[] = $set;
+ }
}
- if (!empty($writeErrors))
- {
- ErrorHandler::fatalLang('smileys_upload_error_notwritable', false, array(implode(', ', $writeErrors)));
+ if (!empty($writeErrors)) {
+ ErrorHandler::fatalLang('smileys_upload_error_notwritable', false, [implode(', ', $writeErrors)]);
}
- foreach (self::$smiley_sets as $set => $smiley_set)
- {
- if (empty($_FILES['smiley_upload']['name'][$set]))
+ foreach (self::$smiley_sets as $set => $smiley_set) {
+ if (empty($_FILES['smiley_upload']['name'][$set])) {
continue;
+ }
- foreach ($this->moveImageIntoPlace($_FILES['smiley_upload']['name'][$set], $_FILES['smiley_upload']['tmp_name'][$set], array($set)) as $dir => $destination_name)
- {
+ foreach ($this->moveImageIntoPlace($_FILES['smiley_upload']['name'][$set], $_FILES['smiley_upload']['tmp_name'][$set], [$set]) as $dir => $destination_name) {
// Overwrite smiley filename with uploaded filename
$_POST['smiley_filename'][$dir] = $destination_name;
}
}
// Make sure all submitted filenames are clean.
- $filenames = array();
+ $filenames = [];
- foreach ($_POST['smiley_filename'] as $posted_set => $posted_filename)
- {
+ foreach ($_POST['smiley_filename'] as $posted_set => $posted_filename) {
$posted_set = self::sanitizeFileName($posted_set);
$posted_filename = self::sanitizeFileName($posted_filename);
// Make sure the set already exists.
- if (!isset(self::$smiley_sets[$posted_set]))
+ if (!isset(self::$smiley_sets[$posted_set])) {
continue;
+ }
$filenames[$posted_set] = pathinfo($posted_filename, PATHINFO_BASENAME);
}
// Fill in any missing sets.
- foreach (self::$smiley_sets as $set => $smiley_set)
- {
+ foreach (self::$smiley_sets as $set => $smiley_set) {
// Uh-oh, something is missing.
- if (empty($filenames[$set]))
- {
+ if (empty($filenames[$set])) {
// Try to make it the same as the default set.
- if (!empty($filenames[Config::$modSettings['smiley_sets_default']]))
- {
+ if (!empty($filenames[Config::$modSettings['smiley_sets_default']])) {
$filenames[$set] = $filenames[Config::$modSettings['smiley_sets_default']];
}
// As a last resort, just try to get whatever the first one is.
- elseif (!empty($filenames))
- {
+ elseif (!empty($filenames)) {
$filenames[$set] = reset($filenames);
}
}
}
// Can't do anything without filenames for the smileys.
- if (empty($filenames))
+ if (empty($filenames)) {
ErrorHandler::fatalLang('smiley_has_no_filename', false);
+ }
// Check whether the new code has duplicates. It should be unique.
- $request = Db::$db->query('', '
- SELECT id_smiley
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_smiley
FROM {db_prefix}smileys
WHERE code = {raw:mysql_binary_type} {string:smiley_code}' . (empty($_POST['smiley']) ? '' : '
AND id_smiley != {int:current_smiley}'),
- array(
+ [
'current_smiley' => $_POST['smiley'],
'mysql_binary_type' => Db::$db->title == MYSQL_TITLE ? 'BINARY' : '',
'smiley_code' => $_POST['smiley_code'],
- )
+ ],
);
- if (Db::$db->num_rows($request) > 0)
- {
+
+ if (Db::$db->num_rows($request) > 0) {
ErrorHandler::fatalLang('smiley_not_unique', false);
}
Db::$db->free_result($request);
- Db::$db->query('', '
- UPDATE {db_prefix}smileys
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}smileys
SET
code = {string:smiley_code},
description = {string:smiley_description},
hidden = {int:smiley_location}
WHERE id_smiley = {int:current_smiley}',
- array(
+ [
'smiley_location' => $_POST['smiley_location'],
'current_smiley' => $_POST['smiley'],
'smiley_code' => $_POST['smiley_code'],
'smiley_description' => $_POST['smiley_description'],
- )
+ ],
);
// Update filename info in the smiley_files table
- $inserts = array();
+ $inserts = [];
- foreach ($filenames as $set => $filename)
- $inserts[] = array($_POST['smiley'], $set, $filename);
+ foreach ($filenames as $set => $filename) {
+ $inserts[] = [$_POST['smiley'], $set, $filename];
+ }
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}smiley_files',
- array(
+ [
'id_smiley' => 'int', 'smiley_set' => 'string-48', 'filename' => 'string-48',
- ),
+ ],
$inserts,
- array('id_smiley', 'smiley_set')
+ ['id_smiley', 'smiley_set'],
);
}
}
@@ -1036,14 +1023,13 @@ public function edit()
}
// Prepare overview of all (custom) smileys.
- if ($this->subaction == 'editsmileys')
- {
+ if ($this->subaction == 'editsmileys') {
// Determine the language specific sort order of smiley locations.
- $smiley_locations = array(
+ $smiley_locations = [
Lang::$txt['smileys_location_form'],
Lang::$txt['smileys_location_hidden'],
Lang::$txt['smileys_location_popup'],
- );
+ ];
asort($smiley_locations);
@@ -1051,8 +1037,7 @@ public function edit()
$smileyset_option_list = '
';
- $listOptions = array(
+ $listOptions = [
'id' => 'smiley_list',
'title' => Lang::$txt['smileys_edit'],
'items_per_page' => 40,
'base_href' => Config::$scripturl . '?action=admin;area=smileys;sa=editsmileys',
'default_sort_col' => 'filename',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getSmileys',
- ),
- 'get_count' => array(
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getNumSmileys',
- ),
+ ],
'no_items_label' => Lang::$txt['smileys_no_entries'],
- 'columns' => array(
- 'picture' => array(
- 'data' => array(
- 'function' => function($rowData)
- {
+ 'columns' => [
+ 'picture' => [
+ 'data' => [
+ 'function' => function ($rowData) {
$return = '';
- foreach ($rowData['filename_array'] as $set => $filename)
- {
+ foreach ($rowData['filename_array'] as $set => $filename) {
$return .= ' ';
}
return $return;
},
'class' => 'centercol',
- ),
- ),
- 'smileys_code' => array(
- 'header' => array(
+ ],
+ ],
+ 'smileys_code' => [
+ 'header' => [
'value' => Lang::$txt['smileys_code'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db_htmlsafe' => 'code',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'code',
'reverse' => 'code DESC',
- ),
- ),
- 'filename' => array(
- 'header' => array(
+ ],
+ ],
+ 'filename' => [
+ 'header' => [
'value' => Lang::$txt['smileys_filename'],
- ),
- 'data' => array(
- 'function' => function($rowData)
- {
+ ],
+ 'data' => [
+ 'function' => function ($rowData) {
$return = ' ' . $rowData['filename'] . '';
- foreach ($rowData['filename_array'] as $set => $filename)
- {
+ foreach ($rowData['filename_array'] as $set => $filename) {
$return .= ' ' . $filename . '';
}
return $return;
},
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'filename',
'reverse' => 'filename DESC',
- ),
- ),
- 'location' => array(
- 'header' => array(
+ ],
+ ],
+ 'location' => [
+ 'header' => [
'value' => Lang::$txt['smileys_location'],
- ),
- 'data' => array(
- 'function' => function($rowData)
- {
- if (empty($rowData['hidden']))
+ ],
+ 'data' => [
+ 'function' => function ($rowData) {
+ if (empty($rowData['hidden'])) {
return Lang::$txt['smileys_location_form'];
+ }
- if ($rowData['hidden'] == 1)
+ if ($rowData['hidden'] == 1) {
return Lang::$txt['smileys_location_hidden'];
+ }
return Lang::$txt['smileys_location_popup'];
},
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => Db::$db->custom_order('hidden', array_keys($smiley_locations)),
'reverse' => Db::$db->custom_order('hidden', array_keys($smiley_locations), true),
- ),
- ),
- 'description' => array(
- 'header' => array(
+ ],
+ ],
+ 'description' => [
+ 'header' => [
'value' => Lang::$txt['smileys_description'],
- ),
- 'data' => array(
- 'function' => function($rowData)
- {
- if (!self::$smileys_dir_found)
+ ],
+ 'data' => [
+ 'function' => function ($rowData) {
+ if (!self::$smileys_dir_found) {
return Utils::htmlspecialchars($rowData['description']);
+ }
// Check if there are smileys missing in some sets.
- $missing_sets = array();
+ $missing_sets = [];
- foreach (self::$smiley_sets as $smiley_set)
- {
+ foreach (self::$smiley_sets as $smiley_set) {
if (
empty($rowData['filename_array'][$smiley_set['path']])
|| !file_exists(
@@ -1167,76 +1148,74 @@ public function edit()
'%1$s/%2$s/%3$s',
self::$smileys_dir,
$smiley_set['path'],
- $rowData['filename_array'][$smiley_set['path']]
- )
+ $rowData['filename_array'][$smiley_set['path']],
+ ),
)
- )
- {
+ ) {
$missing_sets[] = $smiley_set['path'];
}
}
$description = Utils::htmlspecialchars($rowData['description']);
- if (!empty($missing_sets))
- {
+ if (!empty($missing_sets)) {
$description .= sprintf(
' %1$s: %2$s',
Lang::$txt['smileys_not_found_in_set'],
- implode(', ', $missing_sets)
+ implode(', ', $missing_sets),
);
}
return $description;
},
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'description',
'reverse' => 'description DESC',
- ),
- ),
- 'modify' => array(
- 'header' => array(
+ ],
+ ],
+ 'modify' => [
+ 'header' => [
'value' => Lang::$txt['smileys_modify'],
'class' => 'centercol',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' ' . Lang::$txt['smileys_modify'] . '',
- 'params' => array(
+ 'params' => [
'id_smiley' => false,
- ),
- ),
+ ],
+ ],
'class' => 'centercol',
- ),
- ),
- 'check' => array(
- 'header' => array(
+ ],
+ ],
+ 'check' => [
+ 'header' => [
'value' => ' ',
'class' => 'centercol',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' ',
- 'params' => array(
+ 'params' => [
'id_smiley' => false,
- ),
- ),
+ ],
+ ],
'class' => 'centercol',
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . '?action=admin;area=smileys;sa=editsmileys',
'name' => 'smileyForm',
- ),
- 'additional_rows' => array(
- array(
+ ],
+ 'additional_rows' => [
+ [
'position' => 'above_column_headers',
'value' => $smileyset_option_list,
'class' => 'righttext',
- ),
- array(
+ ],
+ [
'position' => 'below_table_data',
'value' => '
' => "\n", '' => "\n", '[' => '[', ']' => ']')))));
+ $message = trim(Utils::htmlspecialcharsDecode(strip_tags(strtr(BBCodeParser::load()->parse($message, false, $id_msg), [' ' => "\n", '' => "\n", '' => "\n", '[' => '[', ']' => ']']))));
// Select the email addresses for this batch.
- $announcements = array();
- $rows = array();
+ $announcements = [];
+ $rows = [];
- $request = Db::$db->query('', '
- SELECT mem.id_member, mem.email_address, mem.lngfile
+ $request = Db::$db->query(
+ '',
+ 'SELECT mem.id_member, mem.email_address, mem.lngfile
FROM {db_prefix}members AS mem
WHERE (mem.id_group IN ({array_int:group_list}) OR mem.id_post_group IN ({array_int:group_list}) OR FIND_IN_SET({raw:additional_group_list}, mem.additional_groups) != 0)
AND mem.is_activated = {int:is_activated}
AND mem.id_member > {int:start}
ORDER BY mem.id_member
LIMIT {int:chunk_size}',
- array(
+ [
'group_list' => $_POST['who'],
'is_activated' => 1,
'start' => Utils::$context['start'],
'additional_group_list' => implode(', mem.additional_groups) != 0 OR FIND_IN_SET(', $_POST['who']),
// @todo Might need an interface?
'chunk_size' => 500,
- )
+ ],
);
+
// All members have received a mail. Go to the next screen.
- if (Db::$db->num_rows($request) == 0)
- {
+ if (Db::$db->num_rows($request) == 0) {
Db::$db->free_result($request);
- Logging::logAction('announce_topic', array('topic' => Topic::$topic_id), 'user');
+ Logging::logAction('announce_topic', ['topic' => Topic::$topic_id], 'user');
- if (!empty($_REQUEST['move']) && User::$me->allowedTo('move_any'))
- {
+ if (!empty($_REQUEST['move']) && User::$me->allowedTo('move_any')) {
Utils::redirectexit('action=movetopic;topic=' . Topic::$topic_id . '.0' . (empty($_REQUEST['goback']) ? '' : ';goback'));
- }
- elseif (!empty($_REQUEST['goback']))
- {
+ } elseif (!empty($_REQUEST['goback'])) {
Utils::redirectexit('topic=' . Topic::$topic_id . '.new;boardseen#new', BrowserDetector::isBrowser('ie'));
- }
- else
- {
+ } else {
Utils::redirectexit('board=' . Board::$info->id . '.0');
}
}
+
// Loop through all members that'll receive an announcement in this batch.
- while ($row = Db::$db->fetch_assoc($request))
- {
+ while ($row = Db::$db->fetch_assoc($request)) {
$rows[$row['id_member']] = $row;
}
Db::$db->free_result($request);
@@ -237,51 +236,47 @@ public function send(): void
// Load their alert preferences
$prefs = Notify::getNotifyPrefs(array_keys($rows), 'announcements', true);
- foreach ($rows as $row)
- {
+ foreach ($rows as $row) {
Utils::$context['start'] = $row['id_member'];
// Force them to have it?
- if (empty($prefs[$row['id_member']]['announcements']))
+ if (empty($prefs[$row['id_member']]['announcements'])) {
continue;
+ }
$cur_language = empty($row['lngfile']) || empty(Config::$modSettings['userLanguage']) ? Lang::$default : $row['lngfile'];
// If the language wasn't defined yet, load it and compose a notification message.
- if (!isset($announcements[$cur_language]))
- {
- $replacements = array(
+ if (!isset($announcements[$cur_language])) {
+ $replacements = [
'TOPICSUBJECT' => Utils::$context['topic_subject'],
'MESSAGE' => $message,
'TOPICLINK' => Config::$scripturl . '?topic=' . Topic::$topic_id . '.0',
'UNSUBSCRIBELINK' => Config::$scripturl . '?action=notifyannouncements;u={UNSUBSCRIBE_ID};token={UNSUBSCRIBE_TOKEN}',
- );
+ ];
$emaildata = Mail::loadEmailTemplate('new_announcement', $replacements, $cur_language);
- $announcements[$cur_language] = array(
+ $announcements[$cur_language] = [
'subject' => $emaildata['subject'],
'body' => $emaildata['body'],
'is_html' => $emaildata['is_html'],
- 'recipients' => array(),
- );
+ 'recipients' => [],
+ ];
}
$announcements[$cur_language]['recipients'][$row['id_member']] = $row['email_address'];
}
// For each language send a different mail - low priority...
- foreach ($announcements as $lang => $mail)
- {
- foreach ($mail['recipients'] as $member_id => $member_email)
- {
+ foreach ($announcements as $lang => $mail) {
+ foreach ($mail['recipients'] as $member_id => $member_email) {
$token = Notify::createUnsubscribeToken($member_id, $member_email, 'announcements');
- $body = str_replace(array('{UNSUBSCRIBE_ID}', '{UNSUBSCRIBE_TOKEN}'), array($member_id, $token), $mail['body']);
+ $body = str_replace(['{UNSUBSCRIBE_ID}', '{UNSUBSCRIBE_TOKEN}'], [$member_id, $token], $mail['body']);
Mail::send($member_email, $mail['subject'], $body, null, null, false, 5);
}
-
}
Utils::$context['percentage_done'] = round(100 * Utils::$context['start'] / Config::$modSettings['latestMember'], 1);
@@ -292,8 +287,9 @@ public function send(): void
Utils::$context['sub_template'] = 'announcement_send';
// Go back to the correct language for the user ;).
- if (!empty(Config::$modSettings['userLanguage']))
+ if (!empty(Config::$modSettings['userLanguage'])) {
Lang::load('Post');
+ }
}
/***********************
@@ -307,8 +303,9 @@ public function send(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -321,6 +318,26 @@ public static function call(): void
self::load()->execute();
}
+ /**
+ * Backward compatibility wrapper for the selectgroup sub-action.
+ */
+ public static function selectGroup(): void
+ {
+ self::load();
+ self::$obj->subaction = 'selectgroup';
+ self::$obj->execute();
+ }
+
+ /**
+ * Backward compatibility wrapper for the send sub-action.
+ */
+ public static function announcementSend(): void
+ {
+ self::load();
+ self::$obj->subaction = 'send';
+ self::$obj->execute();
+ }
+
/******************
* Internal methods
******************/
@@ -334,21 +351,24 @@ protected function __construct()
User::$me->validateSession();
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
ErrorHandler::fatalLang('topic_gone', false);
+ }
Lang::load('Post');
Theme::loadTemplate('Post');
Utils::$context['page_title'] = Lang::$txt['announce_topic'];
- 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__ . '\Announce::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Announce::exportStatic')) {
Announce::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/AttachmentApprove.php b/Sources/Actions/AttachmentApprove.php
index c8ef3dc8e7..7f741f7731 100644
--- a/Sources/Actions/AttachmentApprove.php
+++ b/Sources/Actions/AttachmentApprove.php
@@ -13,13 +13,12 @@
namespace SMF\Actions;
-use SMF\BackwardCompatibility;
-
use SMF\Attachment;
+use SMF\BackwardCompatibility;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Allows the moderator to approve or reject attachments.
@@ -33,12 +32,11 @@ class AttachmentApprove implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ApproveAttach',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -67,62 +65,61 @@ public function execute(): void
// If it approve or delete?
$is_approve = !isset($_GET['sa']) || $_GET['sa'] != 'reject';
- $attachments = array();
+ $attachments = [];
// If we are approving all ID's in a message, get the ID's.
- if ($_GET['sa'] == 'all' && !empty($_GET['mid']))
- {
+ if ($_GET['sa'] == 'all' && !empty($_GET['mid'])) {
$id_msg = (int) $_GET['mid'];
- $request = Db::$db->query('', '
- SELECT id_attach
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_attach
FROM {db_prefix}attachments
WHERE id_msg = {int:id_msg}
AND approved = {int:is_approved}
AND attachment_type = {int:attachment_type}',
- array(
+ [
'id_msg' => $id_msg,
'is_approved' => 0,
'attachment_type' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$attachments[] = $row['id_attach'];
}
Db::$db->free_result($request);
- }
- elseif (!empty($_GET['aid']))
- {
+ } elseif (!empty($_GET['aid'])) {
$attachments[] = (int) $_GET['aid'];
}
- if (empty($attachments))
+ if (empty($attachments)) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Now we have some ID's cleaned and ready to approve, but first - let's check we have permission!
$allowed_boards = User::$me->boardsAllowedTo('approve_posts');
// Validate the attachments exist and are the right approval state.
- $request = Db::$db->query('', '
- SELECT a.id_attach, m.id_board, m.id_msg, m.id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT a.id_attach, m.id_board, m.id_msg, m.id_topic
FROM {db_prefix}attachments AS a
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
WHERE a.id_attach IN ({array_int:attachments})
AND a.attachment_type = {int:attachment_type}
AND a.approved = {int:is_approved}',
- array(
+ [
'attachments' => $attachments,
'attachment_type' => 0,
'is_approved' => 0,
- )
+ ],
);
- $attachments = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $attachments = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// We can only add it if we can approve in this board!
- if ($allowed_boards = array(0) || in_array($row['id_board'], $allowed_boards))
- {
+ if ($allowed_boards = [0] || in_array($row['id_board'], $allowed_boards)) {
$attachments[] = $row['id_attach'];
// Also come up with the redirection URL.
@@ -131,18 +128,16 @@ public function execute(): void
}
Db::$db->free_result($request);
- if (empty($attachments))
+ if (empty($attachments)) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Finally, we are there. Follow through!
- if ($is_approve)
- {
+ if ($is_approve) {
// Checked and deemed worthy.
Attachment::approve($attachments);
- }
- else
- {
- Attachment::remove(array('id_attach' => $attachments, 'do_logging' => true));
+ } else {
+ Attachment::remove(['id_attach' => $attachments, 'do_logging' => true]);
}
// Return to the topic....
@@ -160,8 +155,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;
}
@@ -187,7 +183,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\AttachmentApprove::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\AttachmentApprove::exportStatic')) {
AttachmentApprove::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/AttachmentDownload.php b/Sources/Actions/AttachmentDownload.php
index eccc091713..32aacca34d 100644
--- a/Sources/Actions/AttachmentDownload.php
+++ b/Sources/Actions/AttachmentDownload.php
@@ -13,17 +13,16 @@
namespace SMF\Actions;
-use SMF\BackwardCompatibility;
-
use SMF\Attachment;
+use SMF\BackwardCompatibility;
use SMF\BrowserDetector;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* Downloads an avatar or attachment based on $_GET['attach'], and increments the download count.
@@ -42,12 +41,11 @@ class AttachmentDownload implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'showAttachment',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -96,31 +94,29 @@ public function execute(): void
header_remove('content-encoding');
// We need a valid ID.
- if (empty($this->id))
- {
+ if (empty($this->id)) {
Utils::sendHttpStatus(404, 'File Not Found');
+
die('404 File Not Found');
}
// No access in strict maintenance mode.
- if (!empty(Config::$maintenance) && Config::$maintenance == 2)
- {
+ if (!empty(Config::$maintenance) && Config::$maintenance == 2) {
Utils::sendHttpStatus(404, 'File Not Found');
+
die('404 File Not Found');
}
// Use cache when possible.
- if (($cache = CacheApi::get('attachment_lookup_id-' . $this->id)) != null)
- {
- list ($file, $thumbFile) = $cache;
+ if (($cache = CacheApi::get('attachment_lookup_id-' . $this->id)) != null) {
+ list($file, $thumbFile) = $cache;
$file = @unserialize($file);
$thumbFile = @unserialize($thumbFile);
}
// Get the info from the DB.
- if (empty($file) || empty($thumbFile) && !empty($file->thumb))
- {
+ if (empty($file) || empty($thumbFile) && !empty($file->thumb)) {
/*
* Do we have a hook wanting to use our attachment system?
*
@@ -129,13 +125,13 @@ public function execute(): void
* SMF\Attachment::load() method.
*/
$request = null;
- IntegrationHook::call('integrate_download_request', array(&$request));
- if (!is_null($request) && Db::$db->is_resource($request))
- {
+ IntegrationHook::call('integrate_download_request', [&$request]);
+
+ if (!is_null($request) && Db::$db->is_resource($request)) {
// No attachment has been found.
- if (Db::$db->num_rows($request) == 0)
- {
+ if (Db::$db->num_rows($request) == 0) {
Utils::sendHttpStatus(404, 'File Not Found');
+
die('404 File Not Found');
}
@@ -144,46 +140,41 @@ public function execute(): void
$file = new Attachment(0, $row);
$file->setFileProperties();
- }
- else
- {
+ } else {
Attachment::load($this->id);
- if (!isset(Attachment::$loaded[$this->id]))
- {
+ if (!isset(Attachment::$loaded[$this->id])) {
Utils::sendHttpStatus(404, 'File Not Found');
+
die('404 File Not Found');
}
$file = Attachment::$loaded[$this->id];
- $file->set(array('source' => 'SMF'));
+ $file->set(['source' => 'SMF']);
$file->setFileProperties();
}
- if (!empty($file->thumb))
- {
+ if (!empty($file->thumb)) {
Attachment::load($file->thumb);
$thumbFile = Attachment::$loaded[$file->thumb];
- $thumbFile->set(array('source' => 'SMF'));
+ $thumbFile->set(['source' => 'SMF']);
$thumbFile->setFileProperties();
}
// Cache it.
- if (!empty($file) || !empty($thumbFile))
- CacheApi::put('attachment_lookup_id-' . $this->id, array(serialize($file ?? null), serialize($thumbFile ?? null)), mt_rand(850, 900));
+ if (!empty($file) || !empty($thumbFile)) {
+ CacheApi::put('attachment_lookup_id-' . $this->id, [serialize($file ?? null), serialize($thumbFile ?? null)], mt_rand(850, 900));
+ }
}
// Can they see attachments on this board?
- if (!empty($file->msg))
- {
+ if (!empty($file->msg)) {
// Special case for profile exports.
- if (!empty(Utils::$context['attachment_allow_hidden_boards']))
- {
- $boards_allowed = array(0);
+ if (!empty(Utils::$context['attachment_allow_hidden_boards'])) {
+ $boards_allowed = [0];
}
// Check permissions and board access.
- elseif (($boards_allowed = CacheApi::get('view_attachment_boards_id-' . User::$me->id)) == null)
- {
+ elseif (($boards_allowed = CacheApi::get('view_attachment_boards_id-' . User::$me->id)) == null) {
$boards_allowed = User::$me->boardsAllowedTo('view_attachments');
CacheApi::put('view_attachment_boards_id-' . User::$me->id, $boards_allowed, mt_rand(850, 900));
}
@@ -210,122 +201,128 @@ public function execute(): void
!empty($file->msg)
&& (
empty($file->board)
- || ($boards_allowed !== array(0) && !in_array($file->board, $boards_allowed))
+ || ($boards_allowed !== [0] && !in_array($file->board, $boards_allowed))
)
)
)
// We are not previewing an attachment.
&& !isset($_SESSION['attachments_can_preview'][$this->id])
- )
- {
+ ) {
Utils::sendHttpStatus(404, 'File Not Found');
+
die('404 File Not Found');
}
// If attachment is unapproved, see if user is allowed to approve
- if (!$file->approved && Config::$modSettings['postmod_active'] && !User::$me->allowedTo('approve_posts'))
- {
- $request = Db::$db->query('', '
- SELECT id_member
+ if (!$file->approved && Config::$modSettings['postmod_active'] && !User::$me->allowedTo('approve_posts')) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}messages
WHERE id_msg = {int:id_msg}
LIMIT 1',
- array(
+ [
'id_msg' => $file->msg,
- )
+ ],
);
$id_member = Db::$db->fetch_assoc($request)['id_member'];
Db::$db->free_result($request);
// Let users see own unapproved attachments
- if ($id_member != User::$me->id)
- {
+ if ($id_member != User::$me->id) {
Utils::sendHttpStatus(403, 'Forbidden');
+
die('403 Forbidden');
}
}
// Replace the normal file with its thumbnail if it has one!
- if (!empty($this->showThumb) && !empty($thumbFile))
+ if (!empty($this->showThumb) && !empty($thumbFile)) {
$file = $thumbFile;
+ }
// No point in a nicer message, because this is supposed to be an attachment anyway...
- if (empty($file->exists))
- {
+ if (empty($file->exists)) {
Utils::sendHttpStatus(404, 'File Not Found');
+
die('404 File Not Found');
}
// If it hasn't been modified since the last time this attachment was retrieved, there's no need to display it again.
- if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
- {
+ if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
list($modified_since) = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
- if (!empty($file->mtime) && strtotime($modified_since) >= $file->mtime)
- {
+
+ if (!empty($file->mtime) && strtotime($modified_since) >= $file->mtime) {
ob_end_clean();
header_remove('content-encoding');
// Answer the question - no, it hasn't been modified ;).
Utils::sendHttpStatus(304);
+
exit;
}
}
// Check whether the ETag was sent back, and cache based on that...
- if (!empty($file->etag) && !empty($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $file->etag) !== false)
- {
+ if (!empty($file->etag) && !empty($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $file->etag) !== false) {
ob_end_clean();
header_remove('content-encoding');
Utils::sendHttpStatus(304);
+
exit;
}
// If this is a partial download, we need to determine what data range to send
$range = 0;
- if (isset($_SERVER['HTTP_RANGE']))
- {
- list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
- list($range) = explode(",", $range, 2);
- list($range, $range_end) = explode("-", $range);
+
+ if (isset($_SERVER['HTTP_RANGE'])) {
+ list($a, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
+ list($range) = explode(',', $range, 2);
+ list($range, $range_end) = explode('-', $range);
$range = intval($range);
$range_end = !$range_end ? $file->size - 1 : intval($range_end);
$length = $range_end - $range + 1;
}
// Update the download counter (unless it's a thumbnail or resuming an incomplete download).
- if ($file->type != 3 && empty($this->showThumb) && empty($_REQUEST['preview']) && $range === 0 && empty(Utils::$context['skip_downloads_increment']))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}attachments
+ if ($file->type != 3 && empty($this->showThumb) && empty($_REQUEST['preview']) && $range === 0 && empty(Utils::$context['skip_downloads_increment'])) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}attachments
SET downloads = downloads + 1
WHERE id_attach = {int:id_attach}',
- array(
+ [
'id_attach' => $this->id,
- )
+ ],
);
}
// Make sure the mime type warrants an inline display.
- if (empty($file->mime_type))
+ if (empty($file->mime_type)) {
$file->mime_type = 'application/octet-stream';
+ }
- if (BrowserDetector::isBrowser('ie') || BrowserDetector::isBrowser('opera'))
- $file->mime_type = strtr($file->mime_type, array('application/octet-stream' => 'application/octetstream'));
+ if (BrowserDetector::isBrowser('ie') || BrowserDetector::isBrowser('opera')) {
+ $file->mime_type = strtr($file->mime_type, ['application/octet-stream' => 'application/octetstream']);
+ }
- if (strpos($file->mime_type, 'image/') !== 0)
+ if (strpos($file->mime_type, 'image/') !== 0) {
unset($_REQUEST['image']);
+ }
// On mobile devices, audio and video should be served inline so the browser can play them.
- if (isset($_REQUEST['image']) || (BrowserDetector::isBrowser('is_mobile') && (strpos($file->mime_type, 'audio/') === 0 || strpos($file->mime_type, 'video/') === 0)))
+ if (isset($_REQUEST['image']) || (BrowserDetector::isBrowser('is_mobile') && (strpos($file->mime_type, 'audio/') === 0 || strpos($file->mime_type, 'video/') === 0))) {
$file->disposition = 'inline';
- else
+ } else {
$file->disposition = 'attachment';
+ }
// If necessary, prepend the attachment ID to the file name.
- if (!empty(Utils::$context['prepend_attachment_id']))
+ if (!empty(Utils::$context['prepend_attachment_id'])) {
$file->filename = $_REQUEST['attach'] . ' - ' . $file->filename;
+ }
Utils::emitFile($file, $this->showThumb);
}
@@ -341,8 +338,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;
}
@@ -365,11 +363,13 @@ public static function call(): void
protected function __construct()
{
// Some defaults that we need.
- if (!isset(Utils::$context['character_set']))
+ if (!isset(Utils::$context['character_set'])) {
Utils::$context['character_set'] = empty(Config::$modSettings['global_character_set']) ? (empty(Lang::$txt['lang_character_set']) ? 'ISO-8859-1' : Lang::$txt['lang_character_set']) : Config::$modSettings['global_character_set'];
+ }
- if (!isset(Utils::$context['utf8']))
+ if (!isset(Utils::$context['utf8'])) {
Utils::$context['utf8'] = Utils::$context['character_set'] === 'UTF-8';
+ }
// Which attachment was requested?
$this->id = $_REQUEST['attach'] = isset($_REQUEST['attach']) ? (int) $_REQUEST['attach'] : (int) (isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0);
@@ -380,7 +380,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\AttachmentDownload::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\AttachmentDownload::exportStatic')) {
AttachmentDownload::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/AttachmentUpload.php b/Sources/Actions/AttachmentUpload.php
index 099fdae544..4dad251024 100644
--- a/Sources/Actions/AttachmentUpload.php
+++ b/Sources/Actions/AttachmentUpload.php
@@ -15,12 +15,12 @@
use SMF\Attachment;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This class handles adding/deleting attachments
@@ -28,79 +28,79 @@
class AttachmentUpload implements ActionInterface
{
/**
- * @var int $_msg The ID of the message this attachment is associated with
+ * @var int The ID of the message this attachment is associated with
*/
protected $_msg = 0;
/**
- * @var int|null $_board The ID of the board this attachment's post is in or null if it's not set
+ * @var int|null The ID of the board this attachment's post is in or null if it's not set
*/
protected $_board = null;
/**
- * @var string|bool $_attachmentUploadDir An array of info about attachment upload directories or false
+ * @var string|bool An array of info about attachment upload directories or false
*/
protected $_attachmentUploadDir = false;
/**
- * @var string $_attchDir The path to the current attachment directory
+ * @var string The path to the current attachment directory
*/
protected $_attchDir = '';
/**
- * @var int $_currentAttachmentUploadDir ID of the current attachment directory
+ * @var int ID of the current attachment directory
*/
protected $_currentAttachmentUploadDir;
/**
- * @var bool $_canPostAttachment Whether or not an attachment can be posted
+ * @var bool Whether or not an attachment can be posted
*/
protected $_canPostAttachment;
/**
- * @var array $_generalErrors An array of information about any errors that occurred
+ * @var array An array of information about any errors that occurred
*/
- protected $_generalErrors = array();
+ protected $_generalErrors = [];
/**
- * @var mixed $_initialError Not used?
+ * @var mixed Not used?
*/
protected $_initialError;
/**
- * @var array $_attachments Not used?
+ * @var array Not used?
*/
- protected $_attachments = array();
+ protected $_attachments = [];
/**
- * @var array $_attachResults An array of information about the results of each file
+ * @var array An array of information about the results of each file
*/
- protected $_attachResults = array();
+ protected $_attachResults = [];
/**
- * @var array $_attachSuccess An array of information about successful attachments
+ * @var array An array of information about successful attachments
*/
- protected $_attachSuccess = array();
+ protected $_attachSuccess = [];
/**
- * @var array $_response An array of response information. @used-by \sendResponse() when adding attachments
+ * @var array An array of response information. @used-by \sendResponse() when adding attachments
*/
- protected $_response = array(
+ protected $_response = [
'error' => true,
- 'data' => array(),
+ 'data' => [],
'extra' => '',
- );
+ ];
/**
- * @var array $_subActions An array of all valid sub-actions
+ * @var array An array of all valid sub-actions
*/
- protected $_subActions = array(
+ protected $_subActions = [
'add',
'delete',
- );
+ ];
/**
- * @var string|bool $_sa The current sub-action, or false if there isn't one
+ * @var string|bool The current sub-action, or false if there isn't one
*/
protected $_sa = false;
@@ -120,8 +120,9 @@ class AttachmentUpload implements ActionInterface
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -164,18 +165,16 @@ public function execute(): void
$this->_sa = !empty($_REQUEST['sa']) ? Utils::htmlspecialchars(Utils::htmlTrim($_REQUEST['sa'])) : false;
- if ($this->_canPostAttachment && $this->_sa && in_array($this->_sa, $this->_subActions))
- {
+ if ($this->_canPostAttachment && $this->_sa && in_array($this->_sa, $this->_subActions)) {
$this->{$this->_sa}();
}
// Just send a generic message.
- else
- {
- $this->setResponse(array(
+ else {
+ $this->setResponse([
'text' => $this->_sa == 'add' ? 'attach_error_title' : 'attached_file_deleted_error',
'type' => 'error',
'data' => false,
- ));
+ ]);
}
// Back to the future, oh, to the browser!
@@ -190,28 +189,28 @@ public function delete(): void
$attachID = !empty($_REQUEST['attach']) && is_numeric($_REQUEST['attach']) ? (int) $_REQUEST['attach'] : 0;
// Need something to work with.
- if (!$attachID || (!empty($_SESSION['already_attached']) && !isset($_SESSION['already_attached'][$attachID])))
- {
- $this->setResponse(array(
+ if (!$attachID || (!empty($_SESSION['already_attached']) && !isset($_SESSION['already_attached'][$attachID]))) {
+ $this->setResponse([
'text' => 'attached_file_deleted_error',
'type' => 'error',
'data' => false,
- ));
+ ]);
+
return;
}
// Lets pass some params and see what happens :P
- $affectedMessage = Attachment::remove(array('id_attach' => $attachID), '', true, true);
+ $affectedMessage = Attachment::remove(['id_attach' => $attachID], '', true, true);
// Gotta also remove the attachment from the session var.
unset($_SESSION['already_attached'][$attachID]);
// $affectedMessage returns an empty array array(0) which php treats as non empty... awesome...
- $this->setResponse(array(
+ $this->setResponse([
'text' => !empty($affectedMessage) ? 'attached_file_deleted' : 'attached_file_deleted_error',
'type' => !empty($affectedMessage) ? 'info' : 'warning',
'data' => $affectedMessage,
- ));
+ ]);
}
/**
@@ -220,13 +219,12 @@ public function delete(): void
public function add(): void
{
// You gotta be able to post attachments.
- if (!$this->_canPostAttachment)
- {
- $this->setResponse(array(
+ if (!$this->_canPostAttachment) {
+ $this->setResponse([
'text' => 'attached_file_cannot',
'type' => 'error',
'data' => false,
- ));
+ ]);
return;
}
@@ -235,8 +233,9 @@ public function add(): void
$this->processAttachments();
// The attachments was created and moved the the right folder, time to update the DB.
- if (!empty($_SESSION['temp_attachments']))
+ if (!empty($_SESSION['temp_attachments'])) {
$this->createAttach();
+ }
// Set the response.
$this->setResponse();
@@ -247,119 +246,115 @@ public function add(): void
*/
protected function processAttachments(): void
{
- if (!isset($_FILES['attachment']['name']))
- $_FILES['attachment']['tmp_name'] = array();
+ if (!isset($_FILES['attachment']['name'])) {
+ $_FILES['attachment']['tmp_name'] = [];
+ }
// If there are attachments, calculate the total size and how many.
Utils::$context['attachments']['total_size'] = 0;
Utils::$context['attachments']['quantity'] = 0;
// If this isn't a new post, check the current attachments.
- if (isset($_REQUEST['msg']))
- {
+ if (isset($_REQUEST['msg'])) {
Utils::$context['attachments']['quantity'] = count(Utils::$context['current_attachments']);
- foreach (Utils::$context['current_attachments'] as $attachment)
+ foreach (Utils::$context['current_attachments'] as $attachment) {
Utils::$context['attachments']['total_size'] += $attachment['size'];
+ }
}
// A bit of house keeping first.
- if (!empty($_SESSION['temp_attachments']) && count($_SESSION['temp_attachments']) == 1)
+ if (!empty($_SESSION['temp_attachments']) && count($_SESSION['temp_attachments']) == 1) {
unset($_SESSION['temp_attachments']);
+ }
// Our infamous SESSION var, we are gonna have soo much fun with it!
- if (!isset($_SESSION['temp_attachments']))
- $_SESSION['temp_attachments'] = array();
+ if (!isset($_SESSION['temp_attachments'])) {
+ $_SESSION['temp_attachments'] = [];
+ }
// Make sure we're uploading to the right place.
- if (!empty(Config::$modSettings['automanage_attachments']))
+ if (!empty(Config::$modSettings['automanage_attachments'])) {
Attachment::automanageCheckDirectory();
+ }
// Is the attachments folder actually there?
- if (!empty(Utils::$context['dir_creation_error']))
- {
+ if (!empty(Utils::$context['dir_creation_error'])) {
$this->_generalErrors[] = Utils::$context['dir_creation_error'];
}
// The current attach folder has some issues...
- elseif (!is_dir($this->_attchDir))
- {
+ elseif (!is_dir($this->_attchDir)) {
$this->_generalErrors[] = 'attach_folder_warning';
ErrorHandler::log(sprintf(Lang::$txt['attach_folder_admin_warning'], $this->_attchDir), 'critical');
}
// If this isn't a new post, check the current attachments.
- if (empty($this->_generalErrors) && $this->_msg)
- {
- Utils::$context['attachments'] = array();
+ if (empty($this->_generalErrors) && $this->_msg) {
+ Utils::$context['attachments'] = [];
- $request = Db::$db->query('', '
- SELECT COUNT(*), SUM(size)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*), SUM(size)
FROM {db_prefix}attachments
WHERE id_msg = {int:id_msg}
AND attachment_type = {int:attachment_type}',
- array(
+ [
'id_msg' => (int) $this->_msg,
'attachment_type' => 0,
- )
+ ],
);
list(Utils::$context['attachments']['quantity'], Utils::$context['attachments']['total_size']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- }
- else
- {
- Utils::$context['attachments'] = array(
+ } else {
+ Utils::$context['attachments'] = [
'quantity' => 0,
'total_size' => 0,
- );
+ ];
}
// Check for other general errors here.
// If we have an initial error, delete the files.
- if (!empty($this->_generalErrors))
- {
+ if (!empty($this->_generalErrors)) {
// And delete the files 'cos they ain't going nowhere.
- foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
- {
- if (file_exists($_FILES['attachment']['tmp_name'][$n]))
+ foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy) {
+ if (file_exists($_FILES['attachment']['tmp_name'][$n])) {
unlink($_FILES['attachment']['tmp_name'][$n]);
+ }
}
- $_FILES['attachment']['tmp_name'] = array();
+ $_FILES['attachment']['tmp_name'] = [];
// No point in going further with this.
return;
}
// Loop through $_FILES['attachment'] array and move each file to the current attachments folder.
- foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
- {
- if ($_FILES['attachment']['name'][$n] == '')
+ foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy) {
+ if ($_FILES['attachment']['name'][$n] == '') {
continue;
+ }
// First, let's first check for PHP upload errors.
- $errors = array();
- if (!empty($_FILES['attachment']['error'][$n]))
- {
- if ($_FILES['attachment']['error'][$n] == 2)
- {
- $errors[] = array('file_too_big', array(Config::$modSettings['attachmentSizeLimit']));
- }
- else
- {
+ $errors = [];
+
+ if (!empty($_FILES['attachment']['error'][$n])) {
+ if ($_FILES['attachment']['error'][$n] == 2) {
+ $errors[] = ['file_too_big', [Config::$modSettings['attachmentSizeLimit']]];
+ } else {
ErrorHandler::log($_FILES['attachment']['name'][$n] . ': ' . Lang::$txt['php_upload_error_' . $_FILES['attachment']['error'][$n]]);
}
// Log this one, because...
- if ($_FILES['attachment']['error'][$n] == 6)
- {
+ if ($_FILES['attachment']['error'][$n] == 6) {
ErrorHandler::log($_FILES['attachment']['name'][$n] . ': ' . Lang::$txt['php_upload_error_6'], 'critical');
}
// Weird, no errors were cached, still fill out a generic one.
- if (empty($errors))
+ if (empty($errors)) {
$errors[] = 'attach_php_error';
+ }
}
// Try to move and rename the file before doing any more checks on it.
@@ -367,54 +362,54 @@ protected function processAttachments(): void
$destName = $this->_attchDir . '/' . $attachID;
// No errors, YAY!
- if (empty($errors))
- {
+ if (empty($errors)) {
// The reported MIME type of the attachment might not be reliable.
$detected_mime_type = Utils::getMimeType($_FILES['attachment']['tmp_name'][$n], true);
- if ($detected_mime_type !== false)
+ if ($detected_mime_type !== false) {
$_FILES['attachment']['type'][$n] = $detected_mime_type;
+ }
- $_SESSION['temp_attachments'][$attachID] = array(
+ $_SESSION['temp_attachments'][$attachID] = [
'name' => Utils::htmlspecialchars(basename($_FILES['attachment']['name'][$n])),
'tmp_name' => $destName,
'size' => $_FILES['attachment']['size'][$n],
'type' => $_FILES['attachment']['type'][$n],
'id_folder' => Config::$modSettings['currentAttachmentUploadDir'],
- 'errors' => array(),
- );
+ 'errors' => [],
+ ];
// Move the file to the attachments folder with a temp name for now.
- if (@move_uploaded_file($_FILES['attachment']['tmp_name'][$n], $destName))
- {
+ if (@move_uploaded_file($_FILES['attachment']['tmp_name'][$n], $destName)) {
Utils::makeWritable($destName, 0644);
}
// This is madness!!
- else
- {
+ else {
// File couldn't be moved.
$_SESSION['temp_attachments'][$attachID]['errors'][] = 'attach_timeout';
- if (file_exists($_FILES['attachment']['tmp_name'][$n]))
+ if (file_exists($_FILES['attachment']['tmp_name'][$n])) {
unlink($_FILES['attachment']['tmp_name'][$n]);
+ }
}
}
// Fill up a nice array with some data from the file and the errors encountered so far.
- else
- {
- $_SESSION['temp_attachments'][$attachID] = array(
+ else {
+ $_SESSION['temp_attachments'][$attachID] = [
'name' => Utils::htmlspecialchars(basename($_FILES['attachment']['name'][$n])),
'tmp_name' => $destName,
'errors' => $errors,
- );
+ ];
- if (file_exists($_FILES['attachment']['tmp_name'][$n]))
+ if (file_exists($_FILES['attachment']['tmp_name'][$n])) {
unlink($_FILES['attachment']['tmp_name'][$n]);
+ }
}
// If there's no errors to this point. We still do need to apply some additional checks before we are finished.
- if (empty($_SESSION['temp_attachments'][$attachID]['errors']))
+ if (empty($_SESSION['temp_attachments'][$attachID]['errors'])) {
Attachment::check($attachID);
+ }
}
// Mod authors, finally a hook to hang an alternate attachment upload system upon
@@ -427,7 +422,7 @@ protected function processAttachments(): void
// id_folder => Config::$modSettings['currentAttachmentUploadDir']
// errors => An array of errors (use the index of the Lang::$txt variable for that error).
// Template changes can be done using "integrate_upload_template".
- IntegrationHook::call('integrate_attachment_upload', array());
+ IntegrationHook::call('integrate_attachment_upload', []);
}
/**
@@ -436,88 +431,82 @@ protected function processAttachments(): void
protected function createAttach(): void
{
// Create an empty session var to keep track of all the files we attached.
- if (!isset($_SESSION['already_attached']))
- $_SESSION['already_attached'] = array();
+ if (!isset($_SESSION['already_attached'])) {
+ $_SESSION['already_attached'] = [];
+ }
- foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
- {
- $attachmentOptions = array(
+ foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
+ $attachmentOptions = [
'post' => $this->_msg,
'poster' => User::$me->id,
'name' => $attachment['name'],
'tmp_name' => $attachment['tmp_name'],
- 'size' => isset($attachment['size']) ? $attachment['size'] : 0,
- 'mime_type' => isset($attachment['type']) ? $attachment['type'] : '',
- 'id_folder' => isset($attachment['id_folder']) ? $attachment['id_folder'] : Config::$modSettings['currentAttachmentUploadDir'],
+ 'size' => $attachment['size'] ?? 0,
+ 'mime_type' => $attachment['type'] ?? '',
+ 'id_folder' => $attachment['id_folder'] ?? Config::$modSettings['currentAttachmentUploadDir'],
'approved' => !Config::$modSettings['postmod_active'] || User::$me->allowedTo('post_attachment'),
- 'errors' => array(),
- );
+ 'errors' => [],
+ ];
- if (empty($attachment['errors']))
- {
- if (Attachment::create($attachmentOptions))
- {
+ if (empty($attachment['errors'])) {
+ if (Attachment::create($attachmentOptions)) {
// Avoid JS getting confused.
$attachmentOptions['attachID'] = $attachmentOptions['id'];
unset($attachmentOptions['id']);
$_SESSION['already_attached'][$attachmentOptions['attachID']] = $attachmentOptions['attachID'];
- if (!empty($attachmentOptions['thumb']))
- {
+ if (!empty($attachmentOptions['thumb'])) {
$_SESSION['already_attached'][$attachmentOptions['thumb']] = $attachmentOptions['thumb'];
}
- if ($this->_msg)
+ if ($this->_msg) {
Attachment::assign($_SESSION['already_attached'], $this->_msg);
+ }
}
- }
- else
- {
+ } else {
// Sort out the errors for display and delete any associated files.
- $log_these = array('attachments_no_create', 'attachments_no_write', 'attach_timeout', 'ran_out_of_space', 'cant_access_upload_path', 'attach_0_byte_file');
+ $log_these = ['attachments_no_create', 'attachments_no_write', 'attach_timeout', 'ran_out_of_space', 'cant_access_upload_path', 'attach_0_byte_file'];
- foreach ($attachment['errors'] as $error)
- {
+ foreach ($attachment['errors'] as $error) {
$attachmentOptions['errors'][] = sprintf(Lang::$txt['attach_warning'], $attachment['name']);
- if (!is_array($error))
- {
+ if (!is_array($error)) {
$attachmentOptions['errors'][] = Lang::$txt[$error];
- if (in_array($error, $log_these))
+ if (in_array($error, $log_these)) {
ErrorHandler::log($attachment['name'] . ': ' . Lang::$txt[$error], 'critical');
- }
- else
- {
+ }
+ } else {
$attachmentOptions['errors'][] = vsprintf(Lang::$txt[$error[0]], (array) $error[1]);
}
}
- if (file_exists($attachment['tmp_name']))
+ if (file_exists($attachment['tmp_name'])) {
unlink($attachment['tmp_name']);
+ }
}
// You don't need to know.
- unset($attachmentOptions['tmp_name']);
- unset($attachmentOptions['destination']);
+ unset($attachmentOptions['tmp_name'], $attachmentOptions['destination']);
// Regardless of errors, pass the results.
$this->_attachResults[] = $attachmentOptions;
}
// Temp save this on the db.
- if (!empty($_SESSION['already_attached']))
+ if (!empty($_SESSION['already_attached'])) {
$this->_attachSuccess = $_SESSION['already_attached'];
+ }
unset($_SESSION['temp_attachments']);
// Allow user to see previews for all of this post's attachments, even if the post hasn't been submitted yet.
- if (!isset($_SESSION['attachments_can_preview']))
- $_SESSION['attachments_can_preview'] = array();
+ if (!isset($_SESSION['attachments_can_preview'])) {
+ $_SESSION['attachments_can_preview'] = [];
+ }
- if (!empty($_SESSION['already_attached']))
- {
+ if (!empty($_SESSION['already_attached'])) {
$_SESSION['attachments_can_preview'] += array_fill_keys(array_keys($_SESSION['already_attached']), true);
}
}
@@ -527,46 +516,41 @@ protected function createAttach(): void
*
* @param array $data Data for the response if we're not adding an attachment
*/
- protected function setResponse($data = array()): void
+ protected function setResponse($data = []): void
{
// Some default values in case something is missed or neglected :P
- $this->_response = array(
+ $this->_response = [
'text' => 'attach_php_error',
'type' => 'error',
'data' => false,
- );
+ ];
// Adding needs some VIP treatment.
- if ($this->_sa == 'add')
- {
+ if ($this->_sa == 'add') {
// Is there any generic errors? made some sense out of them!
- if ($this->_generalErrors)
- {
- foreach ($this->_generalErrors as $k => $v)
- {
+ if ($this->_generalErrors) {
+ foreach ($this->_generalErrors as $k => $v) {
$this->_generalErrors[$k] = (is_array($v) ? vsprintf(Lang::$txt[$v[0]], (array) $v[1]) : Lang::$txt[$v]);
}
}
// Gotta urlencode the filename.
- if ($this->_attachResults)
- {
- foreach ($this->_attachResults as $k => $v)
- {
+ if ($this->_attachResults) {
+ foreach ($this->_attachResults as $k => $v) {
$this->_attachResults[$k]['name'] = urlencode($this->_attachResults[$k]['name']);
}
}
- $this->_response = array(
+ $this->_response = [
'files' => $this->_attachResults ? $this->_attachResults : false,
'generalErrors' => $this->_generalErrors ? $this->_generalErrors : false,
- );
+ ];
}
// Rest of us mere mortals gets no special treatment...
- elseif (!empty($data))
- {
- if (!empty($data['text']) && !empty(Lang::$txt[$data['text']]))
+ elseif (!empty($data)) {
+ if (!empty($data['text']) && !empty(Lang::$txt[$data['text']])) {
$this->_response['text'] = Lang::$txt[$data['text']];
+ }
}
}
@@ -577,22 +561,20 @@ protected function sendResponse(): void
{
ob_end_clean();
- if (!empty(Config::$modSettings['enableCompressedOutput']))
- {
+ if (!empty(Config::$modSettings['enableCompressedOutput'])) {
@ob_start('ob_gzhandler');
- }
- else
- {
+ } else {
ob_start();
}
// Set the header.
header('content-type: application/json; charset=' . Utils::$context['character_set'] . '');
- echo Utils::jsonEncode($this->_response ? $this->_response : array());
+ echo Utils::jsonEncode($this->_response ? $this->_response : []);
// Done.
Utils::obExit(false);
+
die;
}
}
diff --git a/Sources/Actions/AutoSuggest.php b/Sources/Actions/AutoSuggest.php
index 3c591ebefd..b1fca12f76 100644
--- a/Sources/Actions/AutoSuggest.php
+++ b/Sources/Actions/AutoSuggest.php
@@ -14,12 +14,11 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
+use SMF\Db\DatabaseApi as Db;
use SMF\IntegrationHook;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Suggests members, membergroups, or SMF versions in reply to AJAX requests.
@@ -33,13 +32,14 @@ class AutoSuggest implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- 'checkRegistered' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'AutoSuggestHandler' => 'AutoSuggestHandler',
+ 'AutoSuggest_Search_Member' => 'AutoSuggest_Search_Member',
+ 'AutoSuggest_Search_MemberGroups' => 'AutoSuggest_Search_MemberGroups',
+ 'AutoSuggest_Search_SMFVersions' => 'AutoSuggest_Search_SMFVersions',
+ ],
+ ];
/*******************
* Public properties
@@ -67,7 +67,7 @@ class AutoSuggest implements ActionInterface
* Optional search parameters.
* This should be set by the constructor.
*/
- public array $search_param = array();
+ public array $search_param = [];
/**************************
* Public static properties
@@ -78,11 +78,11 @@ class AutoSuggest implements ActionInterface
*
* Available suggestion types.
*/
- public static array $suggest_types = array(
+ public static array $suggest_types = [
'member' => 'member',
'membergroups' => 'membergroups',
'versions' => 'versions',
- );
+ ];
/****************************
* Internal static properties
@@ -105,24 +105,20 @@ class AutoSuggest implements ActionInterface
*/
public function execute(): void
{
- if (!isset($this->suggest_type, $this->search, self::$suggest_types[$this->suggest_type]))
+ if (!isset($this->suggest_type, $this->search, self::$suggest_types[$this->suggest_type])) {
return;
+ }
User::$me->checkSession('get');
Theme::loadTemplate('Xml');
Utils::$context['sub_template'] = 'generic_xml';
- if (method_exists($this, self::$suggest_types[$this->suggest_type]))
- {
- Utils::$context['xml_data'] = call_user_func(array($this, self::$suggest_types[$this->suggest_type]));
- }
- elseif (function_exists('AutoSuggest_Search_' . self::$suggest_types[$this->suggest_type]))
- {
+ if (method_exists($this, self::$suggest_types[$this->suggest_type])) {
+ Utils::$context['xml_data'] = call_user_func([$this, self::$suggest_types[$this->suggest_type]]);
+ } elseif (function_exists('AutoSuggest_Search_' . self::$suggest_types[$this->suggest_type])) {
Utils::$context['xml_data'] = call_user_func('AutoSuggest_Search_' . self::$suggest_types[$this->suggest_type]);
- }
- elseif (function_exists('AutoSuggest_Search_' . $this->suggest_type))
- {
+ } elseif (function_exists('AutoSuggest_Search_' . $this->suggest_type)) {
Utils::$context['xml_data'] = call_user_func('AutoSuggest_Search_' . $this->suggest_type);
}
}
@@ -136,37 +132,38 @@ public function member(): array
{
$this->sanitizeSearch();
- $xml_data = array(
- 'items' => array(
+ $xml_data = [
+ 'items' => [
'identifier' => 'item',
- 'children' => array(),
- ),
- );
+ 'children' => [],
+ ],
+ ];
// Find the member.
- $request = Db::$db->query('', '
- SELECT id_member, real_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name
FROM {db_prefix}members
WHERE {raw:real_name} LIKE {string:search}' . (!empty($this->search_param['buddies']) ? '
AND id_member IN ({array_int:buddy_list})' : '') . '
AND is_activated IN (1, 11)
LIMIT ' . (Utils::entityStrlen($this->search) <= 2 ? '100' : '800'),
- array(
+ [
'real_name' => Db::$db->case_sensitive ? 'LOWER(real_name)' : 'real_name',
'buddy_list' => User::$me->buddies,
'search' => $this->search,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $row['real_name'] = strtr($row['real_name'], array('&' => '&', '<' => '<', '>' => '>', '"' => '"'));
- $xml_data['items']['children'][] = array(
- 'attributes' => array(
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $row['real_name'] = strtr($row['real_name'], ['&' => '&', '<' => '<', '>' => '>', '"' => '"']);
+
+ $xml_data['items']['children'][] = [
+ 'attributes' => [
'id' => $row['id_member'],
- ),
+ ],
'value' => $row['real_name'],
- );
+ ];
}
Db::$db->free_result($request);
@@ -182,41 +179,42 @@ public function membergroups(): array
{
$this->sanitizeSearch();
- $xml_data = array(
- 'items' => array(
+ $xml_data = [
+ 'items' => [
'identifier' => 'item',
- 'children' => array(),
- ),
- );
+ 'children' => [],
+ ],
+ ];
// Find the group.
// Only return groups which are not post-based and not "Hidden",
// but not the "Administrators" or "Moderators" groups.
- $request = Db::$db->query('', '
- SELECT id_group, group_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_group, group_name
FROM {db_prefix}membergroups
WHERE {raw:group_name} LIKE {string:search}
AND min_posts = {int:min_posts}
AND id_group NOT IN ({array_int:invalid_groups})
AND hidden != {int:hidden}',
- array(
+ [
'group_name' => Db::$db->case_sensitive ? 'LOWER(group_name)' : 'group_name',
'min_posts' => -1,
- 'invalid_groups' => array(1, 3),
+ 'invalid_groups' => [1, 3],
'hidden' => 2,
'search' => $this->search,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $row['group_name'] = strtr($row['group_name'], array('&' => '&', '<' => '<', '>' => '>', '"' => '"'));
- $xml_data['items']['children'][] = array(
- 'attributes' => array(
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $row['group_name'] = strtr($row['group_name'], ['&' => '&', '<' => '<', '>' => '>', '"' => '"']);
+
+ $xml_data['items']['children'][] = [
+ 'attributes' => [
'id' => $row['id_group'],
- ),
+ ],
'value' => $row['group_name'],
- );
+ ];
}
Db::$db->free_result($request);
@@ -230,60 +228,57 @@ public function membergroups(): array
*/
public function versions(): array
{
- $xml_data = array(
- 'items' => array(
+ $xml_data = [
+ 'items' => [
'identifier' => 'item',
- 'children' => array(),
- ),
- );
+ 'children' => [],
+ ],
+ ];
// First try and get it from the database.
- $versions = array();
- $request = Db::$db->query('', '
- SELECT data
+ $versions = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT data
FROM {db_prefix}admin_info_files
WHERE filename = {string:latest_versions}
AND path = {string:path}',
- array(
+ [
'latest_versions' => 'latest-versions.txt',
'path' => '/smf/',
- )
+ ],
);
- if (Db::$db->num_rows($request))
- {
- $versions = array();
- }
- elseif ($row = Db::$db->fetch_assoc($request) && !empty($row['data']))
- {
+ if (Db::$db->num_rows($request)) {
+ $versions = [];
+ } elseif ($row = Db::$db->fetch_assoc($request) && !empty($row['data'])) {
// The file can have either Windows or Linux line endings, but let's
// ensure we clean it as best we can.
$possible_versions = explode("\n", $row['data']);
- foreach ($possible_versions as $ver)
- {
+ foreach ($possible_versions as $ver) {
$ver = trim($ver);
- if (strpos($ver, 'SMF') === 0)
+ if (strpos($ver, 'SMF') === 0) {
$versions[] = $ver;
+ }
}
}
Db::$db->free_result($request);
// Just in case we don't have anything.
- if (empty($versions))
- $versions = array(SMF_FULL_VERSION);
-
- foreach ($versions as $id => $version)
- {
- if (strpos(strtoupper($version), strtoupper($this->search)) !== false)
- {
- $xml_data['items']['children'][] = array(
- 'attributes' => array(
+ if (empty($versions)) {
+ $versions = [SMF_FULL_VERSION];
+ }
+
+ foreach ($versions as $id => $version) {
+ if (strpos(strtoupper($version), strtoupper($this->search)) !== false) {
+ $xml_data['items']['children'][] = [
+ 'attributes' => [
'id' => $id,
- ),
+ ],
'value' => $version,
- );
+ ];
}
}
@@ -301,8 +296,9 @@ public function versions(): array
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -322,7 +318,7 @@ public static function call(): void
*/
public static function checkRegistered(string $suggest_type): bool
{
- IntegrationHook::call('integrate_autosuggest', array(&$suggest_types));
+ IntegrationHook::call('integrate_autosuggest', [&$suggest_types]);
return isset(self::$suggest_types[$suggest_type]) && (method_exists(__CLASS__, $suggest_type) || function_exists('AutoSuggest_Search_' . self::$suggest_types[$this->suggest_type]) || function_exists('AutoSuggest_Search_' . $suggest_type));
}
@@ -335,8 +331,9 @@ public static function checkRegistered(string $suggest_type): bool
*/
public static function AutoSuggestHandler($suggest_type = null)
{
- if (isset($suggest_type))
+ if (isset($suggest_type)) {
return self::checkRegistered($suggest_type);
+ }
self::call();
}
@@ -380,17 +377,20 @@ public static function AutoSuggest_Search_SMFVersions(): void
*/
protected function __construct()
{
- IntegrationHook::call('integrate_autosuggest', array(&self::$suggest_types));
+ IntegrationHook::call('integrate_autosuggest', [&self::$suggest_types]);
- if (!empty($_REQUEST['suggest_type']) && isset(self::$suggest_types[$_REQUEST['suggest_type']]))
+ if (!empty($_REQUEST['suggest_type']) && isset(self::$suggest_types[$_REQUEST['suggest_type']])) {
$this->suggest_type = $_REQUEST['suggest_type'];
+ }
// Any parameters?
- if (isset($_REQUEST['search_param']))
+ if (isset($_REQUEST['search_param'])) {
$this->search_param = Utils::jsonDecode(base64_decode($_REQUEST['search_param']), true);
+ }
- if (isset($_REQUEST['search']))
+ if (isset($_REQUEST['search'])) {
$this->search = $_REQUEST['search'];
+ }
}
/**
@@ -400,12 +400,13 @@ protected function sanitizeSearch(): void
{
$this->search = trim(Utils::strtolower($this->search)) . '*';
- $this->search = strtr($this->search, array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '&' => '&'));
+ $this->search = strtr($this->search, ['%' => '\\%', '_' => '\\_', '*' => '%', '?' => '_', '&' => '&']);
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\AutoSuggest::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\AutoSuggest::exportStatic')) {
AutoSuggest::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/BoardIndex.php b/Sources/Actions/BoardIndex.php
index d2a52c93f6..27558184d7 100644
--- a/Sources/Actions/BoardIndex.php
+++ b/Sources/Actions/BoardIndex.php
@@ -14,11 +14,10 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
+use SMF\Cache\CacheApi;
use SMF\Category;
use SMF\Config;
-use SMF\Group;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Logging;
@@ -27,7 +26,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
/**
* This class shows the board index.
@@ -47,12 +45,13 @@ class BoardIndex implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static array $backcompat = array(
- 'func_names' => array(
+ private static array $backcompat = [
+ 'func_names' => [
'load' => 'BoardIndex',
+ 'call' => 'call',
'get' => 'getBoardIndex',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -75,47 +74,43 @@ class BoardIndex implements ActionInterface
public function execute(): void
{
// Retrieve the categories and boards.
- $boardIndexOptions = array(
+ $boardIndexOptions = [
'include_categories' => true,
'base_level' => 0,
'parent_id' => 0,
'set_latest_post' => true,
'countChildPosts' => !empty(Config::$modSettings['countChildPosts']),
- );
+ ];
Utils::$context['categories'] = self::get($boardIndexOptions);
// Now set up for the info center.
- Utils::$context['info_center'] = array();
+ Utils::$context['info_center'] = [];
// Retrieve the latest posts if the theme settings require it.
- if (!empty(Theme::$current->settings['number_recent_posts']))
- {
- if (Theme::$current->settings['number_recent_posts'] > 1)
- {
- Utils::$context['latest_posts'] = CacheApi::quickGet('boardindex-latest_posts:' . md5(User::$me->query_wanna_see_board . User::$me->language), '', array($this, 'cache_getLastPosts'), array(Theme::$current->settings['number_recent_posts']));
+ if (!empty(Theme::$current->settings['number_recent_posts'])) {
+ if (Theme::$current->settings['number_recent_posts'] > 1) {
+ Utils::$context['latest_posts'] = CacheApi::quickGet('boardindex-latest_posts:' . md5(User::$me->query_wanna_see_board . User::$me->language), '', [$this, 'cache_getLastPosts'], [Theme::$current->settings['number_recent_posts']]);
}
- if (!empty(Utils::$context['latest_posts']) || !empty(Utils::$context['latest_post']))
- {
- Utils::$context['info_center'][] = array(
+ if (!empty(Utils::$context['latest_posts']) || !empty(Utils::$context['latest_post'])) {
+ Utils::$context['info_center'][] = [
'tpl' => 'recent',
'txt' => 'recent_posts',
- );
+ ];
}
}
// Load the calendar?
- if (!empty(Config::$modSettings['cal_enabled']) && User::$me->allowedTo('calendar_view'))
- {
+ if (!empty(Config::$modSettings['cal_enabled']) && User::$me->allowedTo('calendar_view')) {
// Retrieve the calendar data (events, birthdays, holidays).
- $eventOptions = array(
+ $eventOptions = [
'include_holidays' => Config::$modSettings['cal_showholidays'] > 1,
'include_birthdays' => Config::$modSettings['cal_showbdays'] > 1,
'include_events' => Config::$modSettings['cal_showevents'] > 1,
'num_days_shown' => empty(Config::$modSettings['cal_days_for_index']) || Config::$modSettings['cal_days_for_index'] < 1 ? 1 : Config::$modSettings['cal_days_for_index'],
- );
+ ];
- Utils::$context += CacheApi::quickGet('calendar_index_offset_' . User::$me->time_offset, 'Actions/Calendar.php', 'SMF\\Actions\\Calendar::cache_getRecentEvents', array($eventOptions));
+ Utils::$context += CacheApi::quickGet('calendar_index_offset_' . User::$me->time_offset, 'Actions/Calendar.php', 'SMF\\Actions\\Calendar::cache_getRecentEvents', [$eventOptions]);
// Whether one or multiple days are shown on the board index.
Utils::$context['calendar_only_today'] = Config::$modSettings['cal_days_for_index'] == 1;
@@ -123,52 +118,48 @@ public function execute(): void
// This is used to show the "how-do-I-edit" help.
Utils::$context['calendar_can_edit'] = User::$me->allowedTo('calendar_edit_any');
- if (!empty(Utils::$context['show_calendar']))
- {
- Utils::$context['info_center'][] = array(
+ if (!empty(Utils::$context['show_calendar'])) {
+ Utils::$context['info_center'][] = [
'tpl' => 'calendar',
'txt' => Utils::$context['calendar_only_today'] ? 'calendar_today' : 'calendar_upcoming',
- );
+ ];
}
}
// And stats.
- if (Theme::$current->settings['show_stats_index'])
- {
- Utils::$context['info_center'][] = array(
+ if (Theme::$current->settings['show_stats_index']) {
+ Utils::$context['info_center'][] = [
'tpl' => 'stats',
'txt' => 'forum_stats',
- );
+ ];
}
// Now the online stuff
- Utils::$context += Logging::getMembersOnlineStats(array(
+ Utils::$context += Logging::getMembersOnlineStats([
'show_hidden' => User::$me->allowedTo('moderate_forum'),
'sort' => 'log_time',
'reverse_sort' => true,
- ));
+ ]);
- Utils::$context['info_center'][] = array(
+ Utils::$context['info_center'][] = [
'tpl' => 'online',
'txt' => 'online_users',
- );
+ ];
// Track most online statistics?
- if (!empty(Config::$modSettings['trackStats']))
- {
+ if (!empty(Config::$modSettings['trackStats'])) {
Logging::trackStatsUsersOnline(Utils::$context['num_guests'] + Utils::$context['num_users_online']);
}
// Are we showing all membergroups on the board index?
- if (!empty(Theme::$current->settings['show_group_key']))
- {
- Utils::$context['membergroups'] = CacheApi::quickGet('membergroup_list', 'Group.php', 'SMF\\Group::getCachedList', array());
+ if (!empty(Theme::$current->settings['show_group_key'])) {
+ Utils::$context['membergroups'] = CacheApi::quickGet('membergroup_list', 'Group.php', 'SMF\\Group::getCachedList', []);
}
// Mark read button
- Utils::$context['mark_read_button'] = array(
- 'markread' => array('text' => 'mark_as_read', 'image' => 'markread.png', 'custom' => 'data-confirm="' . Lang::$txt['are_sure_mark_read'] . '"', 'class' => 'you_sure', 'url' => Config::$scripturl . '?action=markasread;sa=all;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']),
- );
+ Utils::$context['mark_read_button'] = [
+ 'markread' => ['text' => 'mark_as_read', 'image' => 'markread.png', 'custom' => 'data-confirm="' . Lang::$txt['are_sure_mark_read'] . '"', 'class' => 'you_sure', 'url' => Config::$scripturl . '?action=markasread;sa=all;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']],
+ ];
// Allow mods to add additional buttons here
IntegrationHook::call('integrate_mark_read_button');
@@ -182,8 +173,8 @@ public function execute(): void
*/
public function getLastPosts(int $number_posts = 5)
{
- $msg_load_options = array(
- 'selects' => array(
+ $msg_load_options = [
+ 'selects' => [
'm.id_msg',
'm.id_topic',
'm.id_board',
@@ -193,38 +184,35 @@ public function getLastPosts(int $number_posts = 5)
'm.subject',
'm.body',
'm.smileys_enabled',
- ),
- 'joins' => array(
+ ],
+ 'joins' => [
'LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)',
- ),
- 'where' => array(
+ ],
+ 'where' => [
'm.id_msg >= {int:likely_max_msg}',
'{query_wanna_see_message_board}',
- ),
- 'order' => array('m.id_msg DESC'),
+ ],
+ 'order' => ['m.id_msg DESC'],
'limit' => $number_posts,
- 'params' => array(
+ 'params' => [
'likely_max_msg' => max(0, Config::$modSettings['maxMsgID'] - 50 * $number_posts),
- ),
- );
+ ],
+ ];
- if (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0)
- {
+ if (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0) {
$msg_load_options['where'][] = 'm.id_board != {int:recycle_board}';
$msg_load_options['params']['recycle_board'] = Config::$modSettings['recycle_board'];
}
- if (Config::$modSettings['postmod_active'])
- {
+ if (Config::$modSettings['postmod_active']) {
$msg_load_options['joins'][] = 'INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)';
$msg_load_options['where'][] = 't.approved = {int:is_approved}';
$msg_load_options['where'][] = 'm.approved = {int:is_approved}';
$msg_load_options['params']['is_approved'] = 1;
}
- foreach (Msg::get(0, $msg_load_options) as $msg)
- {
- $posts[$msg->id] = $msg->format(0, array(
+ foreach (Msg::get(0, $msg_load_options) as $msg) {
+ $posts[$msg->id] = $msg->format(0, [
'do_permissions' => false,
'do_icon' => false,
'load_author' => false,
@@ -232,8 +220,8 @@ public function getLastPosts(int $number_posts = 5)
'make_preview' => true,
'shorten_subject' => 24,
// Going to the last post counts as viewing the whole topic.
- 'url_params' => array('topicseen'),
- ));
+ 'url_params' => ['topicseen'],
+ ]);
// Backward compatibility.
$posts[$msg->id]['poster'] = &$posts[$msg->id]['member'];
@@ -249,7 +237,7 @@ public function getLastPosts(int $number_posts = 5)
*/
public function cache_getLastPosts(int $number_posts = 5)
{
- return array(
+ return [
'data' => $this->getLastPosts($number_posts),
'expires' => time() + 60,
'post_retri_eval' => '
@@ -258,7 +246,7 @@ public function cache_getLastPosts(int $number_posts = 5)
$cache_block[\'data\'][$k][\'time\'] = \\SMF\\Time::create(\'@\' . $post[\'raw_timestamp\'])->format();
$cache_block[\'data\'][$k][\'timestamp\'] = $post[\'raw_timestamp\'];
}',
- );
+ ];
}
/***********************
@@ -272,8 +260,9 @@ public function cache_getLastPosts(int $number_posts = 5)
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -308,20 +297,20 @@ public static function get($board_index_options): array
$board_index_options['parent_id'] = $board_index_options['parent_id'] ?? 0;
// For performance, track the latest post while going through the boards.
- if (!empty($board_index_options['set_latest_post']))
- {
- $latest_post = array(
+ if (!empty($board_index_options['set_latest_post'])) {
+ $latest_post = [
'timestamp' => 0,
- 'ref' => 0
- );
+ 'ref' => 0,
+ ];
}
// This setting is not allowed to be empty
- if (empty(Config::$modSettings['boardindex_max_depth']))
+ if (empty(Config::$modSettings['boardindex_max_depth'])) {
Config::$modSettings['boardindex_max_depth'] = 1;
+ }
// Stuff we always want to have in the query.
- $selects = array(
+ $selects = [
'b.id_board',
'b.name AS board_name',
'b.description',
@@ -340,39 +329,37 @@ public static function get($board_index_options): array
'COALESCE(mem.id_member, 0) AS id_member',
'COALESCE(mem.member_name, m.poster_name) AS poster_name',
'COALESCE(mem.real_name, m.poster_name) AS real_name',
- );
+ ];
- $params = array(
+ $params = [
'current_member' => User::$me->id,
'child_level' => $board_index_options['base_level'],
'max_child_level' => $board_index_options['base_level'] + Config::$modSettings['boardindex_max_depth'],
- 'blank_string' => ''
- );
+ 'blank_string' => '',
+ ];
- $joins = array(
+ $joins = [
'LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = b.id_last_msg)',
'LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)',
- );
+ ];
- $where = array(
+ $where = [
'{query_see_board}',
'b.child_level BETWEEN {int:child_level} AND {int:max_child_level}',
- );
+ ];
- $order = array(
+ $order = [
'b.child_level',
'b.board_order',
- );
+ ];
// Extra stuff based on the passed options.
- if (!empty($board_index_options['parent_id']))
- {
+ if (!empty($board_index_options['parent_id'])) {
$where[] = 'b.id_parent != 0';
$params['id_parent'] = (int) $board_index_options['parent_id'];
}
- if (!empty($board_index_options['include_categories']))
- {
+ if (!empty($board_index_options['include_categories'])) {
$selects[] = 'c.name AS cat_name';
$selects[] = 'c.description AS cat_desc';
$selects[] = 'c.cat_order';
@@ -380,24 +367,21 @@ public static function get($board_index_options): array
array_unshift($order, 'c.cat_order');
}
- if (User::$me->is_guest)
- {
+ if (User::$me->is_guest) {
$selects[] = '0 AS new_from';
$selects[] = '1 AS is_read';
- }
- else
- {
+ } else {
$selects[] = 'COALESCE(lb.id_msg, -1) + 1 AS new_from';
$selects[] = '(CASE WHEN COALESCE(lb.id_msg, 0) >= b.id_last_msg THEN 1 ELSE 0 END) AS is_read';
- if (!empty($board_index_options['include_categories']))
+ if (!empty($board_index_options['include_categories'])) {
$selects[] = 'c.can_collapse';
+ }
$joins[] = 'LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})';
}
- if (!empty(Theme::$current->settings['avatars_on_boardIndex']))
- {
+ if (!empty(Theme::$current->settings['avatars_on_boardIndex'])) {
$selects[] = 'mem.email_address';
$selects[] = 'mem.avatar';
$selects[] = 'COALESCE(am.id_attach, 0) AS member_id_attach';
@@ -408,16 +392,15 @@ public static function get($board_index_options): array
}
// Give mods access to the query.
- IntegrationHook::call('integrate_pre_boardindex', array(&$selects, &$params, &$joins, &$where, &$order));
+ IntegrationHook::call('integrate_pre_boardindex', [&$selects, &$params, &$joins, &$where, &$order]);
// Start with empty arrays.
- $boards = array();
- $cat_boards = array();
+ $boards = [];
+ $cat_boards = [];
// Find all boards and categories, as well as related information.
- foreach (Board::queryData($selects, $params, $joins, $where, $order) as $row_board)
- {
- $row_board = array_filter($row_board, fn($prop) => !is_null($prop));
+ foreach (Board::queryData($selects, $params, $joins, $where, $order) as $row_board) {
+ $row_board = array_filter($row_board, fn ($prop) => !is_null($prop));
$parent = Board::$loaded[$row_board['id_parent']] ?? null;
@@ -425,12 +408,10 @@ public static function get($board_index_options): array
$ignoreThisBoard = in_array($row_board['id_board'], User::$me->ignoreboards);
$row_board['is_read'] = !empty($row_board['is_read']) || $ignoreThisBoard ? '1' : '0';
- if ($board_index_options['include_categories'])
- {
+ if ($board_index_options['include_categories']) {
// Haven't set this category yet.
- if (!isset(Category::$loaded[$row_board['id_cat']]))
- {
- $category = Category::init($row_board['id_cat'], array(
+ if (!isset(Category::$loaded[$row_board['id_cat']])) {
+ $category = Category::init($row_board['id_cat'], [
'id' => $row_board['id_cat'],
'name' => $row_board['cat_name'],
'description' => $row_board['cat_desc'],
@@ -442,18 +423,15 @@ public static function get($board_index_options): array
'css_class' => '',
'link' => '' . (!User::$me->is_guest ?
'' . $row_board['cat_name'] . '' : $row_board['cat_name']),
- ));
+ ]);
$category->parseDescription();
- }
- else
- {
+ } else {
$category = Category::$loaded[$row_board['id_cat']];
}
// If this board has new posts in it (and isn't the recycle bin!) then the category is new.
- if (empty(Config::$modSettings['recycle_enable']) || Config::$modSettings['recycle_board'] != $row_board['id_board'])
- {
+ if (empty(Config::$modSettings['recycle_enable']) || Config::$modSettings['recycle_board'] != $row_board['id_board']) {
$category->new |= empty($row_board['is_read']);
}
@@ -464,72 +442,63 @@ public static function get($board_index_options): array
}
// Is this a new board, or just another moderator?
- if (!isset(Board::$loaded[$row_board['id_board']]->type))
- {
- $board = Board::init($row_board['id_board'], array(
+ if (!isset(Board::$loaded[$row_board['id_board']]->type)) {
+ $board = Board::init($row_board['id_board'], [
'cat' => Category::init($row_board['id_cat']),
'new' => empty($row_board['is_read']),
'type' => $row_board['is_redirect'] ? 'redirect' : 'board',
'name' => $row_board['board_name'],
'description' => $row_board['description'],
'short_description' => Utils::shorten($row_board['description'], 128),
- 'link_moderators' => array(),
- 'link_moderator_groups' => array(),
+ 'link_moderators' => [],
+ 'link_moderator_groups' => [],
'parent' => $row_board['id_parent'],
'child_level' => $row_board['child_level'],
- 'link_children' => array(),
+ 'link_children' => [],
'children_new' => false,
'topics' => $row_board['num_topics'],
'posts' => $row_board['num_posts'],
'is_redirect' => $row_board['is_redirect'],
'unapproved_topics' => $row_board['unapproved_topics'],
'unapproved_posts' => $row_board['unapproved_posts'] - $row_board['unapproved_topics'],
- 'can_approve_posts' => !empty(User::$me->mod_cache['ap']) && (User::$me->mod_cache['ap'] == array(0) || in_array($row_board['id_board'], User::$me->mod_cache['ap'])),
+ 'can_approve_posts' => !empty(User::$me->mod_cache['ap']) && (User::$me->mod_cache['ap'] == [0] || in_array($row_board['id_board'], User::$me->mod_cache['ap'])),
'href' => Config::$scripturl . '?board=' . $row_board['id_board'] . '.0',
'link' => '' . $row_board['board_name'] . '',
'board_class' => 'off',
'css_class' => '',
'last_post' => self::prepareLastPost($row_board),
- ));
+ ]);
$board->parseDescription();
// This is a parent board.
- if (!isset($parent) || $parent->id == $board_index_options['parent_id'])
- {
+ if (!isset($parent) || $parent->id == $board_index_options['parent_id']) {
// @todo Should this be called for every board, not just parent boards?
- IntegrationHook::call('integrate_boardindex_board', array(&$cat_boards, $row_board));
+ IntegrationHook::call('integrate_boardindex_board', [&$cat_boards, $row_board]);
// Add parent boards to the $boards list later used to fetch moderators.
$boards[] = $row_board['id_board'];
// We can do some of the figuring-out-what-icon now.
// For certain types of thing we also set up what the tooltip is.
- if ($board->is_redirect)
- {
+ if ($board->is_redirect) {
$board->board_class = 'redirect';
$board->board_tooltip = Lang::$txt['redirect_board'];
- }
- elseif ($board->new || User::$me->is_guest)
- {
+ } elseif ($board->new || User::$me->is_guest) {
// If we're showing to guests, we want to give them the idea that something interesting is going on!
$board->board_class = 'on';
$board->board_tooltip = Lang::$txt['new_posts'];
- }
- else
- {
+ } else {
$board->board_tooltip = Lang::$txt['old_posts'];
}
}
// This is a child board.
- elseif (isset($parent) && $parent->parent == $board_index_options['parent_id'])
- {
+ elseif (isset($parent) && $parent->parent == $board_index_options['parent_id']) {
// Counting child board posts in the parent's totals?
self::propagateStatsToParents($board, $board_index_options);
// Update the icon if appropriate
- if ($parent->children_new && $parent->board_class == 'off')
- {
+ if ($parent->children_new && $parent->board_class == 'off') {
$parent->board_class = 'on2';
$parent->board_tooltip = Lang::$txt['new_posts'];
}
@@ -538,8 +507,7 @@ public static function get($board_index_options): array
$parent->link_children[] = $board->link;
}
// A further descendent (grandchild, great-grandchild, etc.)
- else
- {
+ else {
self::propagateStatsToParents($board, $board_index_options);
}
}
@@ -550,12 +518,11 @@ public static function get($board_index_options): array
&& !empty($row_board['poster_time'])
&& $row_board['poster_time'] > $latest_post['timestamp']
&& !$ignoreThisBoard
- )
- {
- $latest_post = array(
+ ) {
+ $latest_post = [
'timestamp' => $row_board['poster_time'],
'ref' => isset($parent) ? $parent->last_post : $board->last_post,
- );
+ ];
}
}
@@ -564,94 +531,75 @@ public static function get($board_index_options): array
$moderators = Board::getModerators($boards);
$groups = Board::getModeratorGroups($boards);
- if ($board_index_options['include_categories'])
- {
- foreach (Category::$loaded as &$category)
- {
- foreach ($category->children as $board)
- {
- if (!empty($moderators[$board->id]))
- {
+ if ($board_index_options['include_categories']) {
+ foreach (Category::$loaded as &$category) {
+ foreach ($category->children as $board) {
+ if (!empty($moderators[$board->id])) {
$board->moderators = $moderators[$board->id];
- foreach ($moderators[$board->id] as $moderator)
+ foreach ($moderators[$board->id] as $moderator) {
$board->link_moderators[] = $moderator['link'];
+ }
}
- if (!empty($groups[$board->id]))
- {
+ if (!empty($groups[$board->id])) {
$board->moderator_groups = $groups[$board->id];
- foreach ($groups[$board->id] as $group)
- {
+ foreach ($groups[$board->id] as $group) {
$board->link_moderators[] = $group['link'];
$board->link_moderator_groups[] = $group['link'];
}
}
- if (!empty($board->last_post))
- {
+ if (!empty($board->last_post)) {
$board->last_post['last_post_message'] = sprintf(Lang::$txt['last_post_message'], $board->last_post['member']['link'], $board->last_post['link'], $board->last_post['timestamp'] > 0 ? $board->last_post['time'] : Lang::$txt['not_applicable']);
}
}
}
- }
- else
- {
+ } else {
$cat_boards = &Board::$loaded[$board_index_options['parent_id']]->children;
- foreach ($cat_boards as &$board)
- {
- if (!empty($moderators[$board->id]))
- {
+ foreach ($cat_boards as &$board) {
+ if (!empty($moderators[$board->id])) {
$board->moderators = $moderators[$board->id];
- foreach ($moderators[$board->id] as $moderator)
+ foreach ($moderators[$board->id] as $moderator) {
$board->link_moderators[] = $moderator['link'];
+ }
}
- if (!empty($groups[$board->id]))
- {
+ if (!empty($groups[$board->id])) {
$board->moderator_groups = $groups[$board->id];
- foreach ($groups[$board->id] as $group)
- {
+ foreach ($groups[$board->id] as $group) {
$board->link_moderators[] = $group['link'];
$board->link_moderator_groups[] = $group['link'];
}
}
- if (!empty($board->last_post))
- {
+ if (!empty($board->last_post)) {
$board->last_post['last_post_message'] = sprintf(Lang::$txt['last_post_message'], $board->last_post['member']['link'], $board->last_post['link'], $board->last_post['timestamp'] > 0 ? $board->last_post['time'] : Lang::$txt['not_applicable']);
}
}
}
- if ($board_index_options['include_categories'])
- {
+ if ($board_index_options['include_categories']) {
Category::sort(Category::$loaded);
- }
- else
- {
+ } else {
Board::sort($cat_boards);
}
// By now we should know the most recent post...if we wanna know it that is.
- if (!empty($board_index_options['set_latest_post']) && !empty($latest_post['ref']))
- {
+ if (!empty($board_index_options['set_latest_post']) && !empty($latest_post['ref'])) {
$latest_post['ref']['time'] = Time::create('@' . $latest_post['ref']['timestamp'])->format();
Utils::$context['latest_post'] = $latest_post['ref'];
}
// I can't remember why but trying to make a ternary to get this all in one line is actually a Very Bad Idea.
- if ($board_index_options['include_categories'])
- {
- IntegrationHook::call('integrate_getboardtree', array($board_index_options, &Category::$loaded));
- }
- else
- {
- IntegrationHook::call('integrate_getboardtree', array($board_index_options, &$cat_boards));
+ if ($board_index_options['include_categories']) {
+ IntegrationHook::call('integrate_getboardtree', [$board_index_options, &Category::$loaded]);
+ } else {
+ IntegrationHook::call('integrate_getboardtree', [$board_index_options, &$cat_boards]);
}
return $board_index_options['include_categories'] ? Category::$loaded : $cat_boards;
@@ -677,17 +625,17 @@ protected function __construct()
Utils::$context['canonical_url'] = Config::$scripturl;
// Do not let search engines index anything if there is a random thing in $_GET.
- if (!empty($_GET))
+ if (!empty($_GET)) {
Utils::$context['robot_no_index'] = true;
+ }
// Replace the collapse and expand default alts.
Theme::addJavaScriptVar('smf_expandAlt', Lang::$txt['show_category'], true);
Theme::addJavaScriptVar('smf_collapseAlt', Lang::$txt['hide_category'], true);
- if (!empty(Theme::$current->settings['show_newsfader']))
- {
- Theme::loadJavaScriptFile('slippry.min.js', array(), 'smf_jquery_slippry');
- Theme::loadCSSFile('slider.min.css', array(), 'smf_jquery_slider');
+ if (!empty(Theme::$current->settings['show_newsfader'])) {
+ Theme::loadJavaScriptFile('slippry.min.js', [], 'smf_jquery_slippry');
+ Theme::loadCSSFile('slider.min.css', [], 'smf_jquery_slider');
}
// Set a few minor things.
@@ -708,15 +656,15 @@ protected function __construct()
*/
protected static function propagateStatsToParents($board, $board_index_options): void
{
- if ($board->is_redirect || empty($board->parent))
+ if ($board->is_redirect || empty($board->parent)) {
return;
+ }
// If the parent is already loaded, this will just return it.
// In the unlikely event that it isn't loaded, this will fix that.
$parent = Board::init($board->parent);
- if (!empty($board_index_options['countChildPosts']))
- {
+ if (!empty($board_index_options['countChildPosts'])) {
$parent->own_topics = $parent->own_topics ?? $parent->topics;
$parent->own_posts = $parent->own_posts ?? $parent->posts;
@@ -724,22 +672,22 @@ protected static function propagateStatsToParents($board, $board_index_options):
$parent->posts = $parent->own_posts + $board->posts;
}
- if (($board->last_post['timestamp'] ?? 0) > ($parent->last_post['timestamp'] ?? 0))
- {
+ if (($board->last_post['timestamp'] ?? 0) > ($parent->last_post['timestamp'] ?? 0)) {
$parent->last_post = $board->last_post;
}
- if (!empty($parent->parent))
- {
+ if (!empty($parent->parent)) {
// Does this board contain new boards?
$parent->children_new |= $board->new;
- if ($parent->parent != $board_index_options['parent_id'])
+ if ($parent->parent != $board_index_options['parent_id']) {
$parent->new |= $board->new;
+ }
// Continue propagating up the tree.
- if ($parent->id != $board_index_options['parent_id'])
+ if ($parent->id != $board_index_options['parent_id']) {
self::propagateStatsToParents($parent, $board_index_options);
+ }
}
}
@@ -762,67 +710,66 @@ protected static function propagateStatsToParents($board, $board_index_options):
*/
protected static function prepareLastPost($row_board): array
{
- if (empty($row_board['id_msg']))
- {
- return array(
+ if (empty($row_board['id_msg'])) {
+ return [
'timestamp' => 0,
'href' => '',
'link' => Lang::$txt['not_applicable'],
- 'member' => array(
+ 'member' => [
'id' => 0,
'name' => Lang::$txt['not_applicable'],
'username' => Lang::$txt['not_applicable'],
'href' => '',
'link' => Lang::$txt['not_applicable'],
- ),
- );
+ ],
+ ];
}
Lang::censorText($row_board['subject']);
$short_subject = Utils::shorten($row_board['subject'], 24);
- $msg = new Msg($row_board['id_msg'], array(
+ $msg = new Msg($row_board['id_msg'], [
'id_topic' => $row_board['id_topic'],
'id_board' => $row_board['id_board'],
'poster_time' => (int) $row_board['poster_time'],
'id_member' => $row_board['id_member'],
'poster_name' => $row_board['real_name'],
'subject' => $short_subject,
- ));
+ ]);
$last_post = array_merge(
- $msg->format(0, array(
+ $msg->format(0, [
'do_permissions' => false,
'do_icon' => false,
'load_author' => false,
- )),
- array(
+ ]),
+ [
'start' => 'msg' . $row_board['new_from'],
'topic' => $row_board['id_topic'],
'href' => Config::$scripturl . '?topic=' . $row_board['id_topic'] . '.msg' . $row_board['id_msg'] . (empty($row_board['is_read']) ? ';boardseen' : '') . '#new',
'link' => '' . $short_subject . '',
- )
+ ],
);
unset($msg, Msg::$loaded[$row_board['id_msg']]);
- if (!empty(Theme::$current->settings['avatars_on_boardIndex']))
- {
- $last_post['member']['avatar'] = User::setAvatarData(array(
+ if (!empty(Theme::$current->settings['avatars_on_boardIndex'])) {
+ $last_post['member']['avatar'] = User::setAvatarData([
'avatar' => $row_board['avatar'],
'email' => $row_board['email_address'],
- 'filename' => !empty($row_board['member_filename']) ? $row_board['member_filename'] : ''
- ));
+ 'filename' => !empty($row_board['member_filename']) ? $row_board['member_filename'] : '',
+ ]);
}
- IntegrationHook::call('integrate_boardindex_last_post', array(&$last_post, $row_board));
+ IntegrationHook::call('integrate_boardindex_last_post', [&$last_post, $row_board]);
return $last_post;
}
}
// Export public static functions to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\BoardIndex::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\BoardIndex::exportStatic')) {
BoardIndex::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/BuddyListToggle.php b/Sources/Actions/BuddyListToggle.php
index 6d1330ad66..8f95f3383a 100644
--- a/Sources/Actions/BuddyListToggle.php
+++ b/Sources/Actions/BuddyListToggle.php
@@ -14,12 +14,11 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
+use SMF\Cache\CacheApi;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* This simple action adds/removes the passed user from the current user's buddy list.
@@ -36,12 +35,11 @@ class BuddyListToggle implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'BuddyListToggle',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -80,32 +78,39 @@ public function execute(): void
User::$me->isAllowedTo('profile_extra_own');
User::$me->kickIfGuest();
- if (empty($this->userReceiver))
+ if (empty($this->userReceiver)) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Remove if it's already there...
- if (in_array($this->userReceiver, User::$me->buddies))
- {
- User::$me->buddies = array_diff(User::$me->buddies, array($this->userReceiver));
+ if (in_array($this->userReceiver, User::$me->buddies)) {
+ User::$me->buddies = array_diff(User::$me->buddies, [$this->userReceiver]);
}
// ...or add if it's not and if it's not you.
- elseif (User::$me->id != $this->userReceiver)
- {
+ elseif (User::$me->id != $this->userReceiver) {
User::$me->buddies[] = $this->userReceiver;
// And add a nice alert. Don't abuse though!
- if ((CacheApi::get('Buddy-sent-' . User::$me->id . '-' . $this->userReceiver, 86400)) == null)
- {
- Db::$db->insert('insert',
+ if ((CacheApi::get('Buddy-sent-' . User::$me->id . '-' . $this->userReceiver, 86400)) == null) {
+ Db::$db->insert(
+ 'insert',
'{db_prefix}background_tasks',
- array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
- array('$sourcedir/tasks/Buddy_Notify.php', 'SMF\Tasks\Buddy_Notify', Utils::jsonEncode(array(
- 'receiver_id' => $this->userReceiver,
- 'id_member' => User::$me->id,
- 'member_name' => User::$me->username,
- 'time' => time(),
- )), 0),
- array('id_task')
+ [
+ 'task_class' => 'string',
+ 'task_data' => 'string',
+ 'claimed_time' => 'int',
+ ],
+ [
+ 'SMF\\Tasks\\Buddy_Notify',
+ Utils::jsonEncode([
+ 'receiver_id' => $this->userReceiver,
+ 'id_member' => User::$me->id,
+ 'member_name' => User::$me->username,
+ 'time' => time(),
+ ]),
+ 0,
+ ],
+ ['id_task'],
);
// Store this in a cache entry to avoid creating multiple alerts. Give it a long life cycle.
@@ -114,7 +119,7 @@ public function execute(): void
}
// Update the settings.
- User::updateMemberData(User::$me->id, array('buddy_list' => implode(',', User::$me->buddies)));
+ User::updateMemberData(User::$me->id, ['buddy_list' => implode(',', User::$me->buddies)]);
// Redirect back to the profile
Utils::redirectexit('action=profile;u=' . $this->userReceiver);
@@ -131,8 +136,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;
}
@@ -159,7 +165,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\BuddyListToggle::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\BuddyListToggle::exportStatic')) {
BuddyListToggle::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Calendar.php b/Sources/Actions/Calendar.php
index c582d727aa..cd953337a9 100644
--- a/Sources/Actions/Calendar.php
+++ b/Sources/Actions/Calendar.php
@@ -14,10 +14,11 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
use SMF\BrowserDetector;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Event;
use SMF\IntegrationHook;
@@ -28,8 +29,6 @@
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* This class has only one real task, showing the calendar.
@@ -44,12 +43,32 @@ class Calendar implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'CalendarMain',
- ),
- );
+ 'iCalDownload' => 'iCalDownload',
+ 'CalendarPost' => 'CalendarPost',
+ 'getBirthdayRange' => 'getBirthdayRange',
+ 'getEventRange' => 'getEventRange',
+ 'getHolidayRange' => 'getHolidayRange',
+ 'canLinkEvent' => 'canLinkEvent',
+ 'getTodayInfo' => 'getTodayInfo',
+ 'getCalendarGrid' => 'getCalendarGrid',
+ 'getCalendarWeek' => 'getCalendarWeek',
+ 'getCalendarList' => 'getCalendarList',
+ 'loadDatePicker' => 'loadDatePicker',
+ 'loadTimePicker' => 'loadTimePicker',
+ 'loadDatePair' => 'loadDatePair',
+ 'cache_getOffsetIndependentEvents' => 'cache_getOffsetIndependentEvents',
+ 'cache_getRecentEvents' => 'cache_getRecentEvents',
+ 'validateEventPost' => 'validateEventPost',
+ 'getEventPoster' => 'getEventPoster',
+ 'list_getHolidays' => 'list_getHolidays',
+ 'list_getNumHolidays' => 'list_getNumHolidays',
+ 'removeHolidays' => 'removeHolidays',
+ 'convertDateToEnglish' => 'convertDateToEnglish',
+ ],
+ ];
/*******************
* Public properties
@@ -72,12 +91,12 @@ class Calendar implements ActionInterface
*
* Available sub-actions of this action.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'show' => 'show',
'ical' => 'export',
'post' => 'post',
'clock' => 'clock',
- );
+ ];
/*********************
* Internal properties
@@ -100,10 +119,11 @@ class Calendar 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);
+ }
}
/**
@@ -117,34 +137,34 @@ public function execute(): void
* It goes to the month and year passed in 'month' and 'year' by get or post.
* It is accessed through ?action=calendar.
*
- * @return void
*/
public function show(): void
{
// You can't do anything if the calendar is off.
- if (empty(Config::$modSettings['cal_enabled']))
+ if (empty(Config::$modSettings['cal_enabled'])) {
ErrorHandler::fatalLang('calendar_off', false);
+ }
// This is gonna be needed...
Theme::loadTemplate('Calendar');
- Theme::loadCSSFile('calendar.css', array('force_current' => false, 'validate' => true, 'rtl' => 'calendar.rtl.css'), 'smf_calendar');
+ Theme::loadCSSFile('calendar.css', ['force_current' => false, 'validate' => true, 'rtl' => 'calendar.rtl.css'], 'smf_calendar');
// Did the specify an individual event ID? If so, let's splice the year/month in to what we would otherwise be doing.
- if (isset($_GET['event']))
- {
+ if (isset($_GET['event'])) {
$evid = (int) $_GET['event'];
- if ($evid > 0)
- {
- $request = Db::$db->query('', '
- SELECT start_date
+
+ if ($evid > 0) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT start_date
FROM {db_prefix}calendar
WHERE id_event = {int:event_id}',
- array(
+ [
'event_id' => $evid,
- )
+ ],
);
- if ($row = Db::$db->fetch_assoc($request))
- {
+
+ if ($row = Db::$db->fetch_assoc($request)) {
$_REQUEST['start_date'] = $row['start_date'];
// We might use this later.
@@ -152,39 +172,41 @@ public function show(): void
}
Db::$db->free_result($request);
}
- unset ($_GET['event']);
+ unset($_GET['event']);
}
// Set the page title to mention the calendar ;).
Utils::$context['page_title'] = Lang::$txt['calendar'];
// Ensure a default view is defined
- if (empty(Theme::$current->options['calendar_default_view']))
+ if (empty(Theme::$current->options['calendar_default_view'])) {
Theme::$current->options['calendar_default_view'] = 'viewlist';
+ }
// What view do we want?
- if (isset($_GET['viewweek']))
+ if (isset($_GET['viewweek'])) {
Utils::$context['calendar_view'] = 'viewweek';
- elseif (isset($_GET['viewmonth']))
+ } elseif (isset($_GET['viewmonth'])) {
Utils::$context['calendar_view'] = 'viewmonth';
- elseif (isset($_GET['viewlist']))
+ } elseif (isset($_GET['viewlist'])) {
Utils::$context['calendar_view'] = 'viewlist';
- else
+ } else {
Utils::$context['calendar_view'] = Theme::$current->options['calendar_default_view'];
+ }
// Don't let search engines index the non-default calendar pages
- if (Utils::$context['calendar_view'] !== Theme::$current->options['calendar_default_view'])
+ if (Utils::$context['calendar_view'] !== Theme::$current->options['calendar_default_view']) {
Utils::$context['robot_no_index'] = true;
+ }
// Get the current day of month...
$today = self::getTodayInfo();
// Need a start date for all views
- if (!empty($_REQUEST['start_date']))
- {
+ if (!empty($_REQUEST['start_date'])) {
$start_parsed = date_parse(str_replace(',', '', self::convertDateToEnglish($_REQUEST['start_date'])));
- if (empty($start_parsed['error_count']) && empty($start_parsed['warning_count']))
- {
+
+ if (empty($start_parsed['error_count']) && empty($start_parsed['warning_count'])) {
$_REQUEST['year'] = $start_parsed['year'];
$_REQUEST['month'] = $start_parsed['month'];
$_REQUEST['day'] = $start_parsed['day'];
@@ -194,14 +216,13 @@ public function show(): void
$month = !empty($_REQUEST['month']) ? (int) $_REQUEST['month'] : $today['month'];
$day = !empty($_REQUEST['day']) ? (int) $_REQUEST['day'] : (!empty($_REQUEST['month']) ? 1 : $today['day']);
- $start_object = checkdate($month, $day, $year) === true ? new Time(implode('-', array($year, $month, $day)) . ' ' . User::getTimezone()) : new Time(implode('-', array($today['year'], $today['month'], $today['day'])) . ' ' . User::getTimezone());
+ $start_object = checkdate($month, $day, $year) === true ? new Time(implode('-', [$year, $month, $day]) . ' ' . User::getTimezone()) : new Time(implode('-', [$today['year'], $today['month'], $today['day']]) . ' ' . User::getTimezone());
// Need an end date for the list view
- if (!empty($_REQUEST['end_date']))
- {
+ if (!empty($_REQUEST['end_date'])) {
$end_parsed = date_parse(str_replace(',', '', self::convertDateToEnglish($_REQUEST['end_date'])));
- if (empty($end_parsed['error_count']) && empty($end_parsed['warning_count']))
- {
+
+ if (empty($end_parsed['error_count']) && empty($end_parsed['warning_count'])) {
$_REQUEST['end_year'] = $end_parsed['year'];
$_REQUEST['end_month'] = $end_parsed['month'];
$_REQUEST['end_day'] = $end_parsed['day'];
@@ -213,13 +234,11 @@ public function show(): void
$end_object = null;
- if (isset($end_month, $end_day, $end_year) && checkdate($end_month, $end_day, $end_year))
- {
- $end_object = new Time(implode('-', array($end_year, $end_month, $end_day)) . ' ' . User::getTimezone());
+ if (isset($end_month, $end_day, $end_year) && checkdate($end_month, $end_day, $end_year)) {
+ $end_object = new Time(implode('-', [$end_year, $end_month, $end_day]) . ' ' . User::getTimezone());
}
- if (empty($end_object) || $start_object >= $end_object)
- {
+ if (empty($end_object) || $start_object >= $end_object) {
$num_days_shown = empty(Config::$modSettings['cal_days_for_index']) || Config::$modSettings['cal_days_for_index'] < 1 ? 1 : Config::$modSettings['cal_days_for_index'];
$end_object = new Time($start_object->format('Y-m-d') . ' ' . User::getTimezone());
@@ -227,7 +246,7 @@ public function show(): void
date_add($end_object, date_interval_create_from_date_string($num_days_shown . ' days'));
}
- $curPage = array(
+ $curPage = [
'year' => $start_object->format('Y'),
'month' => $start_object->format('n'),
'day' => $start_object->format('j'),
@@ -236,66 +255,66 @@ public function show(): void
'end_month' => $end_object->format('n'),
'end_day' => $end_object->format('j'),
'end_date' => $end_object->format('Y-m-d'),
- );
+ ];
// Make sure the year and month are in valid ranges.
- if ($curPage['month'] < 1 || $curPage['month'] > 12)
- {
+ if ($curPage['month'] < 1 || $curPage['month'] > 12) {
ErrorHandler::fatalLang('invalid_month', false);
}
- if ($curPage['year'] < Config::$modSettings['cal_minyear'] || $curPage['year'] > Config::$modSettings['cal_maxyear'])
- {
+ if ($curPage['year'] < Config::$modSettings['cal_minyear'] || $curPage['year'] > Config::$modSettings['cal_maxyear']) {
ErrorHandler::fatalLang('invalid_year', false);
}
// If we have a day clean that too.
- if (Utils::$context['calendar_view'] != 'viewmonth')
- {
+ if (Utils::$context['calendar_view'] != 'viewmonth') {
$isValid = checkdate($curPage['month'], $curPage['day'], $curPage['year']);
- if (!$isValid)
+ if (!$isValid) {
ErrorHandler::fatalLang('invalid_day', false);
+ }
}
// Load all the context information needed to show the calendar grid.
- $calendarOptions = array(
+ $calendarOptions = [
'start_day' => !empty(Theme::$current->options['calendar_start_day']) ? Theme::$current->options['calendar_start_day'] : 0,
- 'show_birthdays' => in_array(Config::$modSettings['cal_showbdays'], array(1, 2)),
- 'show_events' => in_array(Config::$modSettings['cal_showevents'], array(1, 2)),
- 'show_holidays' => in_array(Config::$modSettings['cal_showholidays'], array(1, 2)),
+ 'show_birthdays' => in_array(Config::$modSettings['cal_showbdays'], [1, 2]),
+ 'show_events' => in_array(Config::$modSettings['cal_showevents'], [1, 2]),
+ 'show_holidays' => in_array(Config::$modSettings['cal_showholidays'], [1, 2]),
'show_week_num' => true,
'short_day_titles' => !empty(Config::$modSettings['cal_short_days']),
'short_month_titles' => !empty(Config::$modSettings['cal_short_months']),
'show_next_prev' => !empty(Config::$modSettings['cal_prev_next_links']),
- 'show_week_links' => isset(Config::$modSettings['cal_week_links']) ? Config::$modSettings['cal_week_links'] : 0,
- );
+ 'show_week_links' => Config::$modSettings['cal_week_links'] ?? 0,
+ ];
// Load up the main view.
- if (Utils::$context['calendar_view'] == 'viewlist')
+ if (Utils::$context['calendar_view'] == 'viewlist') {
Utils::$context['calendar_grid_main'] = self::getCalendarList($curPage['start_date'], $curPage['end_date'], $calendarOptions);
- elseif (Utils::$context['calendar_view'] == 'viewweek')
+ } elseif (Utils::$context['calendar_view'] == 'viewweek') {
Utils::$context['calendar_grid_main'] = self::getCalendarWeek($curPage['start_date'], $calendarOptions);
- else
+ } else {
Utils::$context['calendar_grid_main'] = self::getCalendarGrid($curPage['start_date'], $calendarOptions);
+ }
// Load up the previous and next months.
Utils::$context['calendar_grid_current'] = self::getCalendarGrid($curPage['start_date'], $calendarOptions, false, false);
// Only show previous month if it isn't pre-January of the min-year
- if (Utils::$context['calendar_grid_current']['previous_calendar']['year'] > Config::$modSettings['cal_minyear'] || $curPage['month'] != 1)
+ if (Utils::$context['calendar_grid_current']['previous_calendar']['year'] > Config::$modSettings['cal_minyear'] || $curPage['month'] != 1) {
Utils::$context['calendar_grid_prev'] = self::getCalendarGrid(Utils::$context['calendar_grid_current']['previous_calendar']['start_date'], $calendarOptions, true, false);
+ }
// Only show next month if it isn't post-December of the max-year
- if (Utils::$context['calendar_grid_current']['next_calendar']['year'] < Config::$modSettings['cal_maxyear'] || $curPage['month'] != 12)
+ if (Utils::$context['calendar_grid_current']['next_calendar']['year'] < Config::$modSettings['cal_maxyear'] || $curPage['month'] != 12) {
Utils::$context['calendar_grid_next'] = self::getCalendarGrid(Utils::$context['calendar_grid_current']['next_calendar']['start_date'], $calendarOptions, false, false);
+ }
// Basic template stuff.
Utils::$context['allow_calendar_event'] = User::$me->allowedTo('calendar_post');
// If you don't allow events not linked to posts and you're not an admin, we have more work to do...
- if (Utils::$context['allow_calendar_event'] && empty(Config::$modSettings['cal_allow_unlinked']) && !User::$me->is_admin)
- {
+ if (Utils::$context['allow_calendar_event'] && empty(Config::$modSettings['cal_allow_unlinked']) && !User::$me->is_admin) {
$boards_can_post = User::$me->boardsAllowedTo('post_new');
Utils::$context['allow_calendar_event'] &= !empty($boards_can_post);
}
@@ -308,31 +327,35 @@ public function show(): void
Utils::$context['blocks_disabled'] = !empty(Config::$modSettings['cal_disable_prev_next']) ? 1 : 0;
// Set the page title to mention the month or week, too
- if (Utils::$context['calendar_view'] != 'viewlist')
+ if (Utils::$context['calendar_view'] != 'viewlist') {
Utils::$context['page_title'] .= ' - ' . (Utils::$context['calendar_view'] == 'viewweek' ? Utils::$context['calendar_grid_main']['week_title'] : Lang::$txt['months_titles'][Utils::$context['current_month']] . ' ' . Utils::$context['current_year']);
+ }
// Load up the linktree!
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=calendar',
- 'name' => Lang::$txt['calendar']
- );
+ 'name' => Lang::$txt['calendar'],
+ ];
// Add the current month to the linktree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=calendar;year=' . Utils::$context['current_year'] . ';month=' . Utils::$context['current_month'],
- 'name' => Lang::$txt['months_titles'][Utils::$context['current_month']] . ' ' . Utils::$context['current_year']
- );
+ 'name' => Lang::$txt['months_titles'][Utils::$context['current_month']] . ' ' . Utils::$context['current_year'],
+ ];
+
// If applicable, add the current week to the linktree.
- if (Utils::$context['calendar_view'] == 'viewweek')
- Utils::$context['linktree'][] = array(
+ if (Utils::$context['calendar_view'] == 'viewweek') {
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=calendar;viewweek;year=' . Utils::$context['current_year'] . ';month=' . Utils::$context['current_month'] . ';day=' . Utils::$context['current_day'],
'name' => Utils::$context['calendar_grid_main']['week_title'],
- );
+ ];
+ }
// Build the calendar button array.
- Utils::$context['calendar_buttons'] = array();
+ Utils::$context['calendar_buttons'] = [];
- if (Utils::$context['can_post'])
- Utils::$context['calendar_buttons']['post_event'] = array('text' => 'calendar_post_event', 'image' => 'calendarpe.png', 'url' => Config::$scripturl . '?action=calendar;sa=post;month=' . Utils::$context['current_month'] . ';year=' . Utils::$context['current_year'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']);
+ if (Utils::$context['can_post']) {
+ Utils::$context['calendar_buttons']['post_event'] = ['text' => 'calendar_post_event', 'image' => 'calendarpe.png', 'url' => Config::$scripturl . '?action=calendar;sa=post;month=' . Utils::$context['current_month'] . ';year=' . Utils::$context['current_year'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']];
+ }
// Allow mods to add additional buttons here
IntegrationHook::call('integrate_calendar_buttons');
@@ -353,124 +376,116 @@ public function post(): void
User::$me->isAllowedTo('calendar_post');
// Cast this for safety...
- if (isset($_REQUEST['eventid']))
+ if (isset($_REQUEST['eventid'])) {
$_REQUEST['eventid'] = (int) $_REQUEST['eventid'];
+ }
// Submitting?
- if (isset($_POST[Utils::$context['session_var']], $_REQUEST['eventid']))
- {
+ if (isset($_POST[Utils::$context['session_var']], $_REQUEST['eventid'])) {
User::$me->checkSession();
// Validate the post...
- if (!isset($_POST['link_to_board']))
+ if (!isset($_POST['link_to_board'])) {
self::validateEventPost();
+ }
// If you're not allowed to edit any events, you have to be the poster.
- if ($_REQUEST['eventid'] > 0 && !User::$me->allowedTo('calendar_edit_any'))
+ if ($_REQUEST['eventid'] > 0 && !User::$me->allowedTo('calendar_edit_any')) {
User::$me->isAllowedTo('calendar_edit_' . (!empty(User::$me->id) && self::getEventPoster($_REQUEST['eventid']) == User::$me->id ? 'own' : 'any'));
+ }
// New - and directing?
- if (isset($_POST['link_to_board']) || empty(Config::$modSettings['cal_allow_unlinked']))
- {
+ if (isset($_POST['link_to_board']) || empty(Config::$modSettings['cal_allow_unlinked'])) {
$_REQUEST['calendar'] = 1;
Post::call();
+
return;
}
+
// New...
- elseif ($_REQUEST['eventid'] == -1)
- {
- $eventOptions = array(
+ if ($_REQUEST['eventid'] == -1) {
+ $eventOptions = [
'board' => 0,
'topic' => 0,
'title' => Utils::entitySubstr($_REQUEST['evtitle'], 0, 100),
'location' => Utils::entitySubstr($_REQUEST['event_location'], 0, 255),
'member' => User::$me->id,
- );
+ ];
Event::create($eventOptions);
}
// Deleting...
- elseif (isset($_REQUEST['deleteevent']))
- {
+ elseif (isset($_REQUEST['deleteevent'])) {
Event::remove($_REQUEST['eventid']);
}
// ... or just update it?
- else
- {
- $eventOptions = array(
+ else {
+ $eventOptions = [
'title' => Utils::entitySubstr($_REQUEST['evtitle'], 0, 100),
'location' => Utils::entitySubstr($_REQUEST['event_location'], 0, 255),
- );
+ ];
Event::modify($_REQUEST['eventid'], $eventOptions);
}
- Config::updateModSettings(array(
+ Config::updateModSettings([
'calendar_updated' => time(),
- ));
+ ]);
// No point hanging around here now...
- if (isset($_POST['start_date']))
- {
+ if (isset($_POST['start_date'])) {
$d = date_parse($_POST['start_date']);
$year = $d['year'];
$month = $d['month'];
$day = $d['day'];
- }
- elseif (isset($_POST['start_datetime']))
- {
+ } elseif (isset($_POST['start_datetime'])) {
$d = date_parse($_POST['start_datetime']);
$year = $d['year'];
$month = $d['month'];
$day = $d['day'];
- }
- else
- {
+ } else {
$today = getdate();
- $year = isset($_POST['year']) ? $_POST['year'] : $today['year'];
- $month = isset($_POST['month']) ? $_POST['month'] : $today['mon'];
- $day = isset($_POST['day']) ? $_POST['day'] : $today['mday'];
+ $year = $_POST['year'] ?? $today['year'];
+ $month = $_POST['month'] ?? $today['mon'];
+ $day = $_POST['day'] ?? $today['mday'];
}
Utils::redirectexit(Config::$scripturl . '?action=calendar;month=' . $month . ';year=' . $year . ';day=' . $day);
}
// If we are not enabled... we are not enabled.
- if (empty(Config::$modSettings['cal_allow_unlinked']) && empty($_REQUEST['eventid']))
- {
+ if (empty(Config::$modSettings['cal_allow_unlinked']) && empty($_REQUEST['eventid'])) {
$_REQUEST['calendar'] = 1;
Post::call();
+
return;
}
// New?
- if (!isset($_REQUEST['eventid']))
- {
+ if (!isset($_REQUEST['eventid'])) {
Utils::$context['event'] = new Event(-1);
- }
- else
- {
+ } else {
list(Utils::$context['event']) = Event::load($_REQUEST['eventid']);
- if (empty(Utils::$context['event']))
+ if (empty(Utils::$context['event'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
// If it has a board, then they should be editing it within the topic.
- if (!empty(Utils::$context['event']->topic) && !empty(Utils::$context['event']->msg))
- {
+ if (!empty(Utils::$context['event']->topic) && !empty(Utils::$context['event']->msg)) {
// We load the board up, for a check on the board access rights...
Topic::$topic_id = Utils::$context['event']->topic;
Board::load();
}
// Make sure the user is allowed to edit this event.
- if (Utils::$context['event']->member != User::$me->id)
+ if (Utils::$context['event']->member != User::$me->id) {
User::$me->isAllowedTo('calendar_edit_any');
- elseif (!User::$me->allowedTo('calendar_edit_any'))
+ } elseif (!User::$me->allowedTo('calendar_edit_any')) {
User::$me->isAllowedTo('calendar_edit_own');
+ }
}
// An all day event? Set up some nice defaults in case the user wants to change that
- if (Utils::$context['event']->allday == true)
- {
+ if (Utils::$context['event']->allday == true) {
Utils::$context['event']->tz = User::getTimezone();
Utils::$context['event']->start->modify(Time::create('now')->format('%H:%M:%S'));
Utils::$context['event']->end->modify(Time::create('now + 1 hour')->format('%H:%M:%S'));
@@ -484,20 +499,18 @@ public function post(): void
// Get list of boards that can be posted in.
$boards = User::$me->boardsAllowedTo('post_new');
- if (empty($boards))
- {
+
+ if (empty($boards)) {
// You can post new events but can't link them to anything...
- Utils::$context['event']->categories = array();
- }
- else
- {
+ Utils::$context['event']->categories = [];
+ } else {
// Load the list of boards and categories in the context.
- $boardListOptions = array(
+ $boardListOptions = [
'included_boards' => in_array(0, $boards) ? null : $boards,
'not_redirection' => true,
'use_permissions' => true,
'selected_board' => Config::$modSettings['cal_defaultboard'],
- );
+ ];
Utils::$context['event']->categories = MessageIndex::getBoardList($boardListOptions);
}
@@ -506,9 +519,9 @@ public function post(): void
Utils::$context['sub_template'] = 'event_post';
Utils::$context['page_title'] = isset($_REQUEST['eventid']) ? Lang::$txt['calendar_edit'] : Lang::$txt['calendar_post_event'];
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'name' => Utils::$context['page_title'],
- );
+ ];
self::loadDatePicker('#event_time_input .date_input');
self::loadTimePicker('#event_time_input .time_input', Time::getShortTimeFormat());
@@ -531,21 +544,24 @@ public function post(): void
public function export(): void
{
// You can't export if the calendar export feature is off.
- if (empty(Config::$modSettings['cal_export']))
+ if (empty(Config::$modSettings['cal_export'])) {
ErrorHandler::fatalLang('calendar_export_off', false);
+ }
// Goes without saying that this is required.
- if (!isset($_REQUEST['eventid']))
+ if (!isset($_REQUEST['eventid'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Load up the event in question and check it is valid.
list($event) = Event::load($_REQUEST['eventid']);
- if (!($event instanceof Event))
+ if (!($event instanceof Event)) {
ErrorHandler::fatalLang('no_access', false);
+ }
// This is what we will be sending later.
- $filecontents = array();
+ $filecontents = [];
$filecontents[] = 'BEGIN:VCALENDAR';
$filecontents[] = 'METHOD:PUBLISH';
$filecontents[] = 'PRODID:-//SimpleMachines//' . SMF_FULL_VERSION . '//EN';
@@ -557,17 +573,20 @@ public function export(): void
// Send some standard headers.
ob_end_clean();
- if (!empty(Config::$modSettings['enableCompressedOutput']))
+
+ if (!empty(Config::$modSettings['enableCompressedOutput'])) {
@ob_start('ob_gzhandler');
- else
+ } else {
ob_start();
+ }
// Send the file headers
header('pragma: ');
header('cache-control: no-cache');
- if (!BrowserDetector::isBrowser('gecko'))
+ if (!BrowserDetector::isBrowser('gecko')) {
header('content-transfer-encoding: binary');
+ }
header('expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
header('last-modified: ' . gmdate('D, d M Y H:i:s', $event->modified_time) . ' GMT');
@@ -575,8 +594,9 @@ public function export(): void
header('connection: close');
header('content-disposition: attachment; filename="' . $event->title . '.ics"');
- if (empty(Config::$modSettings['enableCompressedOutput']))
+ if (empty(Config::$modSettings['enableCompressedOutput'])) {
header('content-length: ' . Utils::entityStrlen($filecontents));
+ }
// This is a calendar item!
header('content-type: text/calendar');
@@ -597,14 +617,14 @@ public function clock(): void
Utils::$context['offimg'] = Theme::$current->settings['images_url'] . '/bbc/bbc_bg.png';
Utils::$context['page_title'] = 'Anyone know what time it is?';
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=calendar',
'name' => Lang::$txt['calendar'],
- );
- Utils::$context['linktree'][] = array(
+ ];
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=calendar;sa=clock',
'name' => 'Clock',
- );
+ ];
Utils::$context['robot_no_index'] = true;
$omfg = isset($_REQUEST['omfg']);
@@ -612,45 +632,35 @@ public function clock(): void
Theme::loadTemplate('Calendar');
- if ($bcd)
- {
+ if ($bcd) {
Utils::$context['sub_template'] = 'bcd';
- Utils::$context['linktree'][] = array('url' => Config::$scripturl . '?action=calendar;sa=clock;bcd', 'name' => 'BCD');
+ Utils::$context['linktree'][] = ['url' => Config::$scripturl . '?action=calendar;sa=clock;bcd', 'name' => 'BCD'];
Utils::$context['clockicons'] = Utils::jsonDecode(base64_decode('eyJoMSI6WzIsMV0sImgyIjpbOCw0LDIsMV0sIm0xIjpbNCwyLDFdLCJtMiI6WzgsNCwyLDFdLCJzMSI6WzQsMiwxXSwiczIiOls4LDQsMiwxXX0='), true);
- }
- elseif (!$omfg && !isset($_REQUEST['time']))
- {
+ } elseif (!$omfg && !isset($_REQUEST['time'])) {
Utils::$context['sub_template'] = 'hms';
- Utils::$context['linktree'][] = array('url' => Config::$scripturl . '?action=calendar;sa=clock', 'name' => 'Binary');
+ Utils::$context['linktree'][] = ['url' => Config::$scripturl . '?action=calendar;sa=clock', 'name' => 'Binary'];
Utils::$context['clockicons'] = Utils::jsonDecode(base64_decode('eyJoIjpbMTYsOCw0LDIsMV0sIm0iOlszMiwxNiw4LDQsMiwxXSwicyI6WzMyLDE2LDgsNCwyLDFdfQ'), true);
- }
- elseif ($omfg)
- {
+ } elseif ($omfg) {
Utils::$context['sub_template'] = 'omfg';
- Utils::$context['linktree'][] = array('url' => Config::$scripturl . '?action=calendar;sa=clock;omfg', 'name' => 'OMFG');
+ Utils::$context['linktree'][] = ['url' => Config::$scripturl . '?action=calendar;sa=clock;omfg', 'name' => 'OMFG'];
Utils::$context['clockicons'] = Utils::jsonDecode(base64_decode('eyJ5ZWFyIjpbNjQsMzIsMTYsOCw0LDIsMV0sIm1vbnRoIjpbOCw0LDIsMV0sImRheSI6WzE2LDgsNCwyLDFdLCJob3VyIjpbMTYsOCw0LDIsMV0sIm1pbiI6WzMyLDE2LDgsNCwyLDFdLCJzZWMiOlszMiwxNiw4LDQsMiwxXX0='), true);
- }
- elseif (isset($_REQUEST['time']))
- {
+ } elseif (isset($_REQUEST['time'])) {
Utils::$context['sub_template'] = 'thetime';
$_REQUEST['time'] = $_REQUEST['time'] == '' ? 'now' : $_REQUEST['time'];
$time = getdate($_REQUEST['time'] == 'now' ? time() : (int) $_REQUEST['time']);
- Utils::$context['linktree'][] = array('url' => Config::$scripturl . '?action=calendar;sa=clock;time=' . $_REQUEST['time'], 'name' => 'Requested Time');
- Utils::$context['clockicons'] = array(
- 'year' => array_fill_keys(array_map(fn($p) => 2**$p, range(6, 0)), false),
- 'mon' => array_fill_keys(array_map(fn($p) => 2**$p, range(3, 0)), false),
- 'mday' => array_fill_keys(array_map(fn($p) => 2**$p, range(4, 0)), false),
- 'hours' => array_fill_keys(array_map(fn($p) => 2**$p, range(5, 0)), false),
- 'minutes' => array_fill_keys(array_map(fn($p) => 2**$p, range(5, 0)), false),
- 'seconds' => array_fill_keys(array_map(fn($p) => 2**$p, range(5, 0)), false),
- );
-
- foreach (Utils::$context['clockicons'] as $t => $vs)
- {
- foreach ($vs as $v => $dumb)
- {
- if ($time[$t] >= $v)
- {
+ Utils::$context['linktree'][] = ['url' => Config::$scripturl . '?action=calendar;sa=clock;time=' . $_REQUEST['time'], 'name' => 'Requested Time'];
+ Utils::$context['clockicons'] = [
+ 'year' => array_fill_keys(array_map(fn ($p) => 2 ** $p, range(6, 0)), false),
+ 'mon' => array_fill_keys(array_map(fn ($p) => 2 ** $p, range(3, 0)), false),
+ 'mday' => array_fill_keys(array_map(fn ($p) => 2 ** $p, range(4, 0)), false),
+ 'hours' => array_fill_keys(array_map(fn ($p) => 2 ** $p, range(5, 0)), false),
+ 'minutes' => array_fill_keys(array_map(fn ($p) => 2 ** $p, range(5, 0)), false),
+ 'seconds' => array_fill_keys(array_map(fn ($p) => 2 ** $p, range(5, 0)), false),
+ ];
+
+ foreach (Utils::$context['clockicons'] as $t => $vs) {
+ foreach ($vs as $v => $dumb) {
+ if ($time[$t] >= $v) {
$time[$t] -= $v;
Utils::$context['clockicons'][$t][$v] = true;
}
@@ -670,8 +680,9 @@ public function clock(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -719,11 +730,11 @@ public static function getBirthdayRange($low_date, $high_date): array
$year_low = (int) substr($low_date, 0, 4);
$year_high = (int) substr($high_date, 0, 4);
- if (Db::$db->title !== POSTGRE_TITLE)
- {
+ if (Db::$db->title !== POSTGRE_TITLE) {
// Collect all of the birthdays for this month. I know, it's a painful query.
- $result = Db::$db->query('', '
- SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
FROM {db_prefix}members
WHERE birthdate != {date:no_birthdate}
AND (
@@ -731,20 +742,19 @@ public static function getBirthdayRange($low_date, $high_date): array
OR DATE_FORMAT(birthdate, {string:year_high}) BETWEEN {date:low_date} AND {date:high_date}') . '
)
AND is_activated = {int:is_activated}',
- array(
+ [
'is_activated' => 1,
'no_birthdate' => '1004-01-01',
'year_low' => $year_low . '-%m-%d',
'year_high' => $year_high . '-%m-%d',
'low_date' => $low_date,
'high_date' => $high_date,
- )
+ ],
);
- }
- else
- {
- $result = Db::$db->query('', '
- SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
+ } else {
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
FROM {db_prefix}members
WHERE birthdate != {date:no_birthdate}
AND (
@@ -752,38 +762,40 @@ public static function getBirthdayRange($low_date, $high_date): array
OR indexable_month_day(birthdate) BETWEEN indexable_month_day({date:year_high_low_date}) AND indexable_month_day({date:year_high_high_date})') . '
)
AND is_activated = {int:is_activated}',
- array(
+ [
'is_activated' => 1,
'no_birthdate' => '1004-01-01',
'year_low_low_date' => $low_date,
'year_low_high_date' => $year_low == $year_high ? $high_date : $year_low . '-12-31',
'year_high_low_date' => $year_low == $year_high ? $low_date : $year_high . '-01-01',
'year_high_high_date' => $high_date,
- )
+ ],
);
}
- $bday = array();
- while ($row = Db::$db->fetch_assoc($result))
- {
- if ($year_low != $year_high)
+ $bday = [];
+
+ while ($row = Db::$db->fetch_assoc($result)) {
+ if ($year_low != $year_high) {
$age_year = substr($row['birthdate'], 5) <= substr($high_date, 5) ? $year_high : $year_low;
- else
+ } else {
$age_year = $year_low;
+ }
- $bday[$age_year . substr($row['birthdate'], 4)][] = array(
+ $bday[$age_year . substr($row['birthdate'], 4)][] = [
'id' => $row['id_member'],
'name' => $row['real_name'],
'age' => $row['birth_year'] > 1004 && $row['birth_year'] <= $age_year ? $age_year - $row['birth_year'] : null,
- 'is_last' => false
- );
+ 'is_last' => false,
+ ];
}
Db::$db->free_result($result);
ksort($bday);
// Set is_last, so the themes know when to stop placing separators.
- foreach ($bday as $mday => $array)
+ foreach ($bday as $mday => $array) {
$bday[$mday][count($array) - 1]['is_last'] = true;
+ }
return $bday;
}
@@ -803,24 +815,23 @@ public static function getBirthdayRange($low_date, $high_date): array
*/
public static function getEventRange($low_date, $high_date, $use_permissions = true): array
{
- $events = array();
+ $events = [];
$one_day = date_interval_create_from_date_string('1 day');
$tz = timezone_open(User::getTimezone());
- foreach (Event::loadRange($low_date, $high_date, $use_permissions) as $event)
- {
+ foreach (Event::loadRange($low_date, $high_date, $use_permissions) as $event) {
$cal_date = new Time($event->start_date_local, $tz);
- while ($cal_date->getTimestamp() <= $event->end->getTimestamp() && $cal_date->format('Y-m-d') <= $high_date)
- {
+ while ($cal_date->getTimestamp() <= $event->end->getTimestamp() && $cal_date->format('Y-m-d') <= $high_date) {
$events[$cal_date->format('Y-m-d')][] = $event;
date_add($cal_date, $one_day);
}
}
- foreach ($events as $mday => $array)
+ foreach ($events as $mday => $array) {
$events[$mday][count($array) - 1]['is_last'] = true;
+ }
ksort($events);
@@ -837,34 +848,37 @@ public static function getEventRange($low_date, $high_date, $use_permissions = t
public static function getHolidayRange($low_date, $high_date): array
{
// Get the lowest and highest dates for "all years".
- if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
+ if (substr($low_date, 0, 4) != substr($high_date, 0, 4)) {
$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_dec}
OR event_date BETWEEN {date:all_year_jan} AND {date:all_year_high}';
- else
+ } else {
$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_high}';
+ }
// Find some holidays... ;).
- $result = Db::$db->query('', '
- SELECT event_date, YEAR(event_date) AS year, title
+ $result = Db::$db->query(
+ '',
+ 'SELECT event_date, YEAR(event_date) AS year, title
FROM {db_prefix}calendar_holidays
WHERE event_date BETWEEN {date:low_date} AND {date:high_date}
OR ' . $allyear_part,
- array(
+ [
'low_date' => $low_date,
'high_date' => $high_date,
'all_year_low' => '1004' . substr($low_date, 4),
'all_year_high' => '1004' . substr($high_date, 4),
'all_year_jan' => '1004-01-01',
'all_year_dec' => '1004-12-31',
- )
+ ],
);
- $holidays = array();
- while ($row = Db::$db->fetch_assoc($result))
- {
- if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
+ $holidays = [];
+
+ while ($row = Db::$db->fetch_assoc($result)) {
+ if (substr($low_date, 0, 4) != substr($high_date, 0, 4)) {
$event_year = substr($row['event_date'], 5) < substr($high_date, 5) ? substr($high_date, 0, 4) : substr($low_date, 0, 4);
- else
+ } else {
$event_year = substr($low_date, 0, 4);
+ }
$holidays[$event_year . substr($row['event_date'], 4)][] = $row['title'];
}
@@ -889,34 +903,36 @@ public static function canLinkEvent(): void
User::$me->isAllowedTo('calendar_post');
// No board? No topic?!?
- if (empty(Board::$info->id))
+ if (empty(Board::$info->id)) {
ErrorHandler::fatalLang('missing_board_id', false);
+ }
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
ErrorHandler::fatalLang('missing_topic_id', false);
+ }
// Administrator, Moderator, or owner. Period.
- if (!User::$me->allowedTo('admin_forum') && !User::$me->allowedTo('moderate_board'))
- {
+ if (!User::$me->allowedTo('admin_forum') && !User::$me->allowedTo('moderate_board')) {
// Not admin or a moderator of this board. You better be the owner - or else.
- $result = Db::$db->query('', '
- SELECT id_member_started
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_member_started
FROM {db_prefix}topics
WHERE id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
- )
+ ],
);
- if ($row = Db::$db->fetch_assoc($result))
- {
+
+ if ($row = Db::$db->fetch_assoc($result)) {
// Not the owner of the topic.
- if ($row['id_member_started'] != User::$me->id)
+ if ($row['id_member_started'] != User::$me->id) {
ErrorHandler::fatalLang('not_your_topic', 'user');
+ }
}
// Topic/Board doesn't exist.....
- else
- {
+ else {
ErrorHandler::fatalLang('calendar_no_topic', 'general');
}
Db::$db->free_result($result);
@@ -932,12 +948,12 @@ public static function canLinkEvent(): void
*/
public static function getTodayInfo(): array
{
- return array(
+ return [
'day' => (int) Time::strftime('%d', time(), User::getTimezone()),
'month' => (int) Time::strftime('%m', time(), User::getTimezone()),
'year' => (int) Time::strftime('%Y', time(), User::getTimezone()),
'date' => Time::strftime('%Y-%m-%d', time(), User::getTimezone()),
- );
+ ];
}
/**
@@ -960,32 +976,32 @@ public static function getCalendarGrid($selected_date, $calendarOptions, $is_pre
$prev_object->modify('first day of previous month');
// Eventually this is what we'll be returning.
- $calendarGrid = array(
- 'week_days' => array(),
- 'weeks' => array(),
+ $calendarGrid = [
+ 'week_days' => [],
+ 'weeks' => [],
'short_day_titles' => !empty($calendarOptions['short_day_titles']),
'short_month_titles' => !empty($calendarOptions['short_month_titles']),
'current_month' => $selected_object->format('n'),
'current_year' => $selected_object->format('Y'),
'current_day' => $selected_object->format('d'),
'show_next_prev' => !empty($calendarOptions['show_next_prev']),
- 'show_week_links' => isset($calendarOptions['show_week_links']) ? $calendarOptions['show_week_links'] : 0,
- 'previous_calendar' => array(
+ 'show_week_links' => $calendarOptions['show_week_links'] ?? 0,
+ 'previous_calendar' => [
'year' => $prev_object->format('Y'),
'month' => $prev_object->format('n'),
'day' => $prev_object->format('d'),
'start_date' => $prev_object->format('Y-m-d'),
'disabled' => Config::$modSettings['cal_minyear'] > $prev_object->format('Y'),
- ),
- 'next_calendar' => array(
+ ],
+ 'next_calendar' => [
'year' => $next_object->format('Y'),
'month' => $next_object->format('n'),
'day' => $next_object->format('d'),
'start_date' => $next_object->format('Y-m-d'),
'disabled' => Config::$modSettings['cal_maxyear'] < $next_object->format('Y'),
- ),
+ ],
'start_date' => $selected_object->format(Time::getDateFormat()),
- );
+ ];
// Get today's date.
$today = self::getTodayInfo();
@@ -994,19 +1010,19 @@ public static function getCalendarGrid($selected_date, $calendarOptions, $is_pre
$last_day_object = new Time($selected_object->format('Y-m-t') . ' ' . User::getTimezone());
// Get information about this month.
- $month_info = array(
- 'first_day' => array(
+ $month_info = [
+ 'first_day' => [
'day_of_week' => $first_day_object->format('w'),
'week_num' => $first_day_object->format('W'),
'date' => $first_day_object->format('Y-m-d'),
- ),
- 'last_day' => array(
+ ],
+ 'last_day' => [
'day_of_month' => $last_day_object->format('t'),
'date' => $last_day_object->format('Y-m-d'),
- ),
+ ],
'first_day_of_year' => Time::create($selected_object->format('Y-01-01') . ' ' . User::getTimezone())->format('w'),
'first_day_of_next_year' => Time::create(($selected_object->format('Y') + 1) . '-01-01' . ' ' . User::getTimezone())->format('w'),
- );
+ ];
// The number of days the first row is shifted to the right for the starting day.
$nShift = $month_info['first_day']['day_of_week'];
@@ -1014,68 +1030,74 @@ public static function getCalendarGrid($selected_date, $calendarOptions, $is_pre
$calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
// Starting any day other than Sunday means a shift...
- if (!empty($calendarOptions['start_day']))
- {
+ if (!empty($calendarOptions['start_day'])) {
$nShift -= $calendarOptions['start_day'];
- if ($nShift < 0)
+
+ if ($nShift < 0) {
$nShift = 7 + $nShift;
+ }
}
// Number of rows required to fit the month.
$nRows = floor(($month_info['last_day']['day_of_month'] + $nShift) / 7);
- if (($month_info['last_day']['day_of_month'] + $nShift) % 7)
+
+ if (($month_info['last_day']['day_of_month'] + $nShift) % 7) {
$nRows++;
+ }
// Fetch the arrays for birthdays, posted events, and holidays.
- $bday = $calendarOptions['show_birthdays'] ? self::getBirthdayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
- $events = $calendarOptions['show_events'] ? self::getEventRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
- $holidays = $calendarOptions['show_holidays'] ? self::getHolidayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
+ $bday = $calendarOptions['show_birthdays'] ? self::getBirthdayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : [];
+ $events = $calendarOptions['show_events'] ? self::getEventRange($month_info['first_day']['date'], $month_info['last_day']['date']) : [];
+ $holidays = $calendarOptions['show_holidays'] ? self::getHolidayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : [];
// Days of the week taking into consideration that they may want it to start on any day.
$count = $calendarOptions['start_day'];
- for ($i = 0; $i < 7; $i++)
- {
+
+ for ($i = 0; $i < 7; $i++) {
$calendarGrid['week_days'][] = $count;
$count++;
- if ($count == 7)
+
+ if ($count == 7) {
$count = 0;
+ }
}
// Iterate through each week.
- $calendarGrid['weeks'] = array();
- for ($nRow = 0; $nRow < $nRows; $nRow++)
- {
+ $calendarGrid['weeks'] = [];
+
+ for ($nRow = 0; $nRow < $nRows; $nRow++) {
// Start off the week - and don't let it go above 52, since that's the number of weeks in a year.
- $calendarGrid['weeks'][$nRow] = array(
- 'days' => array(),
- );
+ $calendarGrid['weeks'][$nRow] = [
+ 'days' => [],
+ ];
// And figure out all the days.
- for ($nCol = 0; $nCol < 7; $nCol++)
- {
+ for ($nCol = 0; $nCol < 7; $nCol++) {
$nDay = ($nRow * 7) + $nCol - $nShift + 1;
- if ($nDay < 1 || $nDay > $month_info['last_day']['day_of_month'])
+ if ($nDay < 1 || $nDay > $month_info['last_day']['day_of_month']) {
$nDay = 0;
+ }
$date = $selected_object->format('Y-m-') . sprintf('%02d', $nDay);
- $calendarGrid['weeks'][$nRow]['days'][$nCol] = array(
+ $calendarGrid['weeks'][$nRow]['days'][$nCol] = [
'day' => $nDay,
'date' => $date,
'is_today' => $date == $today['date'],
'is_first_day' => !empty($calendarOptions['show_week_num']) && (($month_info['first_day']['day_of_week'] + $nDay - 1) % 7 == $calendarOptions['start_day']),
'is_first_of_month' => $nDay === 1,
- 'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
- 'events' => !empty($events[$date]) ? $events[$date] : array(),
- 'birthdays' => !empty($bday[$date]) ? $bday[$date] : array(),
- );
+ 'holidays' => !empty($holidays[$date]) ? $holidays[$date] : [],
+ 'events' => !empty($events[$date]) ? $events[$date] : [],
+ 'birthdays' => !empty($bday[$date]) ? $bday[$date] : [],
+ ];
}
}
// What is the last day of the month?
- if ($is_previous === true)
+ if ($is_previous === true) {
$calendarGrid['last_of_month'] = $month_info['last_day']['day_of_month'];
+ }
// We'll use the shift in the template.
$calendarGrid['shift'] = $nShift;
@@ -1085,8 +1107,7 @@ public static function getCalendarGrid($selected_date, $calendarOptions, $is_pre
$calendarGrid['next_calendar']['href'] = Config::$scripturl . '?action=calendar;viewmonth;year=' . $calendarGrid['next_calendar']['year'] . ';month=' . $calendarGrid['next_calendar']['month'] . ';day=' . $calendarGrid['previous_calendar']['day'];
- if ($has_picker)
- {
+ if ($has_picker) {
self::loadDatePicker('#calendar_navigation .date_input');
self::loadDatePair('#calendar_navigation', 'date_input');
}
@@ -1113,12 +1134,14 @@ public static function getCalendarWeek($selected_date, $calendarOptions): array
$day_of_week = $selected_object->format('w');
$first_day_object = new Time($selected_date . ' ' . User::getTimezone());
- if ($day_of_week != $calendarOptions['start_day'])
- {
+
+ if ($day_of_week != $calendarOptions['start_day']) {
// Here we offset accordingly to get things to the real start of a week.
$date_diff = $day_of_week - $calendarOptions['start_day'];
- if ($date_diff < 0)
+
+ if ($date_diff < 0) {
$date_diff += 7;
+ }
date_sub($first_day_object, date_interval_create_from_date_string($date_diff . ' days'));
}
@@ -1137,62 +1160,62 @@ public static function getCalendarWeek($selected_date, $calendarOptions): array
date_sub($prev_object, date_interval_create_from_date_string('1 week'));
// Now start filling in the calendar grid.
- $calendarGrid = array(
+ $calendarGrid = [
'show_next_prev' => !empty($calendarOptions['show_next_prev']),
- 'previous_week' => array(
+ 'previous_week' => [
'year' => $prev_object->format('Y'),
'month' => $prev_object->format('n'),
'day' => $prev_object->format('d'),
'start_date' => $prev_object->format('Y-m-d'),
'disabled' => Config::$modSettings['cal_minyear'] > $prev_object->format('Y'),
- ),
- 'next_week' => array(
+ ],
+ 'next_week' => [
'year' => $next_object->format('Y'),
'month' => $next_object->format('n'),
'day' => $next_object->format('d'),
'start_date' => $next_object->format('Y-m-d'),
'disabled' => Config::$modSettings['cal_maxyear'] < $next_object->format('Y'),
- ),
+ ],
'start_date' => $selected_object->format(Time::getDateFormat()),
'show_events' => $calendarOptions['show_events'],
'show_holidays' => $calendarOptions['show_holidays'],
'show_birthdays' => $calendarOptions['show_birthdays'],
- );
+ ];
// Fetch the arrays for birthdays, posted events, and holidays.
- $bday = $calendarOptions['show_birthdays'] ? self::getBirthdayRange($first_day_object->format('Y-m-d'), $last_day_object->format('Y-m-d')) : array();
- $events = $calendarOptions['show_events'] ? self::getEventRange($first_day_object->format('Y-m-d'), $last_day_object->format('Y-m-d')) : array();
- $holidays = $calendarOptions['show_holidays'] ? self::getHolidayRange($first_day_object->format('Y-m-d'), $last_day_object->format('Y-m-d')) : array();
+ $bday = $calendarOptions['show_birthdays'] ? self::getBirthdayRange($first_day_object->format('Y-m-d'), $last_day_object->format('Y-m-d')) : [];
+ $events = $calendarOptions['show_events'] ? self::getEventRange($first_day_object->format('Y-m-d'), $last_day_object->format('Y-m-d')) : [];
+ $holidays = $calendarOptions['show_holidays'] ? self::getHolidayRange($first_day_object->format('Y-m-d'), $last_day_object->format('Y-m-d')) : [];
$calendarGrid['week_title'] = sprintf(Lang::$txt['calendar_week_beginning'], Lang::$txt['months'][$first_day_object->format('n')], $first_day_object->format('j'), $first_day_object->format('Y'));
// This holds all the main data - there is at least one month!
- $calendarGrid['months'] = array();
+ $calendarGrid['months'] = [];
$current_day_object = new Time($first_day_object->format('Y-m-d') . ' ' . User::getTimezone());
- for ($i = 0; $i < 7; $i++)
- {
+ for ($i = 0; $i < 7; $i++) {
$current_month = $current_day_object->format('n');
$current_day = $current_day_object->format('j');
$current_date = $current_day_object->format('Y-m-d');
- if (!isset($calendarGrid['months'][$current_month]))
- $calendarGrid['months'][$current_month] = array(
+ if (!isset($calendarGrid['months'][$current_month])) {
+ $calendarGrid['months'][$current_month] = [
'current_month' => $current_month,
'current_year' => $current_day_object->format('Y'),
- 'days' => array(),
- );
+ 'days' => [],
+ ];
+ }
- $calendarGrid['months'][$current_month]['days'][$current_day] = array(
+ $calendarGrid['months'][$current_month]['days'][$current_day] = [
'day' => $current_day,
'day_of_week' => ($current_day_object->format('w') + 7) % 7,
'date' => $current_date,
'is_today' => $current_date == $today['date'],
- 'holidays' => !empty($holidays[$current_date]) ? $holidays[$current_date] : array(),
- 'events' => !empty($events[$current_date]) ? $events[$current_date] : array(),
- 'birthdays' => !empty($bday[$current_date]) ? $bday[$current_date] : array()
- );
+ 'holidays' => !empty($holidays[$current_date]) ? $holidays[$current_date] : [],
+ 'events' => !empty($events[$current_date]) ? $events[$current_date] : [],
+ 'birthdays' => !empty($bday[$current_date]) ? $bday[$current_date] : [],
+ ];
date_add($current_day_object, date_interval_create_from_date_string('1 day'));
}
@@ -1222,7 +1245,7 @@ public static function getCalendarList($start_date, $end_date, $calendarOptions)
$start_object = new Time($start_date . ' ' . User::getTimezone());
$end_object = new Time($end_date . ' ' . User::getTimezone());
- $calendarGrid = array(
+ $calendarGrid = [
'start_date' => $start_object->format(Time::getDateFormat()),
'start_year' => $start_object->format('Y'),
'start_month' => $start_object->format('m'),
@@ -1231,37 +1254,34 @@ public static function getCalendarList($start_date, $end_date, $calendarOptions)
'end_year' => $end_object->format('Y'),
'end_month' => $end_object->format('m'),
'end_day' => $end_object->format('d'),
- );
+ ];
- $calendarGrid['birthdays'] = $calendarOptions['show_birthdays'] ? self::getBirthdayRange($start_date, $end_date) : array();
- $calendarGrid['holidays'] = $calendarOptions['show_holidays'] ? self::getHolidayRange($start_date, $end_date) : array();
- $calendarGrid['events'] = $calendarOptions['show_events'] ? self::getEventRange($start_date, $end_date) : array();
+ $calendarGrid['birthdays'] = $calendarOptions['show_birthdays'] ? self::getBirthdayRange($start_date, $end_date) : [];
+ $calendarGrid['holidays'] = $calendarOptions['show_holidays'] ? self::getHolidayRange($start_date, $end_date) : [];
+ $calendarGrid['events'] = $calendarOptions['show_events'] ? self::getEventRange($start_date, $end_date) : [];
// Get rid of duplicate events
- $temp = array();
- foreach ($calendarGrid['events'] as $date => $date_events)
- {
- foreach ($date_events as $event_key => $event_val)
- {
- if (in_array($event_val['id'], $temp))
- {
+ $temp = [];
+
+ foreach ($calendarGrid['events'] as $date => $date_events) {
+ foreach ($date_events as $event_key => $event_val) {
+ if (in_array($event_val['id'], $temp)) {
unset($calendarGrid['events'][$date][$event_key]);
- if (empty($calendarGrid['events'][$date]))
+ if (empty($calendarGrid['events'][$date])) {
unset($calendarGrid['events'][$date]);
- }
- else
+ }
+ } else {
$temp[] = $event_val['id'];
+ }
}
}
// Give birthdays and holidays a friendly format, without the year.
$date_format = Time::getShortDateFormat();
- foreach (array('birthdays', 'holidays') as $type)
- {
- foreach ($calendarGrid[$type] as $date => $date_content)
- {
+ foreach (['birthdays', 'holidays'] as $type) {
+ foreach ($calendarGrid[$type] as $date => $date_content) {
// Make sure to apply no offsets
$date_local = preg_replace('~(?<=\s)0+(\d)~', '$1', trim(Time::create($date)->format($date_format), " \t\n\r\0\x0B,./;:<>()[]{}\\|-_=+"));
@@ -1283,11 +1303,12 @@ public static function getCalendarList($start_date, $end_date, $calendarOptions)
*/
public static function loadDatePicker($selector = 'input.date_input', $date_format = ''): void
{
- if (empty($date_format))
+ if (empty($date_format)) {
$date_format = Time::getDateFormat();
+ }
// Convert to format used by datepicker
- $date_format = strtr($date_format, array(
+ $date_format = strtr($date_format, [
// Day
'%a' => 'D', '%A' => 'DD', '%e' => 'd', '%d' => 'dd', '%j' => 'oo', '%u' => '', '%w' => '',
// Week
@@ -1303,10 +1324,10 @@ public static function loadDatePicker($selector = 'input.date_input', $date_form
'%c' => 'D, d M yy', '%D' => 'mm/dd/y', '%F' => 'yy-mm-dd', '%s' => '@', '%x' => 'D, d M yy',
// Miscellaneous
'%n' => ' ', '%t' => ' ', '%%' => '%',
- ));
+ ]);
- Theme::loadCSSFile('jquery-ui.datepicker.css', array(), 'smf_datepicker');
- Theme::loadJavaScriptFile('jquery-ui.datepicker.min.js', array('defer' => true), 'smf_datepicker');
+ Theme::loadCSSFile('jquery-ui.datepicker.css', [], 'smf_datepicker');
+ Theme::loadJavaScriptFile('jquery-ui.datepicker.min.js', ['defer' => true], 'smf_datepicker');
Theme::addInlineJavaScript('
$("' . $selector . '").datepicker({
dateFormat: "' . $date_format . '",
@@ -1336,11 +1357,12 @@ public static function loadDatePicker($selector = 'input.date_input', $date_form
*/
public static function loadTimePicker($selector = 'input.time_input', $time_format = ''): void
{
- if (empty($time_format))
+ if (empty($time_format)) {
$time_format = Time::getTimeFormat();
+ }
// Format used for timepicker
- $time_format = strtr($time_format, array(
+ $time_format = strtr($time_format, [
'%H' => 'H',
'%k' => 'G',
'%I' => 'h',
@@ -1353,10 +1375,10 @@ public static function loadTimePicker($selector = 'input.time_input', $time_form
'%S' => 's',
'%T' => 'H:i:s',
'%X' => 'H:i:s',
- ));
+ ]);
- Theme::loadCSSFile('jquery.timepicker.css', array(), 'smf_timepicker');
- Theme::loadJavaScriptFile('jquery.timepicker.min.js', array('defer' => true), 'smf_timepicker');
+ Theme::loadCSSFile('jquery.timepicker.css', [], 'smf_timepicker');
+ Theme::loadJavaScriptFile('jquery.timepicker.min.js', ['defer' => true], 'smf_timepicker');
Theme::addInlineJavaScript('
$("' . $selector . '").timepicker({
timeFormat: "' . $time_format . '",
@@ -1390,22 +1412,20 @@ public static function loadDatePair($container, $date_class = '', $time_class =
$date_class = (string) $date_class;
$time_class = (string) $time_class;
- if ($container == '')
+ if ($container == '') {
return;
+ }
- Theme::loadJavaScriptFile('jquery.datepair.min.js', array('defer' => true), 'smf_datepair');
+ Theme::loadJavaScriptFile('jquery.datepair.min.js', ['defer' => true], 'smf_datepair');
$datepair_options = '';
// If we're not using a date input, we might as well disable these.
- if ($date_class == '')
- {
+ if ($date_class == '') {
$datepair_options .= '
parseDate: function (el) {},
updateDate: function (el, v) {},';
- }
- else
- {
+ } else {
$datepair_options .= '
dateClass: "' . $date_class . '",';
@@ -1425,22 +1445,18 @@ public static function loadDatePair($container, $date_class = '', $time_class =
}
// If not using a time input, disable time functions.
- if ($time_class == '')
- {
+ if ($time_class == '') {
$datepair_options .= '
parseTime: function(input){},
updateTime: function(input, dateObj){},
setMinTime: function(input, dateObj){},';
- }
- else
- {
+ } else {
$datepair_options .= '
timeClass: "' . $time_class . '",';
}
Theme::addInlineJavaScript('
$("' . $container . '").datepair({' . $datepair_options . "\n\t});", true);
-
}
/**
@@ -1459,15 +1475,15 @@ public static function cache_getOffsetIndependentEvents($eventOptions): array
$low_date = Time::strftime('%Y-%m-%d', time() - 24 * 3600);
$high_date = Time::strftime('%Y-%m-%d', time() + $days_to_index * 24 * 3600);
- return array(
- 'data' => array(
- 'holidays' => (!empty($eventOptions['include_holidays']) ? self::getHolidayRange($low_date, $high_date) : array()),
- 'birthdays' => (!empty($eventOptions['include_birthdays']) ? self::getBirthdayRange($low_date, $high_date) : array()),
- 'events' => (!empty($eventOptions['include_events']) ? self::getEventRange($low_date, $high_date, false) : array()),
- ),
- 'refresh_eval' => 'return \'' . Time::strftime('%Y%m%d', time()) . '\' != \SMF\Time::strftime(\'%Y%m%d\', time()) || (!empty(\SMF\Config::$modSettings[\'calendar_updated\']) && ' . time() . ' < \SMF\Config::$modSettings[\'calendar_updated\']);',
+ return [
+ 'data' => [
+ 'holidays' => (!empty($eventOptions['include_holidays']) ? self::getHolidayRange($low_date, $high_date) : []),
+ 'birthdays' => (!empty($eventOptions['include_birthdays']) ? self::getBirthdayRange($low_date, $high_date) : []),
+ 'events' => (!empty($eventOptions['include_events']) ? self::getEventRange($low_date, $high_date, false) : []),
+ ],
+ 'refresh_eval' => 'return \'' . Time::strftime('%Y%m%d', time()) . '\' != \\SMF\\Time::strftime(\'%Y%m%d\', time()) || (!empty(\\SMF\\Config::$modSettings[\'calendar_updated\']) && ' . time() . ' < \\SMF\\Config::$modSettings[\'calendar_updated\']);',
'expires' => time() + 3600,
- );
+ ];
}
/**
@@ -1481,16 +1497,16 @@ public static function cache_getOffsetIndependentEvents($eventOptions): array
public static function cache_getRecentEvents($eventOptions): array
{
// With the 'static' cached data we can calculate the user-specific data.
- $cached_data = CacheApi::quickGet('calendar_index', 'Actions/Calendar.php', 'SMF\\Actions\\Calendar::cache_getOffsetIndependentEvents', array($eventOptions));
+ $cached_data = CacheApi::quickGet('calendar_index', 'Actions/Calendar.php', 'SMF\\Actions\\Calendar::cache_getOffsetIndependentEvents', [$eventOptions]);
// Get the information about today (from user perspective).
$today = self::getTodayInfo();
- $return_data = array(
- 'calendar_holidays' => array(),
- 'calendar_birthdays' => array(),
- 'calendar_events' => array(),
- );
+ $return_data = [
+ 'calendar_holidays' => [],
+ 'calendar_birthdays' => [],
+ 'calendar_events' => [],
+ ];
// Set the event span to be shown in seconds.
$days_for_index = $eventOptions['num_days_shown'] * 86400;
@@ -1498,57 +1514,54 @@ public static function cache_getRecentEvents($eventOptions): array
// Get the current member time/date.
$now = time();
- if (!empty($eventOptions['include_holidays']))
- {
+ if (!empty($eventOptions['include_holidays'])) {
// Holidays between now and now + days.
- for ($i = $now; $i < $now + $days_for_index; $i += 86400)
- {
- if (isset($cached_data['holidays'][Time::strftime('%Y-%m-%d', $i)]))
+ for ($i = $now; $i < $now + $days_for_index; $i += 86400) {
+ if (isset($cached_data['holidays'][Time::strftime('%Y-%m-%d', $i)])) {
$return_data['calendar_holidays'] = array_merge($return_data['calendar_holidays'], $cached_data['holidays'][Time::strftime('%Y-%m-%d', $i)]);
+ }
}
}
- if (!empty($eventOptions['include_birthdays']))
- {
+ if (!empty($eventOptions['include_birthdays'])) {
// Happy Birthday, guys and gals!
- for ($i = $now; $i < $now + $days_for_index; $i += 86400)
- {
+ for ($i = $now; $i < $now + $days_for_index; $i += 86400) {
$loop_date = Time::strftime('%Y-%m-%d', $i);
- if (isset($cached_data['birthdays'][$loop_date]))
- {
- foreach ($cached_data['birthdays'][$loop_date] as $index => $dummy)
+
+ if (isset($cached_data['birthdays'][$loop_date])) {
+ foreach ($cached_data['birthdays'][$loop_date] as $index => $dummy) {
$cached_data['birthdays'][Time::strftime('%Y-%m-%d', $i)][$index]['is_today'] = $loop_date === $today['date'];
+ }
$return_data['calendar_birthdays'] = array_merge($return_data['calendar_birthdays'], $cached_data['birthdays'][$loop_date]);
}
}
}
- if (!empty($eventOptions['include_events']))
- {
- $duplicates = array();
- for ($i = $now; $i < $now + $days_for_index; $i += 86400)
- {
+ if (!empty($eventOptions['include_events'])) {
+ $duplicates = [];
+
+ for ($i = $now; $i < $now + $days_for_index; $i += 86400) {
// Determine the date of the current loop step.
$loop_date = Time::strftime('%Y-%m-%d', $i);
// No events today? Check the next day.
- if (empty($cached_data['events'][$loop_date]))
+ if (empty($cached_data['events'][$loop_date])) {
continue;
+ }
// Loop through all events to add a few last-minute values.
- foreach ($cached_data['events'][$loop_date] as $ev => $event)
- {
+ foreach ($cached_data['events'][$loop_date] as $ev => $event) {
// Create a shortcut variable for easier access.
$this_event = &$cached_data['events'][$loop_date][$ev];
// Skip duplicates.
- if (isset($duplicates[$this_event['topic'] . $this_event['title']]))
- {
+ if (isset($duplicates[$this_event['topic'] . $this_event['title']])) {
unset($cached_data['events'][$loop_date][$ev]);
+
continue;
}
- else
- $duplicates[$this_event['topic'] . $this_event['title']] = true;
+
+ $duplicates[$this_event['topic'] . $this_event['title']] = true;
// Might be set to true afterwards, depending on the permissions.
$this_event['can_edit'] = false;
@@ -1556,35 +1569,39 @@ public static function cache_getRecentEvents($eventOptions): array
$this_event['date'] = $loop_date;
}
- if (!empty($cached_data['events'][$loop_date]))
+ if (!empty($cached_data['events'][$loop_date])) {
$return_data['calendar_events'] = array_merge($return_data['calendar_events'], $cached_data['events'][$loop_date]);
+ }
}
}
// Mark the last item so that a list separator can be used in the template.
- for ($i = 0, $n = count($return_data['calendar_birthdays']); $i < $n; $i++)
+ for ($i = 0, $n = count($return_data['calendar_birthdays']); $i < $n; $i++) {
$return_data['calendar_birthdays'][$i]['is_last'] = !isset($return_data['calendar_birthdays'][$i + 1]);
- for ($i = 0, $n = count($return_data['calendar_events']); $i < $n; $i++)
+ }
+
+ for ($i = 0, $n = count($return_data['calendar_events']); $i < $n; $i++) {
$return_data['calendar_events'][$i]['is_last'] = !isset($return_data['calendar_events'][$i + 1]);
+ }
- return array(
+ return [
'data' => $return_data,
'expires' => time() + 3600,
- 'refresh_eval' => 'return \'' . Time::strftime('%Y%m%d', time()) . '\' != \SMF\Time::strftime(\'%Y%m%d\', time()) || (!empty(\SMF\Config::$modSettings[\'calendar_updated\']) && ' . time() . ' < \SMF\Config::$modSettings[\'calendar_updated\']);',
+ 'refresh_eval' => 'return \'' . Time::strftime('%Y%m%d', time()) . '\' != \\SMF\\Time::strftime(\'%Y%m%d\', time()) || (!empty(\\SMF\\Config::$modSettings[\'calendar_updated\']) && ' . time() . ' < \\SMF\\Config::$modSettings[\'calendar_updated\']);',
'post_retri_eval' => '
foreach ($cache_block[\'data\'][\'calendar_events\'] as $k => $event)
{
// Remove events that the user may not see or wants to ignore.
- if ((count(array_intersect(\SMF\User::$me->groups, $event[\'allowed_groups\'])) === 0 && !\SMF\User::$me->allowedTo(\'admin_forum\') && !empty($event[\'id_board\'])) || in_array($event[\'id_board\'], \SMF\User::$me->ignoreboards))
+ if ((count(array_intersect(\\SMF\\User::$me->groups, $event[\'allowed_groups\'])) === 0 && !\\SMF\\User::$me->allowedTo(\'admin_forum\') && !empty($event[\'id_board\'])) || in_array($event[\'id_board\'], \\SMF\\User::$me->ignoreboards))
unset($cache_block[\'data\'][\'calendar_events\'][$k]);
else
{
// Whether the event can be edited depends on the permissions.
- $cache_block[\'data\'][\'calendar_events\'][$k][\'can_edit\'] = \SMF\User::$me->allowedTo(\'calendar_edit_any\') || ($event[\'poster\'] == \SMF\User::$me->id && \SMF\User::$me->allowedTo(\'calendar_edit_own\'));
+ $cache_block[\'data\'][\'calendar_events\'][$k][\'can_edit\'] = \\SMF\\User::$me->allowedTo(\'calendar_edit_any\') || ($event[\'poster\'] == \\SMF\\User::$me->id && \\SMF\\User::$me->allowedTo(\'calendar_edit_own\'));
// The added session code makes this URL not cachable.
- $cache_block[\'data\'][\'calendar_events\'][$k][\'modify_href\'] = \SMF\Config::$scripturl . \'?action=\' . ($event[\'topic\'] == 0 ? \'calendar;sa=post;\' : \'post;msg=\' . $event[\'msg\'] . \';topic=\' . $event[\'topic\'] . \'.0;calendar;\') . \'eventid=\' . $event[\'id\'] . \';\' . \SMF\Utils::$context[\'session_var\'] . \'=\' . \SMF\Utils::$context[\'session_id\'];
+ $cache_block[\'data\'][\'calendar_events\'][$k][\'modify_href\'] = \\SMF\\Config::$scripturl . \'?action=\' . ($event[\'topic\'] == 0 ? \'calendar;sa=post;\' : \'post;msg=\' . $event[\'msg\'] . \';topic=\' . $event[\'topic\'] . \'.0;calendar;\') . \'eventid=\' . $event[\'id\'] . \';\' . \\SMF\\Utils::$context[\'session_var\'] . \'=\' . \\SMF\\Utils::$context[\'session_id\'];
}
}
@@ -1596,7 +1613,7 @@ public static function cache_getRecentEvents($eventOptions): array
$cache_block[\'data\'][\'calendar_events\'] = array();
$cache_block[\'data\'][\'show_calendar\'] = !empty($cache_block[\'data\'][\'calendar_holidays\']) || !empty($cache_block[\'data\'][\'calendar_birthdays\']) || !empty($cache_block[\'data\'][\'calendar_events\']);',
- );
+ ];
}
/**
@@ -1604,51 +1621,54 @@ public static function cache_getRecentEvents($eventOptions): array
*/
public static function validateEventPost(): void
{
- if (!isset($_POST['deleteevent']))
- {
+ if (!isset($_POST['deleteevent'])) {
// The 2.1 way
- if (isset($_POST['start_date']))
- {
+ if (isset($_POST['start_date'])) {
$d = date_parse(str_replace(',', '', self::convertDateToEnglish($_POST['start_date'])));
- if (!empty($d['error_count']) || !empty($d['warning_count']))
+ if (!empty($d['error_count']) || !empty($d['warning_count'])) {
ErrorHandler::fatalLang('invalid_date', false);
+ }
- if (empty($d['year']))
+ if (empty($d['year'])) {
ErrorHandler::fatalLang('event_year_missing', false);
+ }
- if (empty($d['month']))
+ if (empty($d['month'])) {
ErrorHandler::fatalLang('event_month_missing', false);
- }
- elseif (isset($_POST['start_datetime']))
- {
+ }
+ } elseif (isset($_POST['start_datetime'])) {
$d = date_parse(str_replace(',', '', self::convertDateToEnglish($_POST['start_datetime'])));
- if (!empty($d['error_count']) || !empty($d['warning_count']))
+ if (!empty($d['error_count']) || !empty($d['warning_count'])) {
ErrorHandler::fatalLang('invalid_date', false);
+ }
- if (empty($d['year']))
+ if (empty($d['year'])) {
ErrorHandler::fatalLang('event_year_missing', false);
+ }
- if (empty($d['month']))
+ if (empty($d['month'])) {
ErrorHandler::fatalLang('event_month_missing', false);
+ }
}
// The 2.0 way
- else
- {
+ else {
// No month? No year?
- if (!isset($_POST['month']))
+ if (!isset($_POST['month'])) {
ErrorHandler::fatalLang('event_month_missing', false);
+ }
- if (!isset($_POST['year']))
+ if (!isset($_POST['year'])) {
ErrorHandler::fatalLang('event_year_missing', false);
+ }
// Check the month and year...
- if ($_POST['month'] < 1 || $_POST['month'] > 12)
+ if ($_POST['month'] < 1 || $_POST['month'] > 12) {
ErrorHandler::fatalLang('invalid_month', false);
+ }
- if ($_POST['year'] < Config::$modSettings['cal_minyear'] || $_POST['year'] > Config::$modSettings['cal_maxyear'])
- {
+ if ($_POST['year'] < Config::$modSettings['cal_minyear'] || $_POST['year'] > Config::$modSettings['cal_maxyear']) {
ErrorHandler::fatalLang('invalid_year', false);
}
}
@@ -1658,40 +1678,41 @@ public static function validateEventPost(): void
User::$me->isAllowedTo('calendar_post');
// If they want to us to calculate an end date, make sure it will fit in an acceptable range.
- if (isset($_POST['span']) && (($_POST['span'] < 1) || (!empty(Config::$modSettings['cal_maxspan']) && $_POST['span'] > Config::$modSettings['cal_maxspan'])))
- {
+ if (isset($_POST['span']) && (($_POST['span'] < 1) || (!empty(Config::$modSettings['cal_maxspan']) && $_POST['span'] > Config::$modSettings['cal_maxspan']))) {
ErrorHandler::fatalLang('invalid_days_numb', false);
}
// There is no need to validate the following values if we are just deleting the event.
- if (!isset($_POST['deleteevent']))
- {
+ if (!isset($_POST['deleteevent'])) {
// If we're doing things the 2.0 way, check the day
- if (empty($_POST['start_date']) && empty($_POST['start_datetime']))
- {
+ if (empty($_POST['start_date']) && empty($_POST['start_datetime'])) {
// No day?
- if (!isset($_POST['day']))
+ if (!isset($_POST['day'])) {
ErrorHandler::fatalLang('event_day_missing', false);
+ }
// Bad day?
- if (!checkdate($_POST['month'], $_POST['day'], $_POST['year']))
+ if (!checkdate($_POST['month'], $_POST['day'], $_POST['year'])) {
ErrorHandler::fatalLang('invalid_date', false);
+ }
}
- if (!isset($_POST['evtitle']))
- {
- if (!isset($_POST['subject']))
+ if (!isset($_POST['evtitle'])) {
+ if (!isset($_POST['subject'])) {
ErrorHandler::fatalLang('event_title_missing', false);
+ }
$_POST['evtitle'] = $_POST['subject'];
}
// No title?
- if (Utils::htmlTrim($_POST['evtitle']) === '')
+ if (Utils::htmlTrim($_POST['evtitle']) === '') {
ErrorHandler::fatalLang('event_title_missing', false);
+ }
- if (Utils::entityStrlen($_POST['evtitle']) > 100)
+ if (Utils::entityStrlen($_POST['evtitle']) > 100) {
$_POST['evtitle'] = Utils::entitySubstr($_POST['evtitle'], 0, 100);
+ }
$_POST['evtitle'] = str_replace(';', '', $_POST['evtitle']);
}
@@ -1706,23 +1727,26 @@ public static function validateEventPost(): void
public static function getEventPoster($event_id): int|bool
{
// A simple database query, how hard can that be?
- $request = Db::$db->query('', '
- SELECT id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}calendar
WHERE id_event = {int:id_event}
LIMIT 1',
- array(
+ [
'id_event' => $event_id,
- )
+ ],
);
// No results, return false.
- if (Db::$db->num_rows($request) === 0)
+ if (Db::$db->num_rows($request) === 0) {
return false;
+ }
// Grab the results and return.
- list ($poster) = Db::$db->fetch_row($request);
+ list($poster) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
+
return (int) $poster;
}
@@ -1736,20 +1760,23 @@ public static function getEventPoster($event_id): int|bool
*/
public static function list_getHolidays($start, $items_per_page, $sort): array
{
- $request = Db::$db->query('', '
- SELECT id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
+ $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
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array(
+ [
'sort' => $sort,
'start' => $start,
'max' => $items_per_page,
- )
+ ],
);
- $holidays = array();
- while ($row = Db::$db->fetch_assoc($request))
+ $holidays = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$holidays[] = $row;
+ }
Db::$db->free_result($request);
return $holidays;
@@ -1762,11 +1789,12 @@ public static function list_getHolidays($start, $items_per_page, $sort): array
*/
public static function list_getNumHolidays(): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}calendar_holidays',
- array(
- )
+ [
+ ],
);
list($num_items) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -1781,17 +1809,18 @@ public static function list_getNumHolidays(): int
*/
public static function removeHolidays($holiday_ids): void
{
- Db::$db->query('', '
- DELETE FROM {db_prefix}calendar_holidays
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}calendar_holidays
WHERE id_holiday IN ({array_int:id_holiday})',
- array(
+ [
'id_holiday' => $holiday_ids,
- )
+ ],
);
- Config::updateModSettings(array(
+ Config::updateModSettings([
'calendar_updated' => time(),
- ));
+ ]);
}
/**
@@ -1803,33 +1832,34 @@ public static function removeHolidays($holiday_ids): void
*/
public static function convertDateToEnglish($date): string
{
- if (User::$me->language == 'english')
+ if (User::$me->language == 'english') {
return $date;
+ }
- $replacements = array_combine(array_map('strtolower', Lang::$txt['months_titles']), array(
+ $replacements = array_combine(array_map('strtolower', Lang::$txt['months_titles']), [
'January', 'February', 'March', 'April', 'May', 'June',
- 'July', 'August', 'September', 'October', 'November', 'December'
- ));
- $replacements += array_combine(array_map('strtolower', Lang::$txt['months_short']), array(
+ 'July', 'August', 'September', 'October', 'November', 'December',
+ ]);
+ $replacements += array_combine(array_map('strtolower', Lang::$txt['months_short']), [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
- ));
- $replacements += array_combine(array_map('strtolower', Lang::$txt['days']), array(
- 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
- ));
- $replacements += array_combine(array_map('strtolower', Lang::$txt['days_short']), array(
- 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
- ));
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
+ ]);
+ $replacements += array_combine(array_map('strtolower', Lang::$txt['days']), [
+ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
+ ]);
+ $replacements += array_combine(array_map('strtolower', Lang::$txt['days_short']), [
+ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
+ ]);
// Find all possible variants of AM and PM for this language.
$replacements[strtolower(Lang::$txt['time_am'])] = 'AM';
$replacements[strtolower(Lang::$txt['time_pm'])] = 'PM';
- if (($am = Time::strftime('%p', strtotime('01:00:00'))) !== 'p' && $am !== false)
- {
+
+ if (($am = Time::strftime('%p', strtotime('01:00:00'))) !== 'p' && $am !== false) {
$replacements[strtolower($am)] = 'AM';
$replacements[strtolower(Time::strftime('%p', strtotime('23:00:00')))] = 'PM';
}
- if (($am = Time::strftime('%P', strtotime('01:00:00'))) !== 'P' && $am !== false)
- {
+
+ if (($am = Time::strftime('%P', strtotime('01:00:00'))) !== 'P' && $am !== false) {
$replacements[strtolower($am)] = 'AM';
$replacements[strtolower(Time::strftime('%P', strtotime('23:00:00')))] = 'PM';
}
@@ -1846,27 +1876,30 @@ public static function convertDateToEnglish($date): string
*/
protected function __construct()
{
- if ($_GET['action'] === 'clock')
+ if ($_GET['action'] === 'clock') {
$this->subaction = 'clock';
- elseif (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
+ } elseif (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
+ }
- if ($this->subaction === 'clock')
+ if ($this->subaction === 'clock') {
return;
+ }
// Permissions, permissions, permissions.
User::$me->isAllowedTo('calendar_view');
// Some global template resources.
- Utils::$context['calendar_resources'] = array(
+ Utils::$context['calendar_resources'] = [
'min_year' => Config::$modSettings['cal_minyear'],
'max_year' => Config::$modSettings['cal_maxyear'],
- );
+ ];
}
}
// 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/CoppaForm.php b/Sources/Actions/CoppaForm.php
index da1a851407..874652b2d5 100644
--- a/Sources/Actions/CoppaForm.php
+++ b/Sources/Actions/CoppaForm.php
@@ -14,14 +14,13 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\BrowserDetector;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Theme;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Displays the COPPA form during registration.
@@ -35,12 +34,11 @@ class CoppaForm implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'CoppaForm',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -64,48 +62,46 @@ class CoppaForm implements ActionInterface
public function execute(): void
{
// Get the user details...
- $request = Db::$db->query('', '
- SELECT member_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT member_name
FROM {db_prefix}members
WHERE id_member = {int:id_member}
AND is_activated = {int:is_coppa}',
- array(
+ [
'id_member' => (int) $_GET['member'],
'is_coppa' => 5,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
Db::$db->free_result($request);
ErrorHandler::fatalLang('no_access', false);
}
list($username) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- if (isset($_GET['form']))
- {
+ if (isset($_GET['form'])) {
// Some simple contact stuff for the forum.
Utils::$context['forum_contacts'] = (!empty(Config::$modSettings['coppaPost']) ? Config::$modSettings['coppaPost'] . '
' : '') . (!empty(Config::$modSettings['coppaFax']) ? Config::$modSettings['coppaFax'] . ' ' : '');
Utils::$context['forum_contacts'] = !empty(Utils::$context['forum_contacts']) ? Utils::$context['forum_name_html_safe'] . ' ' . Utils::$context['forum_contacts'] : '';
// Showing template?
- if (!isset($_GET['dl']))
- {
+ if (!isset($_GET['dl'])) {
// Shortcut for producing underlines.
Utils::$context['ul'] = ' ';
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
Utils::$context['sub_template'] = 'coppa_form';
Utils::$context['page_title'] = sprintf(Lang::$txt['coppa_form_title'], Utils::$context['forum_name_html_safe']);
- Utils::$context['coppa_body'] = str_replace(array('{PARENT_NAME}', '{CHILD_NAME}', '{USER_NAME}'), array(Utils::$context['ul'], Utils::$context['ul'], $username), sprintf(Lang::$txt['coppa_form_body'], Utils::$context['forum_name_html_safe']));
+ Utils::$context['coppa_body'] = str_replace(['{PARENT_NAME}', '{CHILD_NAME}', '{USER_NAME}'], [Utils::$context['ul'], Utils::$context['ul'], $username], sprintf(Lang::$txt['coppa_form_body'], Utils::$context['forum_name_html_safe']));
}
// Downloading.
- else
- {
+ else {
// The data.
$ul = ' ';
$crlf = "\r\n";
$data = Utils::$context['forum_contacts'] . $crlf . Lang::$txt['coppa_form_address'] . ':' . $crlf . Lang::$txt['coppa_form_date'] . ':' . $crlf . $crlf . $crlf . sprintf(Lang::$txt['coppa_form_body'], Utils::$context['forum_name_html_safe']);
- $data = str_replace(array('{PARENT_NAME}', '{CHILD_NAME}', '{USER_NAME}', ' ', ' '), array($ul, $ul, $username, $crlf, $crlf), $data);
+ $data = str_replace(['{PARENT_NAME}', '{CHILD_NAME}', '{USER_NAME}', ' ', ' '], [$ul, $ul, $username, $crlf, $crlf], $data);
// Send the headers.
header('connection: close');
@@ -116,22 +112,20 @@ public function execute(): void
echo $data;
Utils::obExit(false);
}
- }
- else
- {
- Utils::$context += array(
+ } else {
+ Utils::$context += [
'page_title' => Lang::$txt['coppa_title'],
'sub_template' => 'coppa',
- );
+ ];
- Utils::$context['coppa'] = array(
+ Utils::$context['coppa'] = [
'body' => str_replace('{MINIMUM_AGE}', Config::$modSettings['coppaAge'], sprintf(Lang::$txt['coppa_after_registration'], Utils::$context['forum_name_html_safe'])),
'many_options' => !empty(Config::$modSettings['coppaPost']) && !empty(Config::$modSettings['coppaFax']),
'post' => empty(Config::$modSettings['coppaPost']) ? '' : Config::$modSettings['coppaPost'],
'fax' => empty(Config::$modSettings['coppaFax']) ? '' : Config::$modSettings['coppaFax'],
'phone' => empty(Config::$modSettings['coppaPhone']) ? '' : str_replace('{PHONE_NUMBER}', Config::$modSettings['coppaPhone'], Lang::$txt['coppa_send_by_phone']),
'id' => $_GET['member'],
- );
+ ];
}
}
@@ -146,8 +140,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;
}
@@ -173,13 +168,15 @@ protected function __construct()
Theme::loadTemplate('Register');
// No User ID??
- if (!isset($_GET['member']))
+ if (!isset($_GET['member'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\CoppaForm::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\CoppaForm::exportStatic')) {
CoppaForm::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Credits.php b/Sources/Actions/Credits.php
index 59eb690dea..a83067b87a 100644
--- a/Sources/Actions/Credits.php
+++ b/Sources/Actions/Credits.php
@@ -14,16 +14,15 @@
namespace SMF\Actions;
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;
/**
* This action prepares credit and copyright information for the credits page
@@ -38,12 +37,11 @@ class Credits implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'Credits',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -80,33 +78,32 @@ public function execute(): void
// Discourage robots from indexing this page.
Utils::$context['robot_no_index'] = true;
- if ($this->in_admin)
- {
- Menu::$loaded['admin']->tab_data = array(
+ if ($this->in_admin) {
+ Menu::$loaded['admin']->tab_data = [
'title' => Lang::$txt['support_credits_title'],
'help' => '',
'description' => '',
- );
+ ];
}
- Utils::$context['credits'] = array(
- array(
+ Utils::$context['credits'] = [
+ [
'pretext' => Lang::$txt['credits_intro'],
'title' => Lang::$txt['credits_team'],
- 'groups' => array(
- array(
+ 'groups' => [
+ [
'title' => Lang::$txt['credits_groups_pm'],
- 'members' => array(
+ 'members' => [
'Aleksi "Lex" Kilpinen',
// Former Project Managers
'Michele "Illori" Davis',
'Jessica "Suki" González',
'Will "Kindred" Wagner',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_dev'],
- 'members' => array(
+ 'members' => [
// Lead Developer
'Shawn Bulen',
// Developers
@@ -138,11 +135,11 @@ public function execute(): void
'Theodore "Orstio" Hildebrandt',
'Thorsten "TE" Eurich',
'winrules',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_support'],
- 'members' => array(
+ 'members' => [
// Lead Support Specialist
'Will "Kindred" Wagner',
// Support Specialists
@@ -176,11 +173,11 @@ public function execute(): void
'Storman™',
'Wade "sησω" Poulsen',
'xenovanis',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_customize'],
- 'members' => array(
+ 'members' => [
// Lead Customizer
'Diego Andrés',
// Customizers
@@ -201,11 +198,11 @@ public function execute(): void
'Ricky.',
'Russell "NEND" Najar',
'SA™',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_docs'],
- 'members' => array(
+ 'members' => [
// Doc Coordinator
'Michele "Illori" Davis',
// Doc Writers
@@ -216,11 +213,11 @@ public function execute(): void
'Chainy',
'Graeme Spence',
'Joshua "groundup" Dickerson',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_internationalizers'],
- 'members' => array(
+ 'members' => [
// Lead Localizer
'Nikola "Dzonny" Novaković',
// Localizers
@@ -229,11 +226,11 @@ public function execute(): void
'Francisco "d3vcho" Domínguez',
'Robert Monden',
'Relyana',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_marketing'],
- 'members' => array(
+ 'members' => [
// Marketing Coordinator
// Marketing
@@ -243,105 +240,103 @@ public function execute(): void
'Bryan "Runic" Deakin',
'Marcus "cσσкιє мσηѕтєя" Forsberg',
'Ralph "[n3rve]" Otowo',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_site'],
- 'members' => array(
+ 'members' => [
'Jeremy "SleePy" Darwood',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_servers'],
- 'members' => array(
+ 'members' => [
'Derek Schwab',
'Michael Johnson',
'Liroy van Hoewijk',
- ),
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ],
+ ];
// Give the translators some credit for their hard work.
- if (!is_array(Lang::$txt['translation_credits']))
- {
+ if (!is_array(Lang::$txt['translation_credits'])) {
Lang::$txt['translation_credits'] = array_filter(array_map('trim', explode(',', Lang::$txt['translation_credits'])));
}
- if (!empty(Lang::$txt['translation_credits']))
- {
- Utils::$context['credits'][] = array(
+ if (!empty(Lang::$txt['translation_credits'])) {
+ Utils::$context['credits'][] = [
'title' => Lang::$txt['credits_groups_translation'],
- 'groups' => array(
- array(
+ 'groups' => [
+ [
'title' => Lang::$txt['credits_groups_translation'],
'members' => Lang::$txt['translation_credits'],
- ),
- ),
- );
+ ],
+ ],
+ ];
}
- Utils::$context['credits'][] = array(
+ Utils::$context['credits'][] = [
'title' => Lang::$txt['credits_special'],
'posttext' => Lang::$txt['credits_anyone'],
- 'groups' => array(
- array(
+ 'groups' => [
+ [
'title' => Lang::$txt['credits_groups_consultants'],
- 'members' => array(
+ 'members' => [
'albertlast',
'Brett Flannigan',
'Mark Rose',
'René-Gilles "Nao 尚" Deberdt',
'tinoest',
Lang::$txt['credits_code_contributors'],
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_beta'],
- 'members' => array(
+ 'members' => [
Lang::$txt['credits_beta_message'],
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_translators'],
- 'members' => array(
+ 'members' => [
Lang::$txt['credits_translators_message'],
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_founder'],
- 'members' => array(
+ 'members' => [
'Unknown W. "[Unknown]" Brackets',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_groups_orignal_pm'],
- 'members' => array(
+ 'members' => [
'Jeff Lewis',
'Joseph Fung',
'David Recordon',
- ),
- ),
- array(
+ ],
+ ],
+ [
'title' => Lang::$txt['credits_in_memoriam'],
- 'members' => array(
+ 'members' => [
'Crip',
'K@',
'metallica48423',
'Paul_Pauline',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
// Give credit to any graphic library's, software library's, plugins etc
- Utils::$context['credits_software_graphics'] = array(
- 'graphics' => array(
+ Utils::$context['credits_software_graphics'] = [
+ 'graphics' => [
'Fugue Icons | © 2012 Yusuke Kamiyamane | These icons are licensed under a Creative Commons Attribution 3.0 License',
'Oxygen Icons | These icons are licensed under GNU LGPLv3',
- ),
- 'software' => array(
+ ],
+ 'software' => [
'JQuery | © John Resig | Licensed under The MIT License (MIT)',
'hoverIntent | © Brian Cherne | Licensed under The MIT License (MIT)',
'SCEditor | © Sam Clarke | Licensed under The MIT License (MIT)',
@@ -354,35 +349,35 @@ public function execute(): void
'Dropzone.js | © Matias Meno | Licensed under The MIT License (MIT)',
'Minify | © Matthias Mullie | Licensed under The MIT License (MIT)',
'PHP-Punycode | © True B.V. | Licensed under The MIT License (MIT)',
- ),
- 'fonts' => array(
+ ],
+ 'fonts' => [
' Anonymous Pro | © 2009 | This font is licensed under the SIL Open Font License, Version 1.1',
' ConsolaMono | © 2012 | This font is licensed under the SIL Open Font License, Version 1.1',
' Phennig | © 2009-2012 | This font is licensed under the SIL Open Font License, Version 1.1',
- ),
- );
+ ],
+ ];
// Support for mods that use the tag via the package manager
- Utils::$context['credits_modifications'] = array();
+ Utils::$context['credits_modifications'] = [];
- if (($mods = CacheApi::get('mods_credits', 86400)) === null)
- {
- $mods = array();
+ if (($mods = CacheApi::get('mods_credits', 86400)) === null) {
+ $mods = [];
- $request = Db::$db->query('substring', '
- SELECT version, name, credits
+ $request = Db::$db->query(
+ 'substring',
+ 'SELECT version, name, credits
FROM {db_prefix}log_packages
WHERE install_state = {int:installed_mods}
AND credits != {string:empty}
AND SUBSTRING(filename, 1, 9) != {string:patch_name}',
- array(
+ [
'installed_mods' => 1,
'patch_name' => 'smf_patch',
'empty' => '',
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$credit_info = Utils::jsonDecode($row['credits'], true);
$copyright = empty($credit_info['copyright']) ? '' : Lang::$txt['credits_copyright'] . ' © ' . Utils::htmlspecialchars($credit_info['copyright']);
@@ -403,22 +398,21 @@ public function execute(): void
Utils::$context['credits_modifications'] = $mods;
- Utils::$context['copyrights'] = array(
+ Utils::$context['copyrights'] = [
'smf' => sprintf(Lang::$forum_copyright, SMF_FULL_VERSION, SMF_SOFTWARE_YEAR, Config::$scripturl),
/* Modification Authors: You may add a copyright statement to this array for your mods.
Copyright statements should be in the form of a value only without a array key. I.E.:
'Some Mod by Thantos © 2010',
Lang::$txt['some_mod_copyright'],
*/
- 'mods' => array(
- ),
- );
+ 'mods' => [
+ ],
+ ];
// Support for those that want to use a hook as well
IntegrationHook::call('integrate_credits');
- if (!$this->in_admin)
- {
+ if (!$this->in_admin) {
Theme::loadTemplate('Who');
Utils::$context['sub_template'] = 'credits';
Utils::$context['robot_no_index'] = true;
@@ -437,8 +431,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;
}
@@ -470,7 +465,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Credits::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Credits::exportStatic')) {
Credits::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Display.php b/Sources/Actions/Display.php
index be59159e64..a13630554f 100644
--- a/Sources/Actions/Display.php
+++ b/Sources/Actions/Display.php
@@ -13,12 +13,13 @@
namespace SMF\Actions;
-use SMF\BackwardCompatibility;
-
use SMF\Alert;
use SMF\Attachment;
+use SMF\BackwardCompatibility;
use SMF\Board;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\Editor;
use SMF\ErrorHandler;
use SMF\Event;
@@ -33,8 +34,6 @@
use SMF\User;
use SMF\Utils;
use SMF\Verifier;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* This class loads the posts in a topic so they can be displayed.
@@ -58,12 +57,11 @@ class Display implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static array $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static array $backcompat = [
+ 'func_names' => [
'call' => 'Display',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -85,14 +83,14 @@ class Display implements ActionInterface
*
* ID numbers of messages in this topic.
*/
- private $messages = array();
+ private $messages = [];
/**
* @var array
*
* ID numbers of the authors of the $messages.
*/
- private $posters = array();
+ private $posters = [];
/**
* @var int
@@ -171,122 +169,124 @@ public function prepareDisplayContext()
static $counter = null;
// Remember which message this is. (ie. reply #83)
- if ($counter === null)
- {
+ if ($counter === null) {
$counter = empty(Theme::$current->options['view_newest_first']) ? Utils::$context['start'] : Topic::$info->total_visible_posts - Utils::$context['start'];
}
- if (!(Msg::$getter instanceof \Generator))
+ if (!(Msg::$getter instanceof \Generator)) {
return false;
+ }
$message = Msg::$getter->current();
Msg::$getter->next();
- if (!$message)
+ if (!$message) {
return false;
+ }
$output = $message->format($counter);
// Set up the quick buttons.
- $output['quickbuttons'] = array(
- 'quote' => array(
+ $output['quickbuttons'] = [
+ 'quote' => [
'label' => Lang::$txt['quote_action'],
'href' => Config::$scripturl . '?action=post;quote=' . $output['id'] . ';topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';last_msg=' . Topic::$info->id_last_msg,
'javascript' => 'onclick="return oQuickReply.quote(' . $output['id'] . ');"',
'icon' => 'quote',
'show' => Utils::$context['can_quote'],
- ),
- 'quote_selected' => array(
+ ],
+ 'quote_selected' => [
'label' => Lang::$txt['quote_selected_action'],
'id' => 'quoteSelected_' . $output['id'],
'href' => 'javascript:void(0)',
'custom' => 'style="display:none"',
'icon' => 'quote_selected',
'show' => Utils::$context['can_quote'],
- ),
- 'quick_edit' => array(
+ ],
+ 'quick_edit' => [
'label' => Lang::$txt['quick_edit'],
'class' => 'quick_edit',
'id' => 'modify_button_' . $output['id'],
'custom' => 'onclick="oQuickModify.modifyMsg(\'' . $output['id'] . '\', \'' . !empty(Config::$modSettings['toggle_subject']) . '\')"',
'icon' => 'quick_edit_button',
'show' => $output['can_modify'],
- ),
- 'more' => array(
- 'modify' => array(
+ ],
+ 'more' => [
+ 'modify' => [
'label' => Lang::$txt['modify'],
'href' => Config::$scripturl . '?action=post;msg=' . $output['id'] . ';topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'],
'icon' => 'modify_button',
'show' => $output['can_modify'],
- ),
- 'remove_topic' => array(
+ ],
+ 'remove_topic' => [
'label' => Lang::$txt['remove_topic'],
'href' => Config::$scripturl . '?action=removetopic2;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'javascript' => 'data-confirm="' . Lang::$txt['are_sure_remove_topic'] . '"',
'class' => 'you_sure',
'icon' => 'remove_button',
'show' => Utils::$context['can_delete'] && (Topic::$info->id_first_msg == $output['id']),
- ),
- 'remove' => array(
+ ],
+ 'remove' => [
'label' => Lang::$txt['remove'],
'href' => Config::$scripturl . '?action=deletemsg;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';msg=' . $output['id'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'javascript' => 'data-confirm="' . Lang::$txt['remove_message_question'] . '"',
'class' => 'you_sure',
'icon' => 'remove_button',
'show' => $output['can_remove'] && (Topic::$info->id_first_msg != $output['id']),
- ),
- 'split' => array(
+ ],
+ 'split' => [
'label' => Lang::$txt['split'],
'href' => Config::$scripturl . '?action=splittopics;topic=' . Utils::$context['current_topic'] . '.0;at=' . $output['id'],
'icon' => 'split_button',
'show' => Utils::$context['can_split'] && !empty(Topic::$info->real_num_replies),
- ),
- 'report' => array(
+ ],
+ 'report' => [
'label' => Lang::$txt['report_to_mod'],
'href' => Config::$scripturl . '?action=reporttm;topic=' . Utils::$context['current_topic'] . '.' . $output['counter'] . ';msg=' . $output['id'],
'icon' => 'error',
'show' => Utils::$context['can_report_moderator'],
- ),
- 'warn' => array(
+ ],
+ 'warn' => [
'label' => Lang::$txt['issue_warning'],
'href' => Config::$scripturl . '?action=profile;area=issuewarning;u=' . $output['member']['id'] . ';msg=' . $output['id'],
'icon' => 'warn_button',
'show' => Utils::$context['can_issue_warning'] && !$output['is_message_author'] && !$output['member']['is_guest'],
- ),
- 'restore' => array(
+ ],
+ 'restore' => [
'label' => Lang::$txt['restore_message'],
'href' => Config::$scripturl . '?action=restoretopic;msgs=' . $output['id'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'icon' => 'restore_button',
'show' => Utils::$context['can_restore_msg'],
- ),
- 'approve' => array(
+ ],
+ 'approve' => [
'label' => Lang::$txt['approve'],
'href' => Config::$scripturl . '?action=moderate;area=postmod;sa=approve;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';msg=' . $output['id'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'icon' => 'approve_button',
'show' => $output['can_approve'],
- ),
- 'unapprove' => array(
+ ],
+ 'unapprove' => [
'label' => Lang::$txt['unapprove'],
'href' => Config::$scripturl . '?action=moderate;area=postmod;sa=approve;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';msg=' . $output['id'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'icon' => 'unapprove_button',
'show' => $output['can_unapprove'],
- ),
- ),
- 'quickmod' => array(
+ ],
+ ],
+ 'quickmod' => [
'class' => 'inline_mod_check',
'id' => 'in_topic_mod_check_' . $output['id'],
'custom' => 'style="display: none;"',
'content' => '',
'show' => !empty(Theme::$current->options['display_quick_mod']) && Theme::$current->options['display_quick_mod'] == 1 && $output['can_remove'],
- ),
- );
+ ],
+ ];
- if (empty(Theme::$current->options['view_newest_first']))
+ if (empty(Theme::$current->options['view_newest_first'])) {
$counter++;
- else
+ } else {
$counter--;
+ }
- IntegrationHook::call('integrate_prepare_display_context', array(&$output, $message, $counter));
+ IntegrationHook::call('integrate_prepare_display_context', [&$output, $message, $counter]);
return $output;
}
@@ -302,8 +302,9 @@ public function prepareDisplayContext()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -331,8 +332,9 @@ public static function call(): void
protected function __construct()
{
// What are you gonna display if this is empty?!
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
ErrorHandler::fatalLang('no_board', false);
+ }
$this->checkPrevNextRedirect();
$this->preventPrefetch();
@@ -351,8 +353,9 @@ protected function __construct()
$this->setUnapprovedPostsMessage();
// Now set all the wonderful, wonderful permissions... like moderation ones...
- foreach (Topic::$info->doPermissions() as $perm => $val)
+ foreach (Topic::$info->doPermissions() as $perm => $val) {
Utils::$context[$perm] = &Topic::$info->permissions[$perm];
+ }
$this->setupTemplate();
}
@@ -363,16 +366,16 @@ protected function __construct()
protected function checkPrevNextRedirect(): void
{
// Find the previous or next topic. But don't bother if there's only one.
- if (isset($_REQUEST['prev_next']) && in_array($_REQUEST['prev_next'], array('prev', 'next')) && Board::$info->num_topics > 1)
- {
+ if (isset($_REQUEST['prev_next']) && in_array($_REQUEST['prev_next'], ['prev', 'next']) && Board::$info->num_topics > 1) {
$prev = $_REQUEST['prev_next'] === 'prev';
// Just prepare some variables that are used in the query.
$gt_lt = $prev ? '>' : '<';
$order = $prev ? '' : ' DESC';
- $request = Db::$db->query('', '
- SELECT t2.id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT t2.id_topic
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}topics AS t2 ON (
(t2.id_last_msg ' . $gt_lt . ' t.id_last_msg AND t2.is_sticky ' . $gt_lt . '= t.is_sticky) OR t2.is_sticky ' . $gt_lt . ' t.is_sticky)
@@ -381,39 +384,39 @@ protected function checkPrevNextRedirect(): void
AND (t2.approved = {int:is_approved} OR (t2.id_member_started != {int:id_member_started} AND t2.id_member_started = {int:current_member}))') . '
ORDER BY t2.is_sticky' . $order . ', t2.id_last_msg' . $order . '
LIMIT 1',
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'current_topic' => Topic::$topic_id,
'is_approved' => 1,
'id_member_started' => 0,
- )
+ ],
);
// No more left.
- if (Db::$db->num_rows($request) == 0)
- {
+ if (Db::$db->num_rows($request) == 0) {
Db::$db->free_result($request);
// Roll over - if we're going prev, get the last - otherwise the first.
- $request = Db::$db->query('', '
- SELECT id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic
FROM {db_prefix}topics
WHERE id_board = {int:current_board}' . (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
AND (approved = {int:is_approved} OR (id_member_started != {int:id_member_started} AND id_member_started = {int:current_member}))') . '
ORDER BY is_sticky' . $order . ', id_last_msg' . $order . '
LIMIT 1',
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'is_approved' => 1,
'id_member_started' => 0,
- )
+ ],
);
}
// Now you can be sure Topic::$topic_id is the id_topic to view.
- list (Topic::$topic_id) = Db::$db->fetch_row($request);
+ list(Topic::$topic_id) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Go to the newest message on the prev/next topic.
@@ -426,20 +429,19 @@ protected function checkPrevNextRedirect(): void
*/
protected function checkMovedMergedRedirect(): void
{
- if (!empty(Topic::$info->id_redirect_topic))
- {
+ if (!empty(Topic::$info->id_redirect_topic)) {
// Mark this as read.
- if (!User::$me->is_guest && Topic::$info->new_from != Topic::$info->id_first_msg)
- {
- Db::$db->insert(Topic::$info->new_from == 0 ? 'ignore' : 'replace',
+ if (!User::$me->is_guest && Topic::$info->new_from != Topic::$info->id_first_msg) {
+ Db::$db->insert(
+ Topic::$info->new_from == 0 ? 'ignore' : 'replace',
'{db_prefix}log_topics',
- array(
+ [
'id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int',
- ),
- array(
+ ],
+ [
User::$me->id, Topic::$info->id, Topic::$info->id_first_msg, Topic::$info->unwatched,
- ),
- array('id_member', 'id_topic')
+ ],
+ ['id_member', 'id_topic'],
);
}
@@ -453,10 +455,10 @@ protected function checkMovedMergedRedirect(): void
protected function preventPrefetch(): void
{
// Not only does a prefetch make things slower for the server, but it makes it impossible to know if they read it.
- if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
- {
+ if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
ob_end_clean();
Utils::sendHttpStatus(403, 'Prefetch Forbidden');
+
die;
}
}
@@ -467,17 +469,17 @@ protected function preventPrefetch(): void
protected function setRobotNoIndex(): void
{
// Let's do some work on what to search index.
- if (count($_GET) > 2)
- {
- foreach ($_GET as $k => $v)
- {
- if (!in_array($k, array('topic', 'board', 'start', session_name())))
+ if (count($_GET) > 2) {
+ foreach ($_GET as $k => $v) {
+ if (!in_array($k, ['topic', 'board', 'start', session_name()])) {
Utils::$context['robot_no_index'] = true;
+ }
}
}
- if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % Utils::$context['messages_per_page'] != 0))
+ if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % Utils::$context['messages_per_page'] != 0)) {
Utils::$context['robot_no_index'] = true;
+ }
}
/**
@@ -485,15 +487,15 @@ protected function setRobotNoIndex(): void
*/
protected function incrementNumViews(): void
{
- if (!User::$me->possibly_robot && (empty($_SESSION['last_read_topic']) || $_SESSION['last_read_topic'] != Topic::$info->id))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ if (!User::$me->possibly_robot && (empty($_SESSION['last_read_topic']) || $_SESSION['last_read_topic'] != Topic::$info->id)) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET num_views = num_views + 1
WHERE id_topic = {int:current_topic}',
- array(
+ [
'current_topic' => Topic::$info->id,
- )
+ ],
);
$_SESSION['last_read_topic'] = Topic::$info->id;
@@ -506,75 +508,78 @@ protected function incrementNumViews(): void
protected function markRead(): void
{
// Guests can't mark topics read or for notifications, just can't sorry.
- if (!User::$me->is_guest && !empty($this->messages))
- {
+ if (!User::$me->is_guest && !empty($this->messages)) {
$mark_at_msg = max($this->messages);
- if ($mark_at_msg >= Topic::$info->id_last_msg)
+
+ if ($mark_at_msg >= Topic::$info->id_last_msg) {
$mark_at_msg = Config::$modSettings['maxMsgID'];
- if ($mark_at_msg >= Topic::$info->new_from)
- {
- Db::$db->insert(Topic::$info->new_from == 0 ? 'ignore' : 'replace',
+ }
+
+ if ($mark_at_msg >= Topic::$info->new_from) {
+ Db::$db->insert(
+ Topic::$info->new_from == 0 ? 'ignore' : 'replace',
'{db_prefix}log_topics',
- array(
+ [
'id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int',
- ),
- array(
+ ],
+ [
User::$me->id, Topic::$info->id, $mark_at_msg, Topic::$info->unwatched,
- ),
- array('id_member', 'id_topic')
+ ],
+ ['id_member', 'id_topic'],
);
}
// Check for notifications on this topic OR board.
- $request = Db::$db->query('', '
- SELECT sent, id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT sent, id_topic
FROM {db_prefix}log_notify
WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
AND id_member = {int:current_member}
LIMIT 2',
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'current_topic' => Topic::$info->id,
- )
+ ],
);
$do_once = true;
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Find if this topic is marked for notification...
- if (!empty($row['id_topic']))
+ if (!empty($row['id_topic'])) {
Utils::$context['is_marked_notify'] = true;
+ }
// Only do this once, but mark the notifications as "not sent yet" for next time.
- if (!empty($row['sent']) && $do_once)
- {
- Db::$db->query('', '
- UPDATE {db_prefix}log_notify
+ if (!empty($row['sent']) && $do_once) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_notify
SET sent = {int:is_not_sent}
WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
AND id_member = {int:current_member}',
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'current_topic' => Topic::$info->id,
'is_not_sent' => 0,
- )
+ ],
);
$do_once = false;
}
}
// Have we recently cached the number of new topics in this board, and it's still a lot?
- if (isset($_REQUEST['topicseen']) && isset($_SESSION['topicseen_cache'][Board::$info->id]) && $_SESSION['topicseen_cache'][Board::$info->id] > 5)
- {
+ if (isset($_REQUEST['topicseen'], $_SESSION['topicseen_cache'][Board::$info->id]) && $_SESSION['topicseen_cache'][Board::$info->id] > 5) {
$_SESSION['topicseen_cache'][Board::$info->id]--;
}
// Mark board as seen if this is the only new topic.
- elseif (isset($_REQUEST['topicseen']))
- {
+ elseif (isset($_REQUEST['topicseen'])) {
// Use the mark read tables... and the last visit to figure out if this should be read or not.
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}topics AS t
LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = {int:current_board} AND lb.id_member = {int:current_member})
LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
@@ -582,41 +587,42 @@ protected function markRead(): void
AND t.id_last_msg > COALESCE(lb.id_msg, 0)
AND t.id_last_msg > COALESCE(lt.id_msg, 0)' . (empty($_SESSION['id_msg_last_visit']) ? '' : '
AND t.id_last_msg > {int:id_msg_last_visit}'),
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'id_msg_last_visit' => (int) $_SESSION['id_msg_last_visit'],
- )
+ ],
);
- list ($numNewTopics) = Db::$db->fetch_row($request);
+ list($numNewTopics) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// If there're no real new topics in this board, mark the board as seen.
- if (empty($numNewTopics))
+ if (empty($numNewTopics)) {
$_REQUEST['boardseen'] = true;
- else
+ } else {
$_SESSION['topicseen_cache'][Board::$info->id] = $numNewTopics;
+ }
}
// Probably one less topic - maybe not, but even if we decrease this too fast it will only make us look more often.
- elseif (isset($_SESSION['topicseen_cache'][Board::$info->id]))
+ elseif (isset($_SESSION['topicseen_cache'][Board::$info->id])) {
$_SESSION['topicseen_cache'][Board::$info->id]--;
+ }
// Mark board as seen if we came using last post link from BoardIndex. (or other places...)
- if (isset($_REQUEST['boardseen']))
- {
- Db::$db->insert('replace',
+ if (isset($_REQUEST['boardseen'])) {
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_boards',
- array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
- array(Config::$modSettings['maxMsgID'], User::$me->id, Board::$info->id),
- array('id_member', 'id_board')
+ ['id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'],
+ [Config::$modSettings['maxMsgID'], User::$me->id, Board::$info->id],
+ ['id_member', 'id_board'],
);
}
// Mark any alerts about this topic or the posts on this page as read.
- if (!empty(User::$me->alerts))
- {
+ if (!empty(User::$me->alerts)) {
Alert::markWhere(
- array(
+ [
// Obviously, only for the current member.
'id_member = {int:current_member}',
@@ -635,13 +641,13 @@ protected function markRead(): void
')' .
')' .
')',
- ),
- array(
+ ],
+ [
'current_member' => User::$me->id,
'current_topic' => Topic::$info->id,
'messages' => $this->messages,
- ),
- true
+ ],
+ true,
);
}
}
@@ -666,34 +672,30 @@ protected function getNotificationMode(): void
protected function setStart(): void
{
// The start isn't a number; it's information about what to do, where to go.
- if (!is_numeric($_REQUEST['start']))
- {
+ if (!is_numeric($_REQUEST['start'])) {
// Redirect to the page and post with new messages, originally by Omar Bazavilvazo.
- if ($_REQUEST['start'] == 'new')
- {
+ if ($_REQUEST['start'] == 'new') {
// Guests automatically go to the last post.
- if (User::$me->is_guest)
- {
+ if (User::$me->is_guest) {
Utils::$context['start_from'] = Topic::$info->total_visible_posts - 1;
$_REQUEST['start'] = empty(Theme::$current->options['view_newest_first']) ? Utils::$context['start_from'] : 0;
- }
- else
- {
+ } else {
// Find the earliest unread message in the topic. (the use of topics here is just for both tables.)
- $request = Db::$db->query('', '
- SELECT COALESCE(lt.id_msg, lmr.id_msg, -1) + 1 AS new_from
+ $request = Db::$db->query(
+ '',
+ 'SELECT COALESCE(lt.id_msg, lmr.id_msg, -1) + 1 AS new_from
FROM {db_prefix}topics AS t
LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = {int:current_topic} AND lt.id_member = {int:current_member})
LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = {int:current_board} AND lmr.id_member = {int:current_member})
WHERE t.id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'current_topic' => Topic::$topic_id,
- )
+ ],
);
- list ($new_from) = Db::$db->fetch_row($request);
+ list($new_from) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Fall through to the next if statement.
@@ -702,28 +704,28 @@ protected function setStart(): void
}
// Start from a certain time index, not a message.
- if (substr($_REQUEST['start'], 0, 4) == 'from')
- {
+ if (substr($_REQUEST['start'], 0, 4) == 'from') {
$timestamp = (int) substr($_REQUEST['start'], 4);
- if ($timestamp === 0)
+
+ if ($timestamp === 0) {
$_REQUEST['start'] = 0;
- else
- {
+ } else {
// Find the number of messages posted before said time...
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}messages
WHERE poster_time < {int:timestamp}
AND id_topic = {int:current_topic}' . (Config::$modSettings['postmod_active'] && Topic::$info->unapproved_posts && !User::$me->allowedTo('approve_posts') ? '
AND (approved = {int:is_approved}' . (User::$me->is_guest ? '' : ' OR id_member = {int:current_member}') . ')' : ''),
- array(
+ [
'current_topic' => Topic::$topic_id,
'current_member' => User::$me->id,
'is_approved' => 1,
'timestamp' => $timestamp,
- )
+ ],
);
- list (Utils::$context['start_from']) = Db::$db->fetch_row($request);
+ list(Utils::$context['start_from']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Handle view_newest_first options, and get the correct start value.
@@ -732,31 +734,31 @@ protected function setStart(): void
}
// Link to a message...
- elseif (substr($_REQUEST['start'], 0, 3) == 'msg')
- {
+ elseif (substr($_REQUEST['start'], 0, 3) == 'msg') {
$this->virtual_msg = (int) substr($_REQUEST['start'], 3);
- if (!Topic::$info->unapproved_posts && $this->virtual_msg >= Topic::$info->id_last_msg)
+
+ if (!Topic::$info->unapproved_posts && $this->virtual_msg >= Topic::$info->id_last_msg) {
Utils::$context['start_from'] = Topic::$info->total_visible_posts - 1;
- elseif (!Topic::$info->unapproved_posts && $this->virtual_msg <= Topic::$info->id_first_msg)
+ } elseif (!Topic::$info->unapproved_posts && $this->virtual_msg <= Topic::$info->id_first_msg) {
Utils::$context['start_from'] = 0;
- else
- {
+ } else {
// Find the start value for that message......
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}messages
WHERE id_msg < {int:virtual_msg}
AND id_topic = {int:current_topic}' . (Config::$modSettings['postmod_active'] && Topic::$info->unapproved_posts && !User::$me->allowedTo('approve_posts') ? '
AND (approved = {int:is_approved}' . (User::$me->is_guest ? '' : ' OR id_member = {int:current_member}') . ')' : ''),
- array(
+ [
'current_member' => User::$me->id,
'current_topic' => Topic::$topic_id,
'virtual_msg' => $this->virtual_msg,
'is_approved' => 1,
'no_member' => 0,
- )
+ ],
);
- list (Utils::$context['start_from']) = Db::$db->fetch_row($request);
+ list(Utils::$context['start_from']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
}
@@ -771,50 +773,52 @@ protected function setStart(): void
*/
protected function getWhoViewing(): void
{
- if (!empty(Theme::$current->settings['display_who_viewing']))
- {
+ if (!empty(Theme::$current->settings['display_who_viewing'])) {
// Start out with no one at all viewing it.
- Utils::$context['view_members'] = array();
- Utils::$context['view_members_list'] = array();
+ Utils::$context['view_members'] = [];
+ Utils::$context['view_members_list'] = [];
Utils::$context['view_num_hidden'] = 0;
// Search for members who have this topic set in their GET data.
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
lo.id_member, lo.log_time, mem.real_name, mem.member_name, mem.show_online,
mg.online_color, mg.id_group, mg.group_name
FROM {db_prefix}log_online AS lo
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lo.id_member)
LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:reg_id_group} THEN mem.id_post_group ELSE mem.id_group END)
WHERE INSTR(lo.url, {string:in_url_string}) > 0 OR lo.session = {string:session}',
- array(
+ [
'reg_id_group' => 0,
'in_url_string' => '"topic":' . Topic::$info->id,
'session' => User::$me->is_guest ? 'ip' . User::$me->ip : session_id(),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (empty($row['id_member']))
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (empty($row['id_member'])) {
continue;
+ }
- if (!empty($row['online_color']))
+ if (!empty($row['online_color'])) {
$link = '' . $row['real_name'] . '';
- else
+ } else {
$link = '' . $row['real_name'] . '';
+ }
$is_buddy = in_array($row['id_member'], User::$me->buddies);
- if ($is_buddy)
+ if ($is_buddy) {
$link = '' . $link . '';
+ }
// Add them both to the list and to the more detailed list.
- if (!empty($row['show_online']) || User::$me->allowedTo('moderate_forum'))
- {
+ if (!empty($row['show_online']) || User::$me->allowedTo('moderate_forum')) {
Utils::$context['view_members_list'][$row['log_time'] . $row['member_name']] = empty($row['show_online']) ? '' . $link . '' : $link;
}
- Utils::$context['view_members'][$row['log_time'] . $row['member_name']] = array(
+ Utils::$context['view_members'][$row['log_time'] . $row['member_name']] = [
'id' => $row['id_member'],
'username' => $row['member_name'],
'name' => $row['real_name'],
@@ -823,10 +827,11 @@ protected function getWhoViewing(): void
'link' => $link,
'is_buddy' => $is_buddy,
'hidden' => empty($row['show_online']),
- );
+ ];
- if (empty($row['show_online']))
+ if (empty($row['show_online'])) {
Utils::$context['view_num_hidden']++;
+ }
}
// The number of guests is equal to the rows minus the ones we actually used ;).
@@ -853,11 +858,14 @@ protected function setPaginationAndLinks(): void
// If all is set, but not allowed... just unset it.
$this->can_show_all = !empty(Config::$modSettings['enableAllMessages']) && Topic::$info->total_visible_posts > Utils::$context['messages_per_page'] && Topic::$info->total_visible_posts < Config::$modSettings['enableAllMessages'];
- if (isset($_REQUEST['all']) && !$this->can_show_all)
+
+ if (isset($_REQUEST['all']) && !$this->can_show_all) {
unset($_REQUEST['all']);
+ }
// Otherwise, it must be allowed... so pretend start was -1.
- elseif (isset($_REQUEST['all']))
+ elseif (isset($_REQUEST['all'])) {
$_REQUEST['start'] = -1;
+ }
// Construct the page index, allowing for the .START method...
Utils::$context['page_index'] = new PageIndex(Config::$scripturl . '?topic=' . Topic::$info->id . '.%1$d', $_REQUEST['start'], Topic::$info->total_visible_posts, Utils::$context['messages_per_page'], true);
@@ -865,42 +873,37 @@ protected function setPaginationAndLinks(): void
Utils::$context['start'] = $_REQUEST['start'];
// This is information about which page is current, and which page we're on - in case you don't like the constructed page index. (again, wireless..)
- Utils::$context['page_info'] = array(
+ Utils::$context['page_info'] = [
'current_page' => $_REQUEST['start'] / Utils::$context['messages_per_page'] + 1,
'num_pages' => floor((Topic::$info->total_visible_posts - 1) / Utils::$context['messages_per_page']) + 1,
- );
+ ];
// Figure out all the links to the next/prev/first/last/etc.
- if (!($this->can_show_all && isset($_REQUEST['all'])))
- {
- Utils::$context['links'] = array(
+ if (!($this->can_show_all && isset($_REQUEST['all']))) {
+ Utils::$context['links'] = [
'first' => $_REQUEST['start'] >= Utils::$context['messages_per_page'] ? Config::$scripturl . '?topic=' . Topic::$info->id . '.0' : '',
'prev' => $_REQUEST['start'] >= Utils::$context['messages_per_page'] ? Config::$scripturl . '?topic=' . Topic::$info->id . '.' . ($_REQUEST['start'] - Utils::$context['messages_per_page']) : '',
'next' => $_REQUEST['start'] + Utils::$context['messages_per_page'] < Topic::$info->total_visible_posts ? Config::$scripturl . '?topic=' . Topic::$info->id . '.' . ($_REQUEST['start'] + Utils::$context['messages_per_page']) : '',
'last' => $_REQUEST['start'] + Utils::$context['messages_per_page'] < Topic::$info->total_visible_posts ? Config::$scripturl . '?topic=' . Topic::$info->id . '.' . (floor(Topic::$info->total_visible_posts / Utils::$context['messages_per_page']) * Utils::$context['messages_per_page']) : '',
- 'up' => Config::$scripturl . '?board=' . Board::$info->id . '.0'
- );
+ 'up' => Config::$scripturl . '?board=' . Board::$info->id . '.0',
+ ];
}
// If they are viewing all the posts, show all the posts, otherwise limit the number.
- if ($this->can_show_all)
- {
- if (isset($_REQUEST['all']))
- {
+ if ($this->can_show_all) {
+ if (isset($_REQUEST['all'])) {
// No limit! (actually, there is a limit, but...)
Utils::$context['messages_per_page'] = -1;
- Utils::$context['page_index'] .= sprintf(strtr(Theme::$current->settings['page_index']['current_page'], array('%1$d' => '%1$s')), Lang::$txt['all']);
+ Utils::$context['page_index'] .= sprintf(strtr(Theme::$current->settings['page_index']['current_page'], ['%1$d' => '%1$s']), Lang::$txt['all']);
// Set start back to 0...
$_REQUEST['start'] = 0;
}
// They aren't using it, but the *option* is there, at least.
- else
- {
- Utils::$context['page_index'] .= sprintf(strtr(Theme::$current->settings['page_index']['page'], array('{URL}' => Config::$scripturl . '?topic=' . Topic::$info->id . '.0;all')), '', Lang::$txt['all']);
+ else {
+ Utils::$context['page_index'] .= sprintf(strtr(Theme::$current->settings['page_index']['page'], ['{URL}' => Config::$scripturl . '?topic=' . Topic::$info->id . '.0;all']), '', Lang::$txt['all']);
}
}
-
}
/**
@@ -911,22 +914,23 @@ protected function setModerators(): void
// Build a list of this board's moderators.
Utils::$context['moderators'] = &Board::$info->moderators;
Utils::$context['moderator_groups'] = &Board::$info->moderator_groups;
- Utils::$context['link_moderators'] = array();
- if (!empty(Board::$info->moderators))
- {
+ Utils::$context['link_moderators'] = [];
+
+ if (!empty(Board::$info->moderators)) {
// Add a link for each moderator...
- foreach (Board::$info->moderators as $mod)
+ foreach (Board::$info->moderators as $mod) {
Utils::$context['link_moderators'][] = '' . $mod['name'] . '';
+ }
}
- if (!empty(Board::$info->moderator_groups))
- {
+
+ if (!empty(Board::$info->moderator_groups)) {
// Add a link for each moderator group as well...
- foreach (Board::$info->moderator_groups as $mod_group)
+ foreach (Board::$info->moderator_groups as $mod_group) {
Utils::$context['link_moderators'][] = '' . $mod_group['name'] . '';
+ }
}
- if (!empty(Utils::$context['link_moderators']))
- {
+ if (!empty(Utils::$context['link_moderators'])) {
// And show it after the board's name.
Utils::$context['linktree'][count(Utils::$context['linktree']) - 1]['extra_after'] = '(' . (count(Utils::$context['link_moderators']) == 1 ? Lang::$txt['moderator'] : Lang::$txt['moderators']) . ': ' . implode(', ', Utils::$context['link_moderators']) . ')';
}
@@ -949,7 +953,7 @@ protected function setupTemplate(): void
{
// Load the proper template.
Theme::loadTemplate('Display');
- Theme::loadCSSFile('attachments.css', array('minimize' => true, 'order_pos' => 450), 'smf_attachments');
+ Theme::loadCSSFile('attachments.css', ['minimize' => true, 'order_pos' => 450], 'smf_attachments');
// Set a canonical URL for this page.
Utils::$context['canonical_url'] = Config::$scripturl . '?topic=' . Topic::$info->id . '.' . ($this->can_show_all ? '0;all' : Utils::$context['start']);
@@ -985,24 +989,22 @@ protected function setupTemplate(): void
Utils::$context['is_marked_notify'] = false;
// Build the link tree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?topic=' . Topic::$info->id . '.0',
'name' => Topic::$info->subject,
- );
+ ];
- Utils::$context['jump_to'] = array(
+ Utils::$context['jump_to'] = [
'label' => addslashes(Utils::htmlspecialcharsDecode(Lang::$txt['jump_to'])),
- 'board_name' => strtr(Utils::htmlspecialchars(strip_tags(Board::$info->name)), array('&' => '&')),
+ 'board_name' => strtr(Utils::htmlspecialchars(strip_tags(Board::$info->name)), ['&' => '&']),
'child_level' => Board::$info->child_level,
- );
+ ];
// For quick reply we need a response prefix in the default forum language.
- if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix', 600)))
- {
- if (Lang::$default === User::$me->language)
+ if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix', 600))) {
+ if (Lang::$default === User::$me->language) {
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
- else
- {
+ } else {
Lang::load('index', Lang::$default, false);
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
Lang::load('index');
@@ -1012,49 +1014,51 @@ protected function setupTemplate(): void
// Are we showing signatures - or disabled fields?
Utils::$context['signature_enabled'] = substr(Config::$modSettings['signature_settings'], 0, 1) == 1;
- Utils::$context['disabled_fields'] = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : array();
+ Utils::$context['disabled_fields'] = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : [];
// Prevent signature images from going outside the box.
- if (Utils::$context['signature_enabled'])
- {
- list ($sig_limits, $sig_bbc) = explode(':', Config::$modSettings['signature_settings']);
+ if (Utils::$context['signature_enabled']) {
+ list($sig_limits, $sig_bbc) = explode(':', Config::$modSettings['signature_settings']);
$sig_limits = explode(',', $sig_limits);
- if (!empty($sig_limits[5]) || !empty($sig_limits[6]))
+ if (!empty($sig_limits[5]) || !empty($sig_limits[6])) {
Theme::addInlineCss('.signature img { ' . (!empty($sig_limits[5]) ? 'max-width: ' . (int) $sig_limits[5] . 'px; ' : '') . (!empty($sig_limits[6]) ? 'max-height: ' . (int) $sig_limits[6] . 'px; ' : '') . '}');
+ }
}
// Load the drafts js file.
- if (!empty(Topic::$info->permissions['drafts_autosave']))
- Theme::loadJavaScriptFile('drafts.js', array('defer' => false, 'minimize' => true), 'smf_drafts');
+ if (!empty(Topic::$info->permissions['drafts_autosave'])) {
+ Theme::loadJavaScriptFile('drafts.js', ['defer' => false, 'minimize' => true], 'smf_drafts');
+ }
// And the drafts language file.
- if (!empty(Topic::$info->permissions['drafts_save']))
+ if (!empty(Topic::$info->permissions['drafts_save'])) {
Lang::load('Drafts');
+ }
// Spellcheck
- if (Utils::$context['show_spellchecking'])
- Theme::loadJavaScriptFile('spellcheck.js', array('defer' => false, 'minimize' => true), 'smf_spellcheck');
+ if (Utils::$context['show_spellchecking']) {
+ Theme::loadJavaScriptFile('spellcheck.js', ['defer' => false, 'minimize' => true], 'smf_spellcheck');
+ }
// topic.js
- Theme::loadJavaScriptFile('topic.js', array('defer' => false, 'minimize' => true), 'smf_topic');
+ Theme::loadJavaScriptFile('topic.js', ['defer' => false, 'minimize' => true], 'smf_topic');
// quotedText.js
- Theme::loadJavaScriptFile('quotedText.js', array('defer' => true, 'minimize' => true), 'smf_quotedText');
+ Theme::loadJavaScriptFile('quotedText.js', ['defer' => true, 'minimize' => true], 'smf_quotedText');
// Mentions
- if (!empty(Config::$modSettings['enable_mentions']) && User::$me->allowedTo('mention'))
- {
- Theme::loadJavaScriptFile('jquery.atwho.min.js', array('defer' => true), 'smf_atwho');
- Theme::loadJavaScriptFile('jquery.caret.min.js', array('defer' => true), 'smf_caret');
- Theme::loadJavaScriptFile('mentions.js', array('defer' => true, 'minimize' => true), 'smf_mentions');
+ if (!empty(Config::$modSettings['enable_mentions']) && User::$me->allowedTo('mention')) {
+ Theme::loadJavaScriptFile('jquery.atwho.min.js', ['defer' => true], 'smf_atwho');
+ Theme::loadJavaScriptFile('jquery.caret.min.js', ['defer' => true], 'smf_caret');
+ Theme::loadJavaScriptFile('mentions.js', ['defer' => true, 'minimize' => true], 'smf_mentions');
}
// Did we report a post to a moderator just now?
Utils::$context['report_sent'] = isset($_GET['reportsent']);
- Utils::$context['name'] = isset($_SESSION['guest_name']) ? $_SESSION['guest_name'] : '';
- Utils::$context['email'] = isset($_SESSION['guest_email']) ? $_SESSION['guest_email'] : '';
+ Utils::$context['name'] = $_SESSION['guest_name'] ?? '';
+ Utils::$context['email'] = $_SESSION['guest_email'] ?? '';
}
/**
@@ -1063,12 +1067,12 @@ protected function setupTemplate(): void
protected function loadEvents(): void
{
// If we want to show event information in the topic, prepare the data.
- if (User::$me->allowedTo('calendar_view') && !empty(Config::$modSettings['cal_showInTopic']) && !empty(Config::$modSettings['cal_enabled']))
- {
+ if (User::$me->allowedTo('calendar_view') && !empty(Config::$modSettings['cal_showInTopic']) && !empty(Config::$modSettings['cal_enabled'])) {
Utils::$context['linked_calendar_events'] = Event::load(Topic::$info->id, true);
- if (!empty(Utils::$context['linked_calendar_events']))
+ if (!empty(Utils::$context['linked_calendar_events'])) {
Utils::$context['linked_calendar_events'][count(Utils::$context['linked_calendar_events']) - 1]['is_last'] = true;
+ }
}
}
@@ -1077,18 +1081,16 @@ protected function loadEvents(): void
*/
protected function loadPoll(): void
{
- if (!Utils::$context['is_poll'])
+ if (!Utils::$context['is_poll']) {
return;
+ }
$poll = Poll::load(Topic::$info->id, Poll::LOAD_BY_TOPIC);
// Create the poll info if it exists and is valid.
- if (empty($poll))
- {
+ if (empty($poll)) {
Utils::$context['is_poll'] = false;
- }
- else
- {
+ } else {
Utils::$context['poll'] = $poll->format();
}
}
@@ -1101,8 +1103,9 @@ protected function setupVerification(): void
// Do we need to show the visual verification image?
Utils::$context['require_verification'] = !User::$me->is_mod && !User::$me->is_admin && !empty(Config::$modSettings['posts_require_captcha']) && (User::$me->posts < Config::$modSettings['posts_require_captcha'] || (User::$me->is_guest && Config::$modSettings['posts_require_captcha'] == -1));
- if (Utils::$context['require_verification'])
- $verifier = new Verifier(array('id' => 'post'));
+ if (Utils::$context['require_verification']) {
+ $verifier = new Verifier(['id' => 'post']);
+ }
}
/**
@@ -1118,52 +1121,53 @@ protected function getMessagesAndPosters(): void
// Jump to page
// Calculate the fastest way to get the messages!
- if ($start >= Topic::$info->total_visible_posts / 2 && Utils::$context['messages_per_page'] != -1)
- {
+ if ($start >= Topic::$info->total_visible_posts / 2 && Utils::$context['messages_per_page'] != -1) {
$DBascending = !$ascending;
$limit = Topic::$info->total_visible_posts <= $start + $limit ? Topic::$info->total_visible_posts - $start : $limit;
$start = Topic::$info->total_visible_posts <= $start + $limit ? 0 : Topic::$info->total_visible_posts - $start - $limit;
$this->firstIndex = empty(Theme::$current->options['view_newest_first']) ? $start - 1 : $limit - 1;
- }
- else
+ } else {
$DBascending = $ascending;
+ }
// Get each post and poster in this topic.
- $request = Db::$db->query('', '
- SELECT id_msg, id_member, approved
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_msg, id_member, approved
FROM {db_prefix}messages
WHERE id_topic = {int:current_topic}' . (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
AND (approved = {int:is_approved}' . (User::$me->is_guest ? '' : ' OR id_member = {int:current_member}') . ')') . '
ORDER BY id_msg ' . ($DBascending ? '' : 'DESC') . (Utils::$context['messages_per_page'] == -1 ? '' : '
LIMIT {int:start}, {int:max}'),
- array(
+ [
'current_member' => User::$me->id,
'current_topic' => Topic::$info->id,
'is_approved' => 1,
'blank_id_member' => 0,
'start' => $start,
'max' => $limit,
- )
+ ],
);
- $this->messages = array();
- $all_posters = array();
+ $this->messages = [];
+ $all_posters = [];
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (!empty($row['id_member']))
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (!empty($row['id_member'])) {
$all_posters[$row['id_msg']] = $row['id_member'];
+ }
$this->messages[] = $row['id_msg'];
}
// Sort the messages into the correct display order
- if (!$DBascending)
+ if (!$DBascending) {
sort($this->messages);
+ }
Db::$db->free_result($request);
$this->posters = array_unique($all_posters);
- IntegrationHook::call('integrate_display_message_list', array(&$this->messages, &$this->posters));
+ IntegrationHook::call('integrate_display_message_list', [&$this->messages, &$this->posters]);
}
/**
@@ -1171,50 +1175,45 @@ protected function getMessagesAndPosters(): void
*/
protected function initDisplayContext(): void
{
- Utils::$context['loaded_attachments'] = array();
+ Utils::$context['loaded_attachments'] = [];
// If there _are_ messages here... (probably an error otherwise :!)
- if (!empty($this->messages))
- {
+ if (!empty($this->messages)) {
Msg::$getter = Msg::get($this->messages);
// Fetch attachments.
- if (!empty(Config::$modSettings['attachmentEnable']) && User::$me->allowedTo('view_attachments'))
- {
+ if (!empty(Config::$modSettings['attachmentEnable']) && User::$me->allowedTo('view_attachments')) {
Attachment::prepareByMsg($this->messages);
}
// And the likes
- if (!empty(Config::$modSettings['enable_likes']))
+ if (!empty(Config::$modSettings['enable_likes'])) {
Utils::$context['my_likes'] = Topic::$info->getLikedMsgs();
+ }
// Go to the last message if the given time is beyond the time of the last message.
- if (isset(Utils::$context['start_from']) && Utils::$context['start_from'] >= Topic::$info->num_replies)
+ if (isset(Utils::$context['start_from']) && Utils::$context['start_from'] >= Topic::$info->num_replies) {
Utils::$context['start_from'] = Topic::$info->num_replies;
+ }
// Since the anchor information is needed on the top of the page we load these variables beforehand.
- Utils::$context['first_message'] = isset($this->messages[$this->firstIndex]) ? $this->messages[$this->firstIndex] : $this->messages[0];
+ Utils::$context['first_message'] = $this->messages[$this->firstIndex] ?? $this->messages[0];
- if (empty(Theme::$current->options['view_newest_first']))
- {
+ if (empty(Theme::$current->options['view_newest_first'])) {
Utils::$context['first_new_message'] = isset(Utils::$context['start_from']) && $_REQUEST['start'] == Utils::$context['start_from'];
- }
- else
- {
+ } else {
Utils::$context['first_new_message'] = isset(Utils::$context['start_from']) && $_REQUEST['start'] == Topic::$info->num_replies - Utils::$context['start_from'];
}
- }
- else
- {
- Msg::$getter = array();
+ } else {
+ Msg::$getter = [];
Utils::$context['first_message'] = 0;
Utils::$context['first_new_message'] = false;
- Utils::$context['likes'] = array();
+ Utils::$context['likes'] = [];
}
// Set the callback. (do you REALIZE how much memory all the messages would take?!?)
// This will be called from the template.
- Utils::$context['get_message'] = array($this, 'prepareDisplayContext');
+ Utils::$context['get_message'] = [$this, 'prepareDisplayContext'];
}
/**
@@ -1223,19 +1222,19 @@ protected function initDisplayContext(): void
protected function setOldTopicWarning(): void
{
// When was the last time this topic was replied to? Should we warn them about it?
- if (!empty(Config::$modSettings['oldTopicDays']) && (Topic::$info->permissions['can_reply'] || Topic::$info->permissions['can_reply_unapproved']) && empty(Topic::$info->is_sticky))
- {
- $request = Db::$db->query('', '
- SELECT poster_time
+ if (!empty(Config::$modSettings['oldTopicDays']) && (Topic::$info->permissions['can_reply'] || Topic::$info->permissions['can_reply_unapproved']) && empty(Topic::$info->is_sticky)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT poster_time
FROM {db_prefix}messages
WHERE id_msg = {int:id_last_msg}
LIMIT 1',
- array(
+ [
'id_last_msg' => Topic::$info->id_last_msg,
- )
+ ],
);
- list ($lastPostTime) = Db::$db->fetch_row($request);
+ list($lastPostTime) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
Utils::$context['oldTopicError'] = $lastPostTime + Config::$modSettings['oldTopicDays'] * 86400 < time();
@@ -1248,12 +1247,12 @@ protected function setOldTopicWarning(): void
protected function loadEditor(): void
{
// Now create the editor.
- new Editor(array(
+ new Editor([
'id' => 'quickReply',
'value' => '',
- 'labels' => array(
+ 'labels' => [
'post_button' => Lang::$txt['post'],
- ),
+ ],
// add height and width for the editor
'height' => '150px',
'width' => '100%',
@@ -1261,7 +1260,7 @@ protected function loadEditor(): void
'preview_type' => Editor::PREVIEW_HTML,
// This is required
'required' => true,
- ));
+ ]);
Utils::$context['attached'] = '';
Utils::$context['make_poll'] = isset($_REQUEST['poll']);
@@ -1269,8 +1268,9 @@ protected function loadEditor(): void
// Message icons - customized icons are off?
Utils::$context['icons'] = Editor::getMessageIcons(Board::$info->id);
- if (!empty(Utils::$context['icons']))
+ if (!empty(Utils::$context['icons'])) {
Utils::$context['icons'][count(Utils::$context['icons']) - 1]['is_last'] = true;
+ }
}
/**
@@ -1279,114 +1279,97 @@ protected function loadEditor(): void
protected function buildButtons(): void
{
// Build the normal button array.
- Utils::$context['normal_buttons'] = array();
+ Utils::$context['normal_buttons'] = [];
- if (Topic::$info->permissions['can_reply'])
- {
- Utils::$context['normal_buttons']['reply'] = array('text' => 'reply', 'url' => Config::$scripturl . '?action=post;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';last_msg=' . Topic::$info->id_last_msg, 'active' => true);
+ if (Topic::$info->permissions['can_reply']) {
+ Utils::$context['normal_buttons']['reply'] = ['text' => 'reply', 'url' => Config::$scripturl . '?action=post;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';last_msg=' . Topic::$info->id_last_msg, 'active' => true];
}
- if (Topic::$info->permissions['can_add_poll'])
- {
- Utils::$context['normal_buttons']['add_poll'] = array('text' => 'add_poll', 'url' => Config::$scripturl . '?action=editpoll;add;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start']);
+ if (Topic::$info->permissions['can_add_poll']) {
+ Utils::$context['normal_buttons']['add_poll'] = ['text' => 'add_poll', 'url' => Config::$scripturl . '?action=editpoll;add;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start']];
}
- if (Topic::$info->permissions['can_mark_unread'])
- {
- Utils::$context['normal_buttons']['mark_unread'] = array('text' => 'mark_unread', 'url' => Config::$scripturl . '?action=markasread;sa=topic;t=' . Utils::$context['mark_unread_time'] . ';topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']);
+ if (Topic::$info->permissions['can_mark_unread']) {
+ Utils::$context['normal_buttons']['mark_unread'] = ['text' => 'mark_unread', 'url' => Config::$scripturl . '?action=markasread;sa=topic;t=' . Utils::$context['mark_unread_time'] . ';topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']];
}
- if (Topic::$info->permissions['can_print'])
- {
- Utils::$context['normal_buttons']['print'] = array('text' => 'print', 'custom' => 'rel="nofollow"', 'url' => Config::$scripturl . '?action=printpage;topic=' . Utils::$context['current_topic'] . '.0');
+ if (Topic::$info->permissions['can_print']) {
+ Utils::$context['normal_buttons']['print'] = ['text' => 'print', 'custom' => 'rel="nofollow"', 'url' => Config::$scripturl . '?action=printpage;topic=' . Utils::$context['current_topic'] . '.0'];
}
- if (Topic::$info->permissions['can_set_notify'])
- {
- Utils::$context['normal_buttons']['notify'] = array(
+ if (Topic::$info->permissions['can_set_notify']) {
+ Utils::$context['normal_buttons']['notify'] = [
'text' => 'notify_topic_' . Utils::$context['topic_notification_mode'],
- 'sub_buttons' => array(
- array(
+ 'sub_buttons' => [
+ [
'test' => 'can_unwatch',
'text' => 'notify_topic_0',
'url' => Config::$scripturl . '?action=notifytopic;topic=' . Utils::$context['current_topic'] . ';mode=0;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
- ),
- array(
+ ],
+ [
'text' => 'notify_topic_1',
'url' => Config::$scripturl . '?action=notifytopic;topic=' . Utils::$context['current_topic'] . ';mode=1;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
- ),
- array(
+ ],
+ [
'text' => 'notify_topic_2',
'url' => Config::$scripturl . '?action=notifytopic;topic=' . Utils::$context['current_topic'] . ';mode=2;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
- ),
- array(
+ ],
+ [
'text' => 'notify_topic_3',
'url' => Config::$scripturl . '?action=notifytopic;topic=' . Utils::$context['current_topic'] . ';mode=3;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
- ),
- ),
- );
+ ],
+ ],
+ ];
}
// Build the mod button array
- Utils::$context['mod_buttons'] = array();
+ Utils::$context['mod_buttons'] = [];
- if (Topic::$info->permissions['can_move'])
- {
- Utils::$context['mod_buttons']['move'] = array('text' => 'move_topic', 'url' => Config::$scripturl . '?action=movetopic;current_board=' . Utils::$context['current_board'] . ';topic=' . Utils::$context['current_topic'] . '.0');
+ if (Topic::$info->permissions['can_move']) {
+ Utils::$context['mod_buttons']['move'] = ['text' => 'move_topic', 'url' => Config::$scripturl . '?action=movetopic;current_board=' . Utils::$context['current_board'] . ';topic=' . Utils::$context['current_topic'] . '.0'];
}
- if (Topic::$info->permissions['can_delete'])
- {
- Utils::$context['mod_buttons']['delete'] = array('text' => 'remove_topic', 'custom' => 'data-confirm="' . Lang::$txt['are_sure_remove_topic'] . '"', 'class' => 'you_sure', 'url' => Config::$scripturl . '?action=removetopic2;topic=' . Utils::$context['current_topic'] . '.0;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']);
+ if (Topic::$info->permissions['can_delete']) {
+ Utils::$context['mod_buttons']['delete'] = ['text' => 'remove_topic', 'custom' => 'data-confirm="' . Lang::$txt['are_sure_remove_topic'] . '"', 'class' => 'you_sure', 'url' => Config::$scripturl . '?action=removetopic2;topic=' . Utils::$context['current_topic'] . '.0;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']];
}
- if (Topic::$info->permissions['can_lock'])
- {
- Utils::$context['mod_buttons']['lock'] = array('text' => empty(Utils::$context['is_locked']) ? 'set_lock' : 'set_unlock', 'url' => Config::$scripturl . '?action=lock;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';sa=' . (Utils::$context['is_locked'] ? 'unlock' : 'lock') . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']);
+ if (Topic::$info->permissions['can_lock']) {
+ Utils::$context['mod_buttons']['lock'] = ['text' => empty(Utils::$context['is_locked']) ? 'set_lock' : 'set_unlock', 'url' => Config::$scripturl . '?action=lock;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';sa=' . (Utils::$context['is_locked'] ? 'unlock' : 'lock') . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']];
}
- if (Topic::$info->permissions['can_sticky'])
- {
- Utils::$context['mod_buttons']['sticky'] = array('text' => empty(Utils::$context['is_sticky']) ? 'set_sticky' : 'set_nonsticky', 'url' => Config::$scripturl . '?action=sticky;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';sa=' . (Utils::$context['is_sticky'] ? 'nonsticky' : 'sticky') . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']);
+ if (Topic::$info->permissions['can_sticky']) {
+ Utils::$context['mod_buttons']['sticky'] = ['text' => empty(Utils::$context['is_sticky']) ? 'set_sticky' : 'set_nonsticky', 'url' => Config::$scripturl . '?action=sticky;topic=' . Utils::$context['current_topic'] . '.' . Utils::$context['start'] . ';sa=' . (Utils::$context['is_sticky'] ? 'nonsticky' : 'sticky') . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']];
}
- if (Topic::$info->permissions['can_merge'])
- {
- Utils::$context['mod_buttons']['merge'] = array('text' => 'merge', 'url' => Config::$scripturl . '?action=mergetopics;board=' . Utils::$context['current_board'] . '.0;from=' . Utils::$context['current_topic']);
+ if (Topic::$info->permissions['can_merge']) {
+ Utils::$context['mod_buttons']['merge'] = ['text' => 'merge', 'url' => Config::$scripturl . '?action=mergetopics;board=' . Utils::$context['current_board'] . '.0;from=' . Utils::$context['current_topic']];
}
- if (Topic::$info->permissions['calendar_post'])
- {
- Utils::$context['mod_buttons']['calendar'] = array('text' => 'calendar_link', 'url' => Config::$scripturl . '?action=post;calendar;msg=' . Topic::$info->id_first_msg . ';topic=' . Utils::$context['current_topic'] . '.0');
+ if (Topic::$info->permissions['calendar_post']) {
+ Utils::$context['mod_buttons']['calendar'] = ['text' => 'calendar_link', 'url' => Config::$scripturl . '?action=post;calendar;msg=' . Topic::$info->id_first_msg . ';topic=' . Utils::$context['current_topic'] . '.0'];
}
// Restore topic. eh? No monkey business.
- if (Topic::$info->permissions['can_restore_topic'])
- {
- Utils::$context['mod_buttons']['restore_topic'] = array('text' => 'restore_topic', 'url' => Config::$scripturl . '?action=restoretopic;topics=' . Utils::$context['current_topic'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']);
+ if (Topic::$info->permissions['can_restore_topic']) {
+ Utils::$context['mod_buttons']['restore_topic'] = ['text' => 'restore_topic', 'url' => Config::$scripturl . '?action=restoretopic;topics=' . Utils::$context['current_topic'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']];
}
// Allow adding new buttons easily.
// Note: Utils::$context['normal_buttons'] and Utils::$context['mod_buttons'] are added for backward compatibility with 2.0, but are deprecated and should not be used
- IntegrationHook::call('integrate_display_buttons', array(&Utils::$context['normal_buttons']));
+ IntegrationHook::call('integrate_display_buttons', [&Utils::$context['normal_buttons']]);
// Note: integrate_mod_buttons is no longer necessary and deprecated, but is kept for backward compatibility with 2.0
- IntegrationHook::call('integrate_mod_buttons', array(&Utils::$context['mod_buttons']));
+ IntegrationHook::call('integrate_mod_buttons', [&Utils::$context['mod_buttons']]);
// If any buttons have a 'test' check, run those tests now to keep things clean.
- foreach (array('normal_buttons', 'mod_buttons') as $button_strip)
- {
- foreach (Utils::$context[$button_strip] as $key => $value)
- {
- if (isset($value['test']) && empty(Utils::$context[$value['test']]))
- {
+ foreach (['normal_buttons', 'mod_buttons'] as $button_strip) {
+ foreach (Utils::$context[$button_strip] as $key => $value) {
+ if (isset($value['test']) && empty(Utils::$context[$value['test']])) {
unset(Utils::$context[$button_strip][$key]);
- }
- elseif (isset($value['sub_buttons']))
- {
- foreach ($value['sub_buttons'] as $subkey => $subvalue)
- {
- if (isset($subvalue['test']) && empty(Utils::$context[$subvalue['test']]))
+ } elseif (isset($value['sub_buttons'])) {
+ foreach ($value['sub_buttons'] as $subkey => $subvalue) {
+ if (isset($subvalue['test']) && empty(Utils::$context[$subvalue['test']])) {
unset(Utils::$context[$button_strip][$key]['sub_buttons'][$subkey]);
+ }
}
}
}
@@ -1395,7 +1378,8 @@ protected function buildButtons(): void
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Display::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Display::exportStatic')) {
Display::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/DisplayAdminFile.php b/Sources/Actions/DisplayAdminFile.php
index 8737c82609..709dc11a3e 100644
--- a/Sources/Actions/DisplayAdminFile.php
+++ b/Sources/Actions/DisplayAdminFile.php
@@ -14,11 +14,10 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Get one of the admin information files from Simple Machines.
@@ -32,12 +31,11 @@ class DisplayAdminFile implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'DisplayAdminFile',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -62,44 +60,46 @@ public function execute(): void
{
Config::setMemoryLimit('32M');
- if (empty($_REQUEST['filename']) || !is_string($_REQUEST['filename']))
+ if (empty($_REQUEST['filename']) || !is_string($_REQUEST['filename'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Strip off the forum cache part or we won't find it...
$_REQUEST['filename'] = str_replace(Utils::$context['browser_cache'], '', $_REQUEST['filename']);
- $request = Db::$db->query('', '
- SELECT data, filetype
+ $request = Db::$db->query(
+ '',
+ 'SELECT data, filetype
FROM {db_prefix}admin_info_files
WHERE filename = {string:current_filename}
LIMIT 1',
- array(
+ [
'current_filename' => $_REQUEST['filename'],
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
- ErrorHandler::fatalLang('admin_file_not_found', true, array($_REQUEST['filename']), 404);
+
+ if (Db::$db->num_rows($request) == 0) {
+ ErrorHandler::fatalLang('admin_file_not_found', true, [$_REQUEST['filename']], 404);
}
list($file_data, $filetype) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// @todo Temp
// Figure out if sesc is still being used.
- if (strpos($file_data, ';sesc=') !== false && $filetype == 'text/javascript')
- {
- $file_data = "\n" . 'if (!(\'smfForum_sessionvar\' in window))' . "\n\t" . 'window.smfForum_sessionvar = \'sesc\';' . "\n" . strtr($file_data, array(';sesc=' => ';\' + window.smfForum_sessionvar + \'='));
+ if (strpos($file_data, ';sesc=') !== false && $filetype == 'text/javascript') {
+ $file_data = "\n" . 'if (!(\'smfForum_sessionvar\' in window))' . "\n\t" . 'window.smfForum_sessionvar = \'sesc\';' . "\n" . strtr($file_data, [';sesc=' => ';\' + window.smfForum_sessionvar + \'=']);
}
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
// Lets make sure we aren't going to output anything nasty.
@ob_end_clean();
- if (!empty(Config::$modSettings['enableCompressedOutput']))
+ if (!empty(Config::$modSettings['enableCompressedOutput'])) {
@ob_start('ob_gzhandler');
- else
+ } else {
@ob_start();
+ }
// Make sure they know what type of file we are.
header('content-type: ' . $filetype);
@@ -118,8 +118,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;
}
@@ -145,7 +146,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\DisplayAdminFile::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\DisplayAdminFile::exportStatic')) {
DisplayAdminFile::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Feed.php b/Sources/Actions/Feed.php
index 49ed20d6f4..22b0c9948b 100644
--- a/Sources/Actions/Feed.php
+++ b/Sources/Actions/Feed.php
@@ -13,13 +13,14 @@
namespace SMF\Actions;
-use SMF\BackwardCompatibility;
-
use SMF\Attachment;
-use SMF\BrowserDetector;
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Board;
+use SMF\BrowserDetector;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\IP;
@@ -29,8 +30,6 @@
use SMF\Url;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* This class contains the code necessary to display XML feeds.
@@ -66,14 +65,13 @@ class Feed implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ShowXmlFeed',
'build' => 'buildXmlFeed',
'cdataParse' => 'cdata_parse',
- ),
- );
+ ],
+ ];
/*****************
* Class constants
@@ -96,34 +94,34 @@ class Feed implements ActionInterface
* These strings have been broken up and concatenated to help prevent any
* automatic search and replace attempts from changing them.
*/
- const XML_NAMESPACES = array(
- 'rss' => array(),
- 'rss2' => array(
- 'atom' => 'htt'.'p:/'.'/ww'.'w.w3.o'.'rg/2005/Atom',
- ),
- 'atom' => array(
- '' => 'htt'.'p:/'.'/ww'.'w.w3.o'.'rg/2005/Atom',
- ),
- 'rdf' => array(
- '' => 'htt'.'p:/'.'/purl.o'.'rg/rss/1.0/',
- 'rdf' => 'htt'.'p:/'.'/ww'.'w.w3.o'.'rg/1999/02/22-rdf-syntax-ns#',
- 'dc' => 'htt'.'p:/'.'/purl.o'.'rg/dc/elements/1.1/',
- ),
- 'smf' => array(
- 'smf' => 'htt'.'p:/'.'/ww'.'w.simple'.'machines.o'.'rg/xml/%1s',
- ),
- );
+ public const XML_NAMESPACES = [
+ 'rss' => [],
+ 'rss2' => [
+ 'atom' => 'htt' . 'p:/' . '/ww' . 'w.w3.o' . 'rg/2005/Atom',
+ ],
+ 'atom' => [
+ '' => 'htt' . 'p:/' . '/ww' . 'w.w3.o' . 'rg/2005/Atom',
+ ],
+ 'rdf' => [
+ '' => 'htt' . 'p:/' . '/purl.o' . 'rg/rss/1.0/',
+ 'rdf' => 'htt' . 'p:/' . '/ww' . 'w.w3.o' . 'rg/1999/02/22-rdf-syntax-ns#',
+ 'dc' => 'htt' . 'p:/' . '/purl.o' . 'rg/dc/elements/1.1/',
+ ],
+ 'smf' => [
+ 'smf' => 'htt' . 'p:/' . '/ww' . 'w.simple' . 'machines.o' . 'rg/xml/%1s',
+ ],
+ ];
/**
* An array of MIME types for feed formats.
*/
- const MIME_TYPES = array(
+ public const MIME_TYPES = [
'rss' => 'application/rss+xml',
'rss2' => 'application/rss+xml',
'atom' => 'application/atom+xml',
'rdf' => 'application/rdf+xml',
'smf' => 'text/xml',
- );
+ ];
/*******************
* Public properties
@@ -182,21 +180,21 @@ class Feed implements ActionInterface
*
* Metadata about this feed.
*/
- public array $metadata = array();
+ public array $metadata = [];
/**
* @var array
*
* Main data in this feed.
*/
- public array $data = array();
+ public array $data = [];
/**
* @var array
*
* Boards to fetch posts from.
*/
- public array $boards = array();
+ public array $boards = [];
/**
* @var string
@@ -211,11 +209,11 @@ class Feed implements ActionInterface
*
* The constructed XML.
*/
- public array $xml = array(
+ public array $xml = [
'header' => '',
'items' => '',
'footer' => '',
- );
+ ];
/**************************
* Public static properties
@@ -226,14 +224,14 @@ class Feed implements ActionInterface
*
* List all the different types of data they can pull.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'recent' => 'getXmlRecent',
'news' => 'getXmlNews',
'members' => 'getXmlMembers',
'profile' => 'getXmlProfile',
'posts' => 'getXmlPosts',
'personal_messages' => 'getXmlPMs',
- );
+ ];
/*********************
* Internal properties
@@ -244,10 +242,10 @@ class Feed implements ActionInterface
*
* Used to optimize SQL queries.
*/
- protected array $optimize_msg = array(
+ protected array $optimize_msg = [
'highest' => 'm.id_msg <= b.id_last_msg',
'lowest' => 'm.id_msg >= 0',
- );
+ ];
/**
* @var string
@@ -280,12 +278,12 @@ class Feed implements ActionInterface
* @param int $member The member whose data is being requested.
* If null, will try $_GET['u'] and then User::$me->id.
*/
- public function __construct(string $subaction = null, int $member = null)
+ public function __construct(?string $subaction = null, ?int $member = null)
{
$this->host = Url::create(Config::$scripturl)->host;
// Easy adding of sub actions
- IntegrationHook::call('integrate_xmlfeeds', array(&self::$subactions));
+ IntegrationHook::call('integrate_xmlfeeds', [&self::$subactions]);
// These things are simple to set.
$this->setSubaction($subaction);
@@ -300,139 +298,135 @@ public function __construct(string $subaction = null, int $member = null)
Lang::load('Stats');
// Some general metadata for this feed. We'll change some of these values below.
- $this->metadata = array(
+ $this->metadata = [
'title' => '',
'desc' => sprintf(Lang::$txt['xml_rss_desc'], Utils::$context['forum_name']),
'author' => Utils::$context['forum_name'],
'source' => Config::$scripturl,
'rights' => '© ' . date('Y') . ' ' . Utils::$context['forum_name'],
'icon' => !empty(Theme::$current->settings['og_image']) ? Theme::$current->settings['og_image'] : Config::$boardurl . '/favicon.ico',
- 'language' => !empty(Lang::$txt['lang_locale']) ? str_replace("_", "-", substr(Lang::$txt['lang_locale'], 0, strcspn(Lang::$txt['lang_locale'], "."))) : 'en',
+ 'language' => !empty(Lang::$txt['lang_locale']) ? str_replace('_', '-', substr(Lang::$txt['lang_locale'], 0, strcspn(Lang::$txt['lang_locale'], '.'))) : 'en',
'self' => Config::$scripturl,
- );
+ ];
// Set $this->metadata['self'] to the canonical form of the requested URL.
- foreach (array('action', 'sa', 'type', 'board', 'boards', 'c', 'u', 'limit', 'offset') as $var)
- {
- if (isset($_GET[$var]))
- {
- $this->metadata['self'] .= ($this->metadata['self'] === Config::$scripturl ? '?' : ';' ) . $var . '=' . $_GET[$var];
+ foreach (['action', 'sa', 'type', 'board', 'boards', 'c', 'u', 'limit', 'offset'] as $var) {
+ if (isset($_GET[$var])) {
+ $this->metadata['self'] .= ($this->metadata['self'] === Config::$scripturl ? '?' : ';') . $var . '=' . $_GET[$var];
}
}
// Handle the cases where a board, boards, or category is asked for.
- if (!empty($_GET['c']) && empty(Board::$info->id))
- {
+ if (!empty($_GET['c']) && empty(Board::$info->id)) {
$_GET['c'] = explode(',', $_GET['c']);
- foreach ($_GET['c'] as $i => $c)
+ foreach ($_GET['c'] as $i => $c) {
$_GET['c'][$i] = (int) $c;
+ }
- if (count($_GET['c']) == 1)
- {
- $request = Db::$db->query('', '
- SELECT name
+ if (count($_GET['c']) == 1) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT name
FROM {db_prefix}categories
WHERE id_cat = {int:current_category}',
- array(
+ [
'current_category' => (int) $_GET['c'][0],
- )
+ ],
);
list($this->metadata['title']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
}
$total_cat_posts = 0;
- $this->boards = array();
- $request = Db::$db->query('', '
- SELECT b.id_board, b.num_posts
+ $this->boards = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board, b.num_posts
FROM {db_prefix}boards AS b
WHERE b.id_cat IN ({array_int:current_category_list})
AND {query_see_board}',
- array(
+ [
'current_category_list' => $_GET['c'],
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$this->boards[] = $row['id_board'];
$total_cat_posts += $row['num_posts'];
}
Db::$db->free_result($request);
- if (!empty($this->boards))
- {
+ if (!empty($this->boards)) {
$this->query_this_board = 'b.id_board IN (' . implode(', ', $this->boards) . ')';
- }
- else
- {
+ } else {
ErrorHandler::fatalLang('no_board', false);
}
// Try to limit the number of messages we look through.
- if ($total_cat_posts > 100 && $total_cat_posts > Config::$modSettings['totalMessages'] / 15)
- {
+ if ($total_cat_posts > 100 && $total_cat_posts > Config::$modSettings['totalMessages'] / 15) {
$this->optimize_msg['lowest'] = 'm.id_msg >= ' . max(0, Config::$modSettings['maxMsgID'] - 400 - $this->limit * 5);
}
- }
- elseif (!empty($_GET['boards']))
- {
+ } elseif (!empty($_GET['boards'])) {
$_GET['boards'] = explode(',', $_GET['boards']);
- foreach ($_GET['boards'] as $i => $b)
+ foreach ($_GET['boards'] as $i => $b) {
$_GET['boards'][$i] = (int) $b;
+ }
$total_posts = 0;
- $this->boards = array();
+ $this->boards = [];
$num_boards = 0;
- $request = Db::$db->query('', '
- SELECT b.id_board, b.num_posts, b.name
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board, b.num_posts, b.name
FROM {db_prefix}boards AS b
WHERE b.id_board IN ({array_int:board_list})
AND {query_see_board}
LIMIT {int:limit}',
- array(
+ [
'board_list' => $_GET['boards'],
'limit' => count($_GET['boards']),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (++$num_boards == 1)
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (++$num_boards == 1) {
$this->metadata['title'] = $row['name'];
+ }
$this->boards[] = $row['id_board'];
$total_posts += $row['num_posts'];
}
Db::$db->free_result($request);
- if ($num_boards == 0)
+ if ($num_boards == 0) {
ErrorHandler::fatalLang('no_board', false);
+ }
- if (!empty($this->boards))
+ if (!empty($this->boards)) {
$this->query_this_board = 'b.id_board IN (' . implode(', ', $this->boards) . ')';
+ }
// The more boards, the more we're going to look through...
- if ($total_posts > 100 && $total_posts > Config::$modSettings['totalMessages'] / 12)
- {
+ if ($total_posts > 100 && $total_posts > Config::$modSettings['totalMessages'] / 12) {
$this->optimize_msg['lowest'] = 'm.id_msg >= ' . max(0, Config::$modSettings['maxMsgID'] - 500 - $this->limit * 5);
}
- }
- elseif (!empty(Board::$info->id))
- {
- $request = Db::$db->query('', '
- SELECT num_posts
+ } elseif (!empty(Board::$info->id)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT num_posts
FROM {db_prefix}boards AS b
WHERE id_board = {int:current_board}
AND {query_see_board}
LIMIT 1',
- array(
+ [
'current_board' => Board::$info->id,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
Db::$db->free_result($request);
ErrorHandler::fatalLang('no_board', false);
}
@@ -447,13 +441,10 @@ public function __construct(string $subaction = null, int $member = null)
$this->query_this_board = 'b.id_board = ' . Board::$info->id;
// Try to look through just a few messages, if at all possible.
- if ($total_posts > 80 && $total_posts > Config::$modSettings['totalMessages'] / 10)
- {
+ if ($total_posts > 80 && $total_posts > Config::$modSettings['totalMessages'] / 10) {
$this->optimize_msg['lowest'] = 'm.id_msg >= ' . max(0, Config::$modSettings['maxMsgID'] - 600 - $this->limit * 5);
}
- }
- else
- {
+ } else {
$this->query_this_board = '{query_see_board}' . (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0 ? '
AND b.id_board != ' . Config::$modSettings['recycle_board'] : '');
@@ -463,8 +454,9 @@ public function __construct(string $subaction = null, int $member = null)
$this->metadata['title'] .= (!empty($this->metadata['title']) ? ' - ' : '') . Utils::$context['forum_name'];
// Sanitize feed metadata values
- foreach ($this->metadata as $key => $value)
+ foreach ($this->metadata as $key => $value) {
$this->metadata[$key] = strip_tags($value);
+ }
}
/**
@@ -486,37 +478,34 @@ public function execute(): void
public function getData(): array
{
// We only want some information, not all of it.
- $cachekey = array($this->subaction, $this->limit, $this->ascending, $this->start_after);
+ $cachekey = [$this->subaction, $this->limit, $this->ascending, $this->start_after];
- if (!empty($this->member))
+ if (!empty($this->member)) {
$cachekey[] = $this->member;
+ }
- if (!empty($this->boards))
+ if (!empty($this->boards)) {
$cachekey[] = 'boards=' . implode(',', $this->boards);
+ }
$cachekey = md5(Utils::jsonEncode($cachekey) . (!empty($this->query_this_board) ? $this->query_this_board : ''));
$cache_t = microtime(true);
// Get the associative array representing the xml.
- if (!empty(CacheApi::$enable) && (!User::$me->is_guest || CacheApi::$enable >= 3))
- {
+ if (!empty(CacheApi::$enable) && (!User::$me->is_guest || CacheApi::$enable >= 3)) {
$this->data = CacheApi::get('xmlfeed-' . $this->format . ':' . (User::$me->is_guest ? '' : User::$me->id . '-') . $cachekey, 240);
}
- if (empty($this->data))
- {
+ if (empty($this->data)) {
// Should we call one of this class's own methods, or something added by a mod?
- if (is_callable(array($this, self::$subactions[$this->subaction])))
- {
- $call = array($this, self::$subactions[$this->subaction]);
- }
- else
- {
+ if (is_callable([$this, self::$subactions[$this->subaction]])) {
+ $call = [$this, self::$subactions[$this->subaction]];
+ } else {
$call = Utils::getCallable(self::$subactions[$this->subaction]);
}
- $this->data = !empty($call) ? call_user_func($call, $this->format) : array();
+ $this->data = !empty($call) ? call_user_func($call, $this->format) : [];
if (
!empty(CacheApi::$enable)
@@ -524,8 +513,7 @@ public function getData(): array
(User::$me->is_guest && CacheApi::$enable >= 3)
|| (!User::$me->is_guest && (microtime(true) - $cache_t > 0.2))
)
- )
- {
+ ) {
CacheApi::put('xmlfeed-' . $this->format . ':' . (User::$me->is_guest ? '' : User::$me->id . '-') . $cachekey, $this->data, 240);
}
}
@@ -542,17 +530,14 @@ public function emit(): void
$filename[] = $this->metadata['title'];
$filename[] = $this->subaction;
- if (in_array($this->subaction, array('profile', 'posts', 'personal_messages')))
+ if (in_array($this->subaction, ['profile', 'posts', 'personal_messages'])) {
$filename[] = 'u=' . $this->member;
+ }
- if (!empty($this->boards))
- {
- if (count($this->boards) > 1)
- {
+ if (!empty($this->boards)) {
+ if (count($this->boards) > 1) {
$filename[] = 'boards=' . implode(',', $this->boards);
- }
- else
- {
+ } else {
$filename[] = 'board=' . reset($this->boards);
}
}
@@ -561,15 +546,14 @@ public function emit(): void
$filename = preg_replace(Utils::$context['utf8'] ? '/[^\p{L}\p{M}\p{N}\-]+/u' : '/[\s_,.\/\\;:\'<>?|\[\]{}~!@#$%^&*()=+`]+/', '_', str_replace('"', '', Utils::htmlspecialcharsDecode(strip_tags(implode('-', $filename)))));
- $file = array(
+ $file = [
'filename' => $filename . '.xml',
'mime_type' => self::MIME_TYPES[$this->format] . '; charset=' . (empty(Utils::$context['character_set']) ? 'UTF-8' : Utils::$context['character_set']),
'content' => implode('', $this->xml),
'disposition' => isset($_GET['download']) ? 'attachment' : 'inline',
- );
+ ];
- if (isset($_GET['debug']) || (BrowserDetector::isBrowser('ie') && $this->format == 'rdf'))
- {
+ if (isset($_GET['debug']) || (BrowserDetector::isBrowser('ie') && $this->format == 'rdf')) {
$file['mime_type'] = str_replace(self::MIME_TYPES[$this->format], self::MIME_TYPES['smf'], $file['mime_type']);
}
@@ -586,149 +570,145 @@ public function emit(): void
*/
public function getXmlMembers(): array
{
- if (!User::$me->allowedTo('view_mlist'))
- return array();
+ if (!User::$me->allowedTo('view_mlist')) {
+ return [];
+ }
Lang::load('Profile');
// Find the most (or least) recent members.
- $data = array();
+ $data = [];
- $request = Db::$db->query('', '
- SELECT id_member, member_name, real_name, date_registered, last_login
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, member_name, real_name, date_registered, last_login
FROM {db_prefix}members
ORDER BY id_member {raw:ascdesc}
LIMIT {int:limit}',
- array(
+ [
'limit' => $this->limit,
'ascdesc' => !empty($this->ascending) ? 'ASC' : 'DESC',
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// If any control characters slipped in somehow, kill the evil things
- $row = filter_var($row, FILTER_CALLBACK, array('options' => '\\SMF\\Utils::cleanXml'));
+ $row = filter_var($row, FILTER_CALLBACK, ['options' => '\\SMF\\Utils::cleanXml']);
// Create a GUID for each member using the tag URI scheme
$guid = 'tag:' . $this->host . ',' . gmdate('Y-m-d', $row['date_registered']) . ':member=' . $row['id_member'];
// Make the data look rss-ish.
- if ($this->format == 'rss' || $this->format == 'rss2')
- {
- $data[] = array(
+ if ($this->format == 'rss' || $this->format == 'rss2') {
+ $data[] = [
'tag' => 'item',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $row['real_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- ),
- array(
+ ],
+ [
'tag' => 'comments',
'content' => Config::$scripturl . '?action=pm;sa=send;u=' . $row['id_member'],
- ),
- array(
+ ],
+ [
'tag' => 'pubDate',
- 'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['date_registered']),
- ),
- array(
+ 'content' => gmdate('D, d M Y H:i:s \\G\\M\\T', $row['date_registered']),
+ ],
+ [
'tag' => 'guid',
'content' => $guid,
- 'attributes' => array(
+ 'attributes' => [
'isPermaLink' => 'false',
- ),
- ),
- ),
- );
- }
- elseif ($this->format == 'rdf')
- {
- $data[] = array(
+ ],
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'rdf') {
+ $data[] = [
'tag' => 'item',
- 'attributes' => array('rdf:about' => Config::$scripturl . '?action=profile;u=' . $row['id_member']),
- 'content' => array(
- array(
+ 'attributes' => ['rdf:about' => Config::$scripturl . '?action=profile;u=' . $row['id_member']],
+ 'content' => [
+ [
'tag' => 'dc:format',
'content' => 'text/html',
- ),
- array(
+ ],
+ [
'tag' => 'title',
'content' => $row['real_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- ),
- ),
- );
- }
- elseif ($this->format == 'atom')
- {
- $data[] = array(
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'atom') {
+ $data[] = [
'tag' => 'entry',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $row['real_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array(
+ 'attributes' => [
'rel' => 'alternate',
'type' => 'text/html',
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- ),
- ),
- array(
+ ],
+ ],
+ [
'tag' => 'published',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['date_registered']),
- ),
- array(
+ ],
+ [
'tag' => 'updated',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['last_login']),
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $guid,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
// More logical format for the data, but harder to apply.
- else
- {
- $data[] = array(
+ else {
+ $data[] = [
'tag' => 'member',
- 'attributes' => array('label' => Lang::$txt['who_member']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['who_member']],
+ 'content' => [
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $row['real_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'time',
- 'attributes' => array('label' => Lang::$txt['date_registered'], 'UTC' => Time::gmstrftime('%F %T', $row['date_registered'])),
+ 'attributes' => ['label' => Lang::$txt['date_registered'], 'UTC' => Time::gmstrftime('%F %T', $row['date_registered'])],
'content' => Utils::htmlspecialchars(strip_tags(Time::create('@' . $row['date_registered'], new \DateTimeZone(Config::$modSettings['default_timezone']))->format(null, false))),
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_member'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- ),
- ),
- );
+ ],
+ ],
+ ];
}
}
Db::$db->free_result($request);
@@ -750,15 +730,16 @@ public function getXmlNews(): array
- are on an any board OR in a specified board.
- can be seen by this user. */
- $data = array();
+ $data = [];
$done = false;
$loops = 0;
- while (!$done)
- {
+
+ while (!$done) {
$optimize_msg = implode(' AND ', $this->optimize_msg);
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
m.smileys_enabled, m.poster_time, m.id_msg, m.subject, m.body, m.modified_time,
m.icon, t.id_topic, t.id_board, t.num_replies,
b.name AS bname,
@@ -775,45 +756,39 @@ public function getXmlNews(): array
AND t.approved = {int:is_approved}' : '') . '
ORDER BY t.id_first_msg {raw:ascdesc}
LIMIT {int:limit}',
- array(
+ [
'current_board' => Board::$info->id,
'is_approved' => 1,
'limit' => $this->limit,
'optimize_msg' => $optimize_msg,
'ascdesc' => !empty($this->ascending) ? 'ASC' : 'DESC',
- )
+ ],
);
+
// If we don't have $this->limit results, try again with an unoptimized version covering all rows.
- if ($loops < 2 && Db::$db->num_rows($request) < $this->limit)
- {
+ if ($loops < 2 && Db::$db->num_rows($request) < $this->limit) {
Db::$db->free_result($request);
- if (empty($_GET['boards']) && empty(Board::$info->id))
- {
+ if (empty($_GET['boards']) && empty(Board::$info->id)) {
unset($this->optimize_msg['lowest']);
- }
- else
- {
+ } else {
$this->optimize_msg['lowest'] = 'm.id_msg >= t.id_first_msg';
}
$this->optimize_msg['highest'] = 'm.id_msg <= t.id_last_msg';
$loops++;
- }
- else
- {
+ } else {
$done = true;
}
}
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// If any control characters slipped in somehow, kill the evil things
- $row = filter_var($row, FILTER_CALLBACK, array('options' => '\\SMF\\Utils::cleanXml'));
+ $row = filter_var($row, FILTER_CALLBACK, ['options' => '\\SMF\\Utils::cleanXml']);
// Limit the length of the message, if the option is set.
- if (!empty(Config::$modSettings['xmlnews_maxlen']) && Utils::entityStrlen(str_replace(' ', "\n", $row['body'])) > Config::$modSettings['xmlnews_maxlen'])
- {
- $row['body'] = strtr(Utils::entitySubstr(str_replace(' ', "\n", $row['body']), 0, Config::$modSettings['xmlnews_maxlen'] - 3), array("\n" => ' ')) . '...';
+ if (!empty(Config::$modSettings['xmlnews_maxlen']) && Utils::entityStrlen(str_replace(' ', "\n", $row['body'])) > Config::$modSettings['xmlnews_maxlen']) {
+ $row['body'] = strtr(Utils::entitySubstr(str_replace(' ', "\n", $row['body']), 0, Config::$modSettings['xmlnews_maxlen'] - 3), ["\n" => ' ']) . '...';
}
$row['body'] = BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], $row['id_msg']);
@@ -822,31 +797,25 @@ public function getXmlNews(): array
Lang::censorText($row['subject']);
// Do we want to include any attachments?
- if (!empty(Config::$modSettings['attachmentEnable']) && !empty(Config::$modSettings['xmlnews_attachments']) && User::$me->allowedTo('view_attachments', $row['id_board']))
- {
+ if (!empty(Config::$modSettings['attachmentEnable']) && !empty(Config::$modSettings['xmlnews_attachments']) && User::$me->allowedTo('view_attachments', $row['id_board'])) {
$loaded_attachments = Attachment::loadByMsg($row['id_msg'], Attachment::APPROVED_TRUE);
// Sort the attachments by size to make things easier below
- if (!empty($loaded_attachments))
- {
+ if (!empty($loaded_attachments)) {
uasort(
$loaded_attachments,
- function($a, $b)
- {
- if ($a->size == $b->size)
+ function ($a, $b) {
+ if ($a->size == $b->size) {
return 0;
+ }
return ($a->size < $b->size) ? -1 : 1;
- }
+ },
);
- }
- else
- {
+ } else {
$loaded_attachments = null;
}
- }
- else
- {
+ } else {
$loaded_attachments = null;
}
@@ -854,318 +823,303 @@ function($a, $b)
$guid = 'tag:' . $this->host . ',' . gmdate('Y-m-d', $row['poster_time']) . ':topic=' . $row['id_topic'];
// Being news, this actually makes sense in rss format.
- if ($this->format == 'rss' || $this->format == 'rss2')
- {
+ if ($this->format == 'rss' || $this->format == 'rss2') {
// Only one attachment allowed in RSS.
- if ($loaded_attachments !== null)
- {
+ if ($loaded_attachments !== null) {
$attachment = array_pop($loaded_attachments);
- $enclosure = array(
+ $enclosure = [
'url' => self::fixPossibleUrl(Config::$scripturl . '?action=dlattach;topic=' . $attachment->topic . '.0;attach=' . $attachment->id),
'length' => $attachment->size,
'type' => $attachment->mime_type,
- );
- }
- else
- {
+ ];
+ } else {
$enclosure = null;
}
- $data[] = array(
+ $data[] = [
'tag' => 'item',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0',
- ),
- array(
+ ],
+ [
'tag' => 'description',
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'author',
'content' => (User::$me->allowedTo('moderate_forum') || $row['id_member'] == User::$me->id) ? $row['poster_email'] . ' (' . $row['poster_name'] . ')' : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'comments',
'content' => Config::$scripturl . '?action=post;topic=' . $row['id_topic'] . '.0',
- ),
- array(
+ ],
+ [
'tag' => 'category',
'content' => $row['bname'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'pubDate',
- 'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['poster_time']),
- ),
- array(
+ 'content' => gmdate('D, d M Y H:i:s \\G\\M\\T', $row['poster_time']),
+ ],
+ [
'tag' => 'guid',
'content' => $guid,
- 'attributes' => array(
+ 'attributes' => [
'isPermaLink' => 'false',
- ),
- ),
- array(
+ ],
+ ],
+ [
'tag' => 'enclosure',
'attributes' => $enclosure,
- ),
- ),
- );
- }
- elseif ($this->format == 'rdf')
- {
- $data[] = array(
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'rdf') {
+ $data[] = [
'tag' => 'item',
- 'attributes' => array('rdf:about' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0'),
- 'content' => array(
- array(
+ 'attributes' => ['rdf:about' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0'],
+ 'content' => [
+ [
'tag' => 'dc:format',
'content' => 'text/html',
- ),
- array(
+ ],
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0',
- ),
- array(
+ ],
+ [
'tag' => 'description',
'content' => $row['body'],
'cdata' => true,
- ),
- ),
- );
- }
- elseif ($this->format == 'atom')
- {
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'atom') {
// Only one attachment allowed
- if (!empty($loaded_attachments))
- {
+ if (!empty($loaded_attachments)) {
$attachment = array_pop($loaded_attachments);
- $enclosure = array(
+ $enclosure = [
'rel' => 'enclosure',
'href' => self::fixPossibleUrl(Config::$scripturl . '?action=dlattach;topic=' . $attachment->topic . '.0;attach=' . $attachment->id),
'length' => $attachment->size,
'type' => $attachment->mime_type,
- );
- }
- else
- {
+ ];
+ } else {
$enclosure = null;
}
- $data[] = array(
+ $data[] = [
'tag' => 'entry',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array(
+ 'attributes' => [
'rel' => 'alternate',
'type' => 'text/html',
'href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0',
- ),
- ),
- array(
+ ],
+ ],
+ [
'tag' => 'summary',
- 'attributes' => array('type' => 'html'),
+ 'attributes' => ['type' => 'html'],
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'category',
- 'attributes' => array('term' => $row['bname']),
+ 'attributes' => ['term' => $row['bname']],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'author',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'name',
'content' => $row['poster_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'email',
'content' => (User::$me->allowedTo('moderate_forum') || $row['id_member'] == User::$me->id) ? $row['poster_email'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'uri',
'content' => !empty($row['id_member']) ? Config::$scripturl . '?action=profile;u=' . $row['id_member'] : null,
- ),
- )
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'published',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['poster_time']),
- ),
- array(
+ ],
+ [
'tag' => 'updated',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', empty($row['modified_time']) ? $row['poster_time'] : $row['modified_time']),
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $guid,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'attributes' => $enclosure,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
// The biggest difference here is more information.
- else
- {
+ else {
Lang::load('Post');
- $attachments = array();
- if (!empty($loaded_attachments))
- {
- foreach ($loaded_attachments as $attachment)
- {
- $attachments[] = array(
+ $attachments = [];
+
+ if (!empty($loaded_attachments)) {
+ foreach ($loaded_attachments as $attachment) {
+ $attachments[] = [
'tag' => 'attachment',
- 'attributes' => array('label' => Lang::$txt['attachment']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['attachment']],
+ 'content' => [
+ [
'tag' => 'id',
'content' => $attachment->id,
- ),
- array(
+ ],
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
- 'content' => preg_replace('~&#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '\\1;', $attachment->name),
- ),
- array(
+ 'attributes' => ['label' => Lang::$txt['name']],
+ 'content' => preg_replace('~&#(\d{1,7}|x[0-9a-fA-F]{1,6});~', '\1;', $attachment->name),
+ ],
+ [
'tag' => 'downloads',
- 'attributes' => array('label' => Lang::$txt['downloads']),
+ 'attributes' => ['label' => Lang::$txt['downloads']],
'content' => $attachment->downloads,
- ),
- array(
+ ],
+ [
'tag' => 'size',
- 'attributes' => array('label' => Lang::$txt['filesize']),
+ 'attributes' => ['label' => Lang::$txt['filesize']],
'content' => ($attachment->size < 1024000) ? round($attachment->size / 1024, 2) . ' ' . Lang::$txt['kilobyte'] : round($attachment->size / 1024 / 1024, 2) . ' ' . Lang::$txt['megabyte'],
- ),
- array(
+ ],
+ [
'tag' => 'byte_size',
- 'attributes' => array('label' => Lang::$txt['filesize']),
+ 'attributes' => ['label' => Lang::$txt['filesize']],
'content' => $attachment->size,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?action=dlattach;topic=' . $attachment->topic . '.0;attach=' . $attachment->id,
- ),
- )
- );
+ ],
+ ],
+ ];
}
- }
- else
- {
+ } else {
$attachments = null;
}
- $data[] = array(
+ $data[] = [
'tag' => 'article',
- 'attributes' => array('label' => Lang::$txt['news']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['news']],
+ 'content' => [
+ [
'tag' => 'time',
- 'attributes' => array('label' => Lang::$txt['date'], 'UTC' => Time::gmstrftime('%F %T', $row['poster_time'])),
+ 'attributes' => ['label' => Lang::$txt['date'], 'UTC' => Time::gmstrftime('%F %T', $row['poster_time'])],
'content' => Utils::htmlspecialchars(strip_tags(Time::create('@' . $row['poster_time'], new \DateTimeZone(Config::$modSettings['default_timezone']))->format(null, false))),
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_topic'],
- ),
- array(
+ ],
+ [
'tag' => 'subject',
- 'attributes' => array('label' => Lang::$txt['subject']),
+ 'attributes' => ['label' => Lang::$txt['subject']],
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'body',
- 'attributes' => array('label' => Lang::$txt['message']),
+ 'attributes' => ['label' => Lang::$txt['message']],
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'poster',
- 'attributes' => array('label' => Lang::$txt['author']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['author']],
+ 'content' => [
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $row['poster_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_member'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => !empty($row['id_member']) ? array('label' => Lang::$txt['url']) : null,
+ 'attributes' => !empty($row['id_member']) ? ['label' => Lang::$txt['url']] : null,
'content' => !empty($row['id_member']) ? Config::$scripturl . '?action=profile;u=' . $row['id_member'] : '',
- ),
- )
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'topic',
- 'attributes' => array('label' => Lang::$txt['topic']),
+ 'attributes' => ['label' => Lang::$txt['topic']],
'content' => $row['id_topic'],
- ),
- array(
+ ],
+ [
'tag' => 'board',
- 'attributes' => array('label' => Lang::$txt['board']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['board']],
+ 'content' => [
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $row['bname'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_board'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?board=' . $row['id_board'] . '.0',
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0',
- ),
- array(
+ ],
+ [
'tag' => 'attachments',
- 'attributes' => array('label' => Lang::$txt['attachments']),
+ 'attributes' => ['label' => Lang::$txt['attachments']],
'content' => $attachments,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
}
Db::$db->free_result($request);
@@ -1181,16 +1135,17 @@ function($a, $b)
*/
public function getXmlRecent(): array
{
- $data = array();
- $messages = array();
+ $data = [];
+ $messages = [];
$done = false;
$loops = 0;
- while (!$done)
- {
+
+ while (!$done) {
$optimize_msg = implode(' AND ', $this->optimize_msg);
- $request = Db::$db->query('', '
- SELECT m.id_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}boards AS b ON (m.id_board = b.id_board)
INNER JOIN {db_prefix}topics AS t ON (m.id_topic = t.id_topic)
@@ -1201,38 +1156,42 @@ public function getXmlRecent(): array
AND t.approved = {int:is_approved}' : '') . '
ORDER BY m.id_msg DESC
LIMIT {int:limit}',
- array(
+ [
'limit' => $this->limit,
'current_board' => Board::$info->id,
'is_approved' => 1,
'optimize_msg' => $optimize_msg,
- )
+ ],
);
+
// If we don't have $this->limit results, try again with an unoptimized version covering all rows.
- if ($loops < 2 && Db::$db->num_rows($request) < $this->limit)
- {
+ if ($loops < 2 && Db::$db->num_rows($request) < $this->limit) {
Db::$db->free_result($request);
- if (empty($_GET['boards']) && empty(Board::$info->id))
+
+ if (empty($_GET['boards']) && empty(Board::$info->id)) {
unset($this->optimize_msg['lowest']);
- else
+ } else {
$this->optimize_msg['lowest'] = $loops ? 'm.id_msg >= t.id_first_msg' : 'm.id_msg >= (t.id_last_msg - t.id_first_msg) / 2';
+ }
$loops++;
- }
- else
+ } else {
$done = true;
+ }
}
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$messages[] = $row['id_msg'];
}
Db::$db->free_result($request);
- if (empty($messages))
- return array();
+ if (empty($messages)) {
+ return [];
+ }
// Find the most recent posts this user can see.
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
m.smileys_enabled, m.poster_time, m.id_msg, m.subject, m.body, m.id_topic, t.id_board,
b.name AS bname, t.num_replies, m.id_member, m.icon, mf.id_member AS id_first_member,
COALESCE(mem.real_name, m.poster_name) AS poster_name, mf.subject AS first_subject,
@@ -1248,21 +1207,20 @@ public function getXmlRecent(): array
' . (empty(Board::$info->id) ? '' : 'AND t.id_board = {int:current_board}') . '
ORDER BY m.id_msg DESC
LIMIT {int:limit}',
- array(
+ [
'limit' => $this->limit,
'current_board' => Board::$info->id,
'message_list' => $messages,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// If any control characters slipped in somehow, kill the evil things
- $row = filter_var($row, FILTER_CALLBACK, array('options' => '\\SMF\\Utils::cleanXml'));
+ $row = filter_var($row, FILTER_CALLBACK, ['options' => '\\SMF\\Utils::cleanXml']);
// Limit the length of the message, if the option is set.
- if (!empty(Config::$modSettings['xmlnews_maxlen']) && Utils::entityStrlen(str_replace(' ', "\n", $row['body'])) > Config::$modSettings['xmlnews_maxlen'])
- {
- $row['body'] = strtr(Utils::entitySubstr(str_replace(' ', "\n", $row['body']), 0, Config::$modSettings['xmlnews_maxlen'] - 3), array("\n" => ' ')) . '...';
+ if (!empty(Config::$modSettings['xmlnews_maxlen']) && Utils::entityStrlen(str_replace(' ', "\n", $row['body'])) > Config::$modSettings['xmlnews_maxlen']) {
+ $row['body'] = strtr(Utils::entitySubstr(str_replace(' ', "\n", $row['body']), 0, Config::$modSettings['xmlnews_maxlen'] - 3), ["\n" => ' ']) . '...';
}
$row['body'] = BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], $row['id_msg']);
@@ -1271,31 +1229,25 @@ public function getXmlRecent(): array
Lang::censorText($row['subject']);
// Do we want to include any attachments?
- if (!empty(Config::$modSettings['attachmentEnable']) && !empty(Config::$modSettings['xmlnews_attachments']) && User::$me->allowedTo('view_attachments', $row['id_board']))
- {
+ if (!empty(Config::$modSettings['attachmentEnable']) && !empty(Config::$modSettings['xmlnews_attachments']) && User::$me->allowedTo('view_attachments', $row['id_board'])) {
$loaded_attachments = Attachment::loadByMsg($row['id_msg'], Attachment::APPROVED_TRUE);
// Sort the attachments by size to make things easier below
- if (!empty($loaded_attachments))
- {
+ if (!empty($loaded_attachments)) {
uasort(
$loaded_attachments,
- function($a, $b)
- {
- if ($a->size == $b->size)
+ function ($a, $b) {
+ if ($a->size == $b->size) {
return 0;
+ }
return ($a->size < $b->size) ? -1 : 1;
- }
+ },
);
- }
- else
- {
+ } else {
$loaded_attachments = null;
}
- }
- else
- {
+ } else {
$loaded_attachments = null;
}
@@ -1303,355 +1255,340 @@ function($a, $b)
$guid = 'tag:' . $this->host . ',' . gmdate('Y-m-d', $row['poster_time']) . ':msg=' . $row['id_msg'];
// Doesn't work as well as news, but it kinda does..
- if ($this->format == 'rss' || $this->format == 'rss2')
- {
+ if ($this->format == 'rss' || $this->format == 'rss2') {
// Only one attachment allowed in RSS.
- if ($loaded_attachments !== null)
- {
+ if ($loaded_attachments !== null) {
$attachment = array_pop($loaded_attachments);
- $enclosure = array(
+ $enclosure = [
'url' => self::fixPossibleUrl(Config::$scripturl . '?action=dlattach;topic=' . $attachment->topic . '.0;attach=' . $attachment->id),
'length' => $attachment->size,
'type' => $attachment->mime_type,
- );
- }
- else
- {
+ ];
+ } else {
$enclosure = null;
}
- $data[] = array(
+ $data[] = [
'tag' => 'item',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
- ),
- array(
+ ],
+ [
'tag' => 'description',
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'author',
'content' => (User::$me->allowedTo('moderate_forum') || (!empty($row['id_member']) && $row['id_member'] == User::$me->id)) ? $row['poster_email'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'category',
'content' => $row['bname'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'comments',
'content' => Config::$scripturl . '?action=post;topic=' . $row['id_topic'] . '.0',
- ),
- array(
+ ],
+ [
'tag' => 'pubDate',
- 'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['poster_time']),
- ),
- array(
+ 'content' => gmdate('D, d M Y H:i:s \\G\\M\\T', $row['poster_time']),
+ ],
+ [
'tag' => 'guid',
'content' => $guid,
- 'attributes' => array(
+ 'attributes' => [
'isPermaLink' => 'false',
- ),
- ),
- array(
+ ],
+ ],
+ [
'tag' => 'enclosure',
'attributes' => $enclosure,
- ),
- ),
- );
- }
- elseif ($this->format == 'rdf')
- {
- $data[] = array(
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'rdf') {
+ $data[] = [
'tag' => 'item',
- 'attributes' => array('rdf:about' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg']),
- 'content' => array(
- array(
+ 'attributes' => ['rdf:about' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg']],
+ 'content' => [
+ [
'tag' => 'dc:format',
'content' => 'text/html',
- ),
- array(
+ ],
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
- ),
- array(
+ ],
+ [
'tag' => 'description',
'content' => $row['body'],
'cdata' => true,
- ),
- ),
- );
- }
- elseif ($this->format == 'atom')
- {
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'atom') {
// Only one attachment allowed
- if (!empty($loaded_attachments))
- {
+ if (!empty($loaded_attachments)) {
$attachment = array_pop($loaded_attachments);
- $enclosure = array(
+ $enclosure = [
'rel' => 'enclosure',
'href' => self::fixPossibleUrl(Config::$scripturl . '?action=dlattach;topic=' . $attachment->topic . '.0;attach=' . $attachment->id),
'length' => $attachment->size,
'type' => $attachment->mime_type,
- );
- }
- else
- {
+ ];
+ } else {
$enclosure = null;
}
- $data[] = array(
+ $data[] = [
'tag' => 'entry',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array(
+ 'attributes' => [
'rel' => 'alternate',
'type' => 'text/html',
'href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
- ),
- ),
- array(
+ ],
+ ],
+ [
'tag' => 'summary',
- 'attributes' => array('type' => 'html'),
+ 'attributes' => ['type' => 'html'],
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'category',
- 'attributes' => array('term' => $row['bname']),
+ 'attributes' => ['term' => $row['bname']],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'author',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'name',
'content' => $row['poster_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'email',
'content' => (User::$me->allowedTo('moderate_forum') || (!empty($row['id_member']) && $row['id_member'] == User::$me->id)) ? $row['poster_email'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'uri',
'content' => !empty($row['id_member']) ? Config::$scripturl . '?action=profile;u=' . $row['id_member'] : null,
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'published',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['poster_time']),
- ),
- array(
+ ],
+ [
'tag' => 'updated',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', empty($row['modified_time']) ? $row['poster_time'] : $row['modified_time']),
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $guid,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'attributes' => $enclosure,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
// A lot of information here. Should be enough to please the rss-ers.
- else
- {
+ else {
Lang::load('Post');
- $attachments = array();
- if (!empty($loaded_attachments))
- {
- foreach ($loaded_attachments as $attachment)
- {
- $attachments[] = array(
+ $attachments = [];
+
+ if (!empty($loaded_attachments)) {
+ foreach ($loaded_attachments as $attachment) {
+ $attachments[] = [
'tag' => 'attachment',
- 'attributes' => array('label' => Lang::$txt['attachment']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['attachment']],
+ 'content' => [
+ [
'tag' => 'id',
'content' => $attachment->id,
- ),
- array(
+ ],
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
- 'content' => preg_replace('~&#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '\\1;', $attachment->name),
- ),
- array(
+ 'attributes' => ['label' => Lang::$txt['name']],
+ 'content' => preg_replace('~&#(\d{1,7}|x[0-9a-fA-F]{1,6});~', '\1;', $attachment->name),
+ ],
+ [
'tag' => 'downloads',
- 'attributes' => array('label' => Lang::$txt['downloads']),
+ 'attributes' => ['label' => Lang::$txt['downloads']],
'content' => $attachment->downloads,
- ),
- array(
+ ],
+ [
'tag' => 'size',
- 'attributes' => array('label' => Lang::$txt['filesize']),
+ 'attributes' => ['label' => Lang::$txt['filesize']],
'content' => ($attachment->size < 1024000) ? round($attachment->size / 1024, 2) . ' ' . Lang::$txt['kilobyte'] : round($attachment->size / 1024 / 1024, 2) . ' ' . Lang::$txt['megabyte'],
- ),
- array(
+ ],
+ [
'tag' => 'byte_size',
- 'attributes' => array('label' => Lang::$txt['filesize']),
+ 'attributes' => ['label' => Lang::$txt['filesize']],
'content' => $attachment->size,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?action=dlattach;topic=' . $attachment->topic . '.0;attach=' . $attachment->id,
- ),
- )
- );
+ ],
+ ],
+ ];
}
- }
- else
- {
+ } else {
$attachments = null;
}
- $data[] = array(
+ $data[] = [
'tag' => 'recent-post', // Hyphen rather than underscore for backward compatibility reasons
- 'attributes' => array('label' => Lang::$txt['post']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['post']],
+ 'content' => [
+ [
'tag' => 'time',
- 'attributes' => array('label' => Lang::$txt['date'], 'UTC' => Time::gmstrftime('%F %T', $row['poster_time'])),
+ 'attributes' => ['label' => Lang::$txt['date'], 'UTC' => Time::gmstrftime('%F %T', $row['poster_time'])],
'content' => Utils::htmlspecialchars(strip_tags(Time::create('@' . $row['poster_time'], new \DateTimeZone(Config::$modSettings['default_timezone']))->format(null, false))),
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_msg'],
- ),
- array(
+ ],
+ [
'tag' => 'subject',
- 'attributes' => array('label' => Lang::$txt['subject']),
+ 'attributes' => ['label' => Lang::$txt['subject']],
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'body',
- 'attributes' => array('label' => Lang::$txt['message']),
+ 'attributes' => ['label' => Lang::$txt['message']],
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'starter',
- 'attributes' => array('label' => Lang::$txt['topic_started']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['topic_started']],
+ 'content' => [
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $row['first_poster_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_first_member'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => !empty($row['id_first_member']) ? array('label' => Lang::$txt['url']) : null,
+ 'attributes' => !empty($row['id_first_member']) ? ['label' => Lang::$txt['url']] : null,
'content' => !empty($row['id_first_member']) ? Config::$scripturl . '?action=profile;u=' . $row['id_first_member'] : '',
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'poster',
- 'attributes' => array('label' => Lang::$txt['author']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['author']],
+ 'content' => [
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $row['poster_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_member'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => !empty($row['id_member']) ? array('label' => Lang::$txt['url']) : null,
+ 'attributes' => !empty($row['id_member']) ? ['label' => Lang::$txt['url']] : null,
'content' => !empty($row['id_member']) ? Config::$scripturl . '?action=profile;u=' . $row['id_member'] : '',
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'topic',
- 'attributes' => array('label' => Lang::$txt['topic']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['topic']],
+ 'content' => [
+ [
'tag' => 'subject',
- 'attributes' => array('label' => Lang::$txt['subject']),
+ 'attributes' => ['label' => Lang::$txt['subject']],
'content' => $row['first_subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_topic'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.new#new',
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'board',
- 'attributes' => array('label' => Lang::$txt['board']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['board']],
+ 'content' => [
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $row['bname'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_board'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?board=' . $row['id_board'] . '.0',
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
- ),
- array(
+ ],
+ [
'tag' => 'attachments',
- 'attributes' => array('label' => Lang::$txt['attachments']),
+ 'attributes' => ['label' => Lang::$txt['attachments']],
'content' => $attachments,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
}
Db::$db->free_result($request);
@@ -1668,298 +1605,287 @@ function($a, $b)
public function getXmlProfile(): array
{
// You must input a valid user, and you must be allowed to view that user's profile.
- if (empty($this->member) || ($this->member != User::$me->id && !User::$me->allowedTo('profile_view')) || (User::load($this->member) === array()))
- {
- return array();
+ if (empty($this->member) || ($this->member != User::$me->id && !User::$me->allowedTo('profile_view')) || (User::load($this->member) === [])) {
+ return [];
}
// Load the member's contextual information! (Including custom fields for our proprietary XML type)
$profile = User::$loaded[$this->member]->format($this->format == 'smf');
// If any control characters slipped in somehow, kill the evil things
- $profile = filter_var($profile, FILTER_CALLBACK, array('options' => '\\SMF\\Utils::cleanXml'));
+ $profile = filter_var($profile, FILTER_CALLBACK, ['options' => '\\SMF\\Utils::cleanXml']);
// Create a GUID for this member using the tag URI scheme
$guid = 'tag:' . $this->host . ',' . gmdate('Y-m-d', $profile['registered_timestamp']) . ':member=' . $profile['id'];
- if ($this->format == 'rss' || $this->format == 'rss2')
- {
- $data[] = array(
+ if ($this->format == 'rss' || $this->format == 'rss2') {
+ $data[] = [
'tag' => 'item',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $profile['name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?action=profile;u=' . $profile['id'],
- ),
- array(
+ ],
+ [
'tag' => 'description',
- 'content' => isset($profile['group']) ? $profile['group'] : $profile['post_group'],
+ 'content' => $profile['group'] ?? $profile['post_group'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'comments',
'content' => Config::$scripturl . '?action=pm;sa=send;u=' . $profile['id'],
- ),
- array(
+ ],
+ [
'tag' => 'pubDate',
- 'content' => gmdate('D, d M Y H:i:s \G\M\T', $profile['registered_timestamp']),
- ),
- array(
+ 'content' => gmdate('D, d M Y H:i:s \\G\\M\\T', $profile['registered_timestamp']),
+ ],
+ [
'tag' => 'guid',
'content' => $guid,
- 'attributes' => array(
+ 'attributes' => [
'isPermaLink' => 'false',
- ),
- ),
- )
- );
- }
- elseif ($this->format == 'rdf')
- {
- $data[] = array(
+ ],
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'rdf') {
+ $data[] = [
'tag' => 'item',
- 'attributes' => array('rdf:about' => Config::$scripturl . '?action=profile;u=' . $profile['id']),
- 'content' => array(
- array(
+ 'attributes' => ['rdf:about' => Config::$scripturl . '?action=profile;u=' . $profile['id']],
+ 'content' => [
+ [
'tag' => 'dc:format',
'content' => 'text/html',
- ),
- array(
+ ],
+ [
'tag' => 'title',
'content' => $profile['name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?action=profile;u=' . $profile['id'],
- ),
- array(
+ ],
+ [
'tag' => 'description',
- 'content' => isset($profile['group']) ? $profile['group'] : $profile['post_group'],
+ 'content' => $profile['group'] ?? $profile['post_group'],
'cdata' => true,
- ),
- )
- );
- }
- elseif ($this->format == 'atom')
- {
- $data[] = array(
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'atom') {
+ $data[] = [
'tag' => 'entry',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $profile['name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array(
+ 'attributes' => [
'rel' => 'alternate',
'type' => 'text/html',
'href' => Config::$scripturl . '?action=profile;u=' . $profile['id'],
- ),
- ),
- array(
+ ],
+ ],
+ [
'tag' => 'summary',
- 'attributes' => array('type' => 'html'),
- 'content' => isset($profile['group']) ? $profile['group'] : $profile['post_group'],
+ 'attributes' => ['type' => 'html'],
+ 'content' => $profile['group'] ?? $profile['post_group'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'author',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'name',
'content' => $profile['name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'email',
'content' => $profile['show_email'] ? $profile['email'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'uri',
'content' => !empty($profile['website']['url']) ? $profile['website']['url'] : Config::$scripturl . '?action=profile;u=' . $profile['id_member'],
'cdata' => !empty($profile['website']['url']),
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'published',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', $profile['registered_timestamp']),
- ),
- array(
+ ],
+ [
'tag' => 'updated',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', $profile['last_login_timestamp']),
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $guid,
- ),
- )
- );
- }
- else
- {
+ ],
+ ],
+ ];
+ } else {
Lang::load('Profile');
- $data = array(
- array(
+ $data = [
+ [
'tag' => 'username',
- 'attributes' => User::$me->is_admin || User::$me->id == $profile['id'] ? array('label' => Lang::$txt['username']) : null,
+ 'attributes' => User::$me->is_admin || User::$me->id == $profile['id'] ? ['label' => Lang::$txt['username']] : null,
'content' => User::$me->is_admin || User::$me->id == $profile['id'] ? $profile['username'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $profile['name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?action=profile;u=' . $profile['id'],
- ),
- array(
+ ],
+ [
'tag' => 'posts',
- 'attributes' => array('label' => Lang::$txt['member_postcount']),
+ 'attributes' => ['label' => Lang::$txt['member_postcount']],
'content' => $profile['posts'],
- ),
- array(
+ ],
+ [
'tag' => 'post-group',
- 'attributes' => array('label' => Lang::$txt['post_based_membergroup']),
+ 'attributes' => ['label' => Lang::$txt['post_based_membergroup']],
'content' => $profile['post_group'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'language',
- 'attributes' => array('label' => Lang::$txt['preferred_language']),
+ 'attributes' => ['label' => Lang::$txt['preferred_language']],
'content' => $profile['language'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'last-login',
- 'attributes' => array('label' => Lang::$txt['lastLoggedIn'], 'UTC' => Time::gmstrftime('%F %T', $profile['last_login_timestamp'])),
+ 'attributes' => ['label' => Lang::$txt['lastLoggedIn'], 'UTC' => Time::gmstrftime('%F %T', $profile['last_login_timestamp'])],
'content' => Time::create('@' . $row['last_login_timestamp'], new \DateTimeZone(Config::$modSettings['default_timezone']))->format(null, false),
- ),
- array(
+ ],
+ [
'tag' => 'registered',
- 'attributes' => array('label' => Lang::$txt['date_registered'], 'UTC' => Time::gmstrftime('%F %T', $profile['registered_timestamp'])),
+ 'attributes' => ['label' => Lang::$txt['date_registered'], 'UTC' => Time::gmstrftime('%F %T', $profile['registered_timestamp'])],
'content' => Time::create('@' . $row['registered_timestamp'], new \DateTimeZone(Config::$modSettings['default_timezone']))->format(null, false),
- ),
- array(
+ ],
+ [
'tag' => 'avatar',
- 'attributes' => !empty($profile['avatar']['url']) ? array('label' => Lang::$txt['personal_picture']) : null,
+ 'attributes' => !empty($profile['avatar']['url']) ? ['label' => Lang::$txt['personal_picture']] : null,
'content' => !empty($profile['avatar']['url']) ? $profile['avatar']['url'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'signature',
- 'attributes' => !empty($profile['signature']) ? array('label' => Lang::$txt['signature']) : null,
+ 'attributes' => !empty($profile['signature']) ? ['label' => Lang::$txt['signature']] : null,
'content' => !empty($profile['signature']) ? $profile['signature'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'blurb',
- 'attributes' => !empty($profile['blurb']) ? array('label' => Lang::$txt['personal_text']) : null,
+ 'attributes' => !empty($profile['blurb']) ? ['label' => Lang::$txt['personal_text']] : null,
'content' => !empty($profile['blurb']) ? $profile['blurb'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'title',
- 'attributes' => !empty($profile['title']) ? array('label' => Lang::$txt['title']) : null,
+ 'attributes' => !empty($profile['title']) ? ['label' => Lang::$txt['title']] : null,
'content' => !empty($profile['title']) ? $profile['title'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'position',
- 'attributes' => !empty($profile['group']) ? array('label' => Lang::$txt['position']) : null,
+ 'attributes' => !empty($profile['group']) ? ['label' => Lang::$txt['position']] : null,
'content' => !empty($profile['group']) ? $profile['group'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'email',
- 'attributes' => !empty($profile['show_email']) || User::$me->is_admin || User::$me->id == $profile['id'] ? array('label' => Lang::$txt['user_email_address']) : null,
+ 'attributes' => !empty($profile['show_email']) || User::$me->is_admin || User::$me->id == $profile['id'] ? ['label' => Lang::$txt['user_email_address']] : null,
'content' => !empty($profile['show_email']) || User::$me->is_admin || User::$me->id == $profile['id'] ? $profile['email'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'website',
- 'attributes' => empty($profile['website']['url']) ? null : array('label' => Lang::$txt['website']),
- 'content' => empty($profile['website']['url']) ? null : array(
- array(
+ 'attributes' => empty($profile['website']['url']) ? null : ['label' => Lang::$txt['website']],
+ 'content' => empty($profile['website']['url']) ? null : [
+ [
'tag' => 'title',
- 'attributes' => !empty($profile['website']['title']) ? array('label' => Lang::$txt['website_title']) : null,
+ 'attributes' => !empty($profile['website']['title']) ? ['label' => Lang::$txt['website_title']] : null,
'content' => !empty($profile['website']['title']) ? $profile['website']['title'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['website_url']),
+ 'attributes' => ['label' => Lang::$txt['website_url']],
'content' => $profile['website']['url'],
'cdata' => true,
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'online',
- 'attributes' => !empty($profile['online']['is_online']) ? array('label' => Lang::$txt['online']) : null,
+ 'attributes' => !empty($profile['online']['is_online']) ? ['label' => Lang::$txt['online']] : null,
'content' => !empty($profile['online']['is_online']) ? 'true' : null,
- ),
- array(
+ ],
+ [
'tag' => 'ip_addresses',
- 'attributes' => array('label' => Lang::$txt['ip_address']),
- 'content' => User::$me->allowedTo('moderate_forum') || User::$me->id == $profile['id'] ? array(
- array(
+ 'attributes' => ['label' => Lang::$txt['ip_address']],
+ 'content' => User::$me->allowedTo('moderate_forum') || User::$me->id == $profile['id'] ? [
+ [
'tag' => 'ip',
- 'attributes' => array('label' => Lang::$txt['most_recent_ip']),
+ 'attributes' => ['label' => Lang::$txt['most_recent_ip']],
'content' => $profile['ip'],
- ),
- array(
+ ],
+ [
'tag' => 'ip2',
'content' => $profile['ip'] != $profile['ip2'] ? $profile['ip2'] : null,
- ),
- ) : null,
- ),
- );
+ ],
+ ] : null,
+ ],
+ ];
- if (!empty($profile['birth_date']) && substr($profile['birth_date'], 0, 4) != '0000' && substr($profile['birth_date'], 0, 4) != '1004')
- {
+ if (!empty($profile['birth_date']) && substr($profile['birth_date'], 0, 4) != '0000' && substr($profile['birth_date'], 0, 4) != '1004') {
list($birth_year, $birth_month, $birth_day) = sscanf($profile['birth_date'], '%d-%d-%d');
$datearray = getdate(time());
$age = $datearray['year'] - $birth_year - (($datearray['mon'] > $birth_month || ($datearray['mon'] == $birth_month && $datearray['mday'] >= $birth_day)) ? 0 : 1);
- $data[] = array(
+ $data[] = [
'tag' => 'age',
- 'attributes' => array('label' => Lang::$txt['age']),
+ 'attributes' => ['label' => Lang::$txt['age']],
'content' => $age,
- );
- $data[] = array(
+ ];
+ $data[] = [
'tag' => 'birthdate',
- 'attributes' => array('label' => Lang::$txt['dob']),
+ 'attributes' => ['label' => Lang::$txt['dob']],
'content' => $profile['birth_date'],
- );
+ ];
}
- if (!empty($profile['custom_fields']))
- {
- foreach ($profile['custom_fields'] as $custom_field)
- {
- $data[] = array(
+ if (!empty($profile['custom_fields'])) {
+ foreach ($profile['custom_fields'] as $custom_field) {
+ $data[] = [
'tag' => $custom_field['col_name'],
- 'attributes' => array('label' => $custom_field['title']),
+ 'attributes' => ['label' => $custom_field['title']],
'content' => $custom_field['simple'],
'cdata' => true,
- );
+ ];
}
}
}
@@ -1978,57 +1904,56 @@ public function getXmlProfile(): array
*/
public function getXmlPosts(): array
{
- if (empty($this->member) || ($this->member != User::$me->id && !User::$me->allowedTo('profile_view')))
- {
- return array();
+ if (empty($this->member) || ($this->member != User::$me->id && !User::$me->allowedTo('profile_view'))) {
+ return [];
}
- $data = array();
+ $data = [];
$show_all = !empty(User::$me->is_admin) || defined('EXPORTING');
- $query_this_message_board = str_replace(array('{query_see_board}', 'b.'), array('{query_see_message_board}', 'm.'), $this->query_this_board);
+ $query_this_message_board = str_replace(['{query_see_board}', 'b.'], ['{query_see_message_board}', 'm.'], $this->query_this_board);
/* MySQL can choke if we use joins in the main query when the user has
* massively long posts. To avoid that, we get the names of the boards
* and the user's displayed name in separate queries.
*/
- $boardnames = array();
- $request = Db::$db->query('', '
- SELECT id_board, name
+ $boardnames = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board, name
FROM {db_prefix}boards',
- array()
+ [],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$boardnames[$row['id_board']] = $row['name'];
}
Db::$db->free_result($request);
- if ($this->member == User::$me->id)
- {
+ if ($this->member == User::$me->id) {
$poster_name = User::$me->name;
- }
- else
- {
- $request = Db::$db->query('', '
- SELECT COALESCE(real_name, member_name) AS poster_name
+ } else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT COALESCE(real_name, member_name) AS poster_name
FROM {db_prefix}members
WHERE id_member = {int:uid}',
- array(
+ [
'uid' => $this->member,
- )
+ ],
);
list($poster_name) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
}
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
m.id_msg, m.id_topic, m.id_board, m.id_member, m.poster_email, m.poster_ip,
m.poster_time, m.subject, m.modified_time, m.modified_name, m.modified_reason, m.body,
m.likes, m.approved, m.smileys_enabled
- FROM {db_prefix}messages AS m' . (Config::$modSettings['postmod_active'] && !$show_all ?'
+ FROM {db_prefix}messages AS m' . (Config::$modSettings['postmod_active'] && !$show_all ? '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)' : '') . '
WHERE m.id_member = {int:uid}
AND m.id_msg > {int:start_after}
@@ -2037,424 +1962,403 @@ public function getXmlPosts(): array
AND t.approved = {int:is_approved}' : '') . '
ORDER BY m.id_msg {raw:ascdesc}
LIMIT {int:limit}',
- array(
+ [
'limit' => $this->limit,
'start_after' => $this->start_after,
'uid' => $this->member,
'is_approved' => 1,
'ascdesc' => !empty($this->ascending) ? 'ASC' : 'DESC',
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Utils::$context['last'] = $row['id_msg'];
// We want a readable version of the IP address
$row['poster_ip'] = new IP($row['poster_ip']);
// If any control characters slipped in somehow, kill the evil things
- $row = filter_var($row, FILTER_CALLBACK, array('options' => '\\SMF\\Utils::cleanXml'));
+ $row = filter_var($row, FILTER_CALLBACK, ['options' => '\\SMF\\Utils::cleanXml']);
// If using our own format, we want both the raw and the parsed content.
$row[$this->format === 'smf' ? 'body_html' : 'body'] = BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], $row['id_msg']);
// Do we want to include any attachments?
- if (!empty(Config::$modSettings['attachmentEnable']) && !empty(Config::$modSettings['xmlnews_attachments']))
- {
+ if (!empty(Config::$modSettings['attachmentEnable']) && !empty(Config::$modSettings['xmlnews_attachments'])) {
$loaded_attachments = Attachment::loadByMsg($row['id_msg'], Attachment::APPROVED_TRUE);
// Sort the attachments by size to make things easier below
- if (!empty($loaded_attachments))
- {
+ if (!empty($loaded_attachments)) {
uasort(
$loaded_attachments,
- function($a, $b)
- {
- if ($a->size == $b->size)
- return 0;
+ function ($a, $b) {
+ if ($a->size == $b->size) {
+ return 0;
+ }
- return ($a->size < $b->size) ? -1 : 1;
- }
+ return ($a->size < $b->size) ? -1 : 1;
+ },
);
- }
- else
- {
+ } else {
$loaded_attachments = null;
}
- }
- else
- {
+ } else {
$loaded_attachments = null;
}
// Create a GUID for this post using the tag URI scheme
$guid = 'tag:' . $this->host . ',' . gmdate('Y-m-d', $row['poster_time']) . ':msg=' . $row['id_msg'];
- if ($this->format == 'rss' || $this->format == 'rss2')
- {
+ if ($this->format == 'rss' || $this->format == 'rss2') {
// Only one attachment allowed in RSS.
- if ($loaded_attachments !== null)
- {
+ if ($loaded_attachments !== null) {
$attachment = array_pop($loaded_attachments);
- $enclosure = array(
+ $enclosure = [
'url' => self::fixPossibleUrl(Config::$scripturl . '?action=dlattach;topic=' . $attachment->topic . '.0;attach=' . $attachment->id),
'length' => $attachment->size,
'type' => $attachment->mime_type,
- );
- }
- else
- {
+ ];
+ } else {
$enclosure = null;
}
- $data[] = array(
+ $data[] = [
'tag' => 'item',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?msg=' . $row['id_msg'],
- ),
- array(
+ ],
+ [
'tag' => 'description',
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'author',
'content' => (User::$me->allowedTo('moderate_forum') || ($row['id_member'] == User::$me->id)) ? $row['poster_email'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'category',
'content' => $boardnames[$row['id_board']],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'comments',
'content' => Config::$scripturl . '?action=post;topic=' . $row['id_topic'] . '.0',
- ),
- array(
+ ],
+ [
'tag' => 'pubDate',
- 'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['poster_time']),
- ),
- array(
+ 'content' => gmdate('D, d M Y H:i:s \\G\\M\\T', $row['poster_time']),
+ ],
+ [
'tag' => 'guid',
'content' => $guid,
- 'attributes' => array(
+ 'attributes' => [
'isPermaLink' => 'false',
- ),
- ),
- array(
+ ],
+ ],
+ [
'tag' => 'enclosure',
'attributes' => $enclosure,
- ),
- ),
- );
- }
- elseif ($this->format == 'rdf')
- {
- $data[] = array(
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'rdf') {
+ $data[] = [
'tag' => 'item',
- 'attributes' => array('rdf:about' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg']),
- 'content' => array(
- array(
+ 'attributes' => ['rdf:about' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg']],
+ 'content' => [
+ [
'tag' => 'dc:format',
'content' => 'text/html',
- ),
- array(
+ ],
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?msg=' . $row['id_msg'],
- ),
- array(
+ ],
+ [
'tag' => 'description',
'content' => $row['body'],
'cdata' => true,
- ),
- ),
- );
- }
- elseif ($this->format == 'atom')
- {
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'atom') {
// Only one attachment allowed
- if (!empty($loaded_attachments))
- {
+ if (!empty($loaded_attachments)) {
$attachment = array_pop($loaded_attachments);
- $enclosure = array(
+ $enclosure = [
'rel' => 'enclosure',
'href' => self::fixPossibleUrl(Config::$scripturl . '?action=dlattach;topic=' . $attachment->topic . '.0;attach=' . $attachment->id),
'length' => $attachment->size,
'type' => $attachment->mime_type,
- );
- }
- else
- {
+ ];
+ } else {
$enclosure = null;
}
- $data[] = array(
+ $data[] = [
'tag' => 'entry',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array(
+ 'attributes' => [
'rel' => 'alternate',
'type' => 'text/html',
'href' => Config::$scripturl . '?msg=' . $row['id_msg'],
- ),
- ),
- array(
+ ],
+ ],
+ [
'tag' => 'summary',
- 'attributes' => array('type' => 'html'),
+ 'attributes' => ['type' => 'html'],
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'author',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'name',
'content' => $poster_name,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'email',
'content' => (User::$me->allowedTo('moderate_forum') || ($row['id_member'] == User::$me->id)) ? $row['poster_email'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'uri',
'content' => !empty($row['id_member']) ? Config::$scripturl . '?action=profile;u=' . $row['id_member'] : null,
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'published',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['poster_time']),
- ),
- array(
+ ],
+ [
'tag' => 'updated',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', empty($row['modified_time']) ? $row['poster_time'] : $row['modified_time']),
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $guid,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'attributes' => $enclosure,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
// A lot of information here. Should be enough to please the rss-ers.
- else
- {
+ else {
Lang::load('Post');
- $attachments = array();
- if (!empty($loaded_attachments))
- {
- foreach ($loaded_attachments as $attachment)
- {
- $attachments[] = array(
+ $attachments = [];
+
+ if (!empty($loaded_attachments)) {
+ foreach ($loaded_attachments as $attachment) {
+ $attachments[] = [
'tag' => 'attachment',
- 'attributes' => array('label' => Lang::$txt['attachment']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['attachment']],
+ 'content' => [
+ [
'tag' => 'id',
'content' => $attachment->id,
- ),
- array(
+ ],
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
- 'content' => preg_replace('~&#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '\\1;', $attachment->name),
- ),
- array(
+ 'attributes' => ['label' => Lang::$txt['name']],
+ 'content' => preg_replace('~&#(\d{1,7}|x[0-9a-fA-F]{1,6});~', '\1;', $attachment->name),
+ ],
+ [
'tag' => 'downloads',
- 'attributes' => array('label' => Lang::$txt['downloads']),
+ 'attributes' => ['label' => Lang::$txt['downloads']],
'content' => $attachment->downloads,
- ),
- array(
+ ],
+ [
'tag' => 'size',
- 'attributes' => array('label' => Lang::$txt['filesize']),
+ 'attributes' => ['label' => Lang::$txt['filesize']],
'content' => ($attachment->size < 1024000) ? round($attachment->size / 1024, 2) . ' ' . Lang::$txt['kilobyte'] : round($attachment->size / 1024 / 1024, 2) . ' ' . Lang::$txt['megabyte'],
- ),
- array(
+ ],
+ [
'tag' => 'byte_size',
- 'attributes' => array('label' => Lang::$txt['filesize']),
+ 'attributes' => ['label' => Lang::$txt['filesize']],
'content' => $attachment->size,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?action=dlattach;topic=' . $attachment->topic . '.0;attach=' . $attachment->id,
- ),
- array(
+ ],
+ [
'tag' => 'approval_status',
- 'attributes' => $show_all ? array('label' => Lang::$txt['approval_status']) : null,
+ 'attributes' => $show_all ? ['label' => Lang::$txt['approval_status']] : null,
'content' => $show_all ? $attachment->approved : null,
- ),
- )
- );
+ ],
+ ],
+ ];
}
- }
- else
- {
+ } else {
$attachments = null;
}
- $data[] = array(
+ $data[] = [
'tag' => 'member_post',
- 'attributes' => array('label' => Lang::$txt['post']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['post']],
+ 'content' => [
+ [
'tag' => 'id',
'content' => $row['id_msg'],
- ),
- array(
+ ],
+ [
'tag' => 'subject',
- 'attributes' => array('label' => Lang::$txt['subject']),
+ 'attributes' => ['label' => Lang::$txt['subject']],
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'body',
- 'attributes' => array('label' => Lang::$txt['message']),
+ 'attributes' => ['label' => Lang::$txt['message']],
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'body_html',
- 'attributes' => array('label' => Lang::$txt['html']),
+ 'attributes' => ['label' => Lang::$txt['html']],
'content' => $row['body_html'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'poster',
- 'attributes' => array('label' => Lang::$txt['author']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['author']],
+ 'content' => [
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $poster_name,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_member'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- ),
- array(
+ ],
+ [
'tag' => 'email',
- 'attributes' => (User::$me->allowedTo('moderate_forum') || $row['id_member'] == User::$me->id) ? array('label' => Lang::$txt['user_email_address']) : null,
+ 'attributes' => (User::$me->allowedTo('moderate_forum') || $row['id_member'] == User::$me->id) ? ['label' => Lang::$txt['user_email_address']] : null,
'content' => (User::$me->allowedTo('moderate_forum') || $row['id_member'] == User::$me->id) ? $row['poster_email'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'ip',
- 'attributes' => (User::$me->allowedTo('moderate_forum') || $row['id_member'] == User::$me->id) ? array('label' => Lang::$txt['ip']) : null,
+ 'attributes' => (User::$me->allowedTo('moderate_forum') || $row['id_member'] == User::$me->id) ? ['label' => Lang::$txt['ip']] : null,
'content' => (User::$me->allowedTo('moderate_forum') || $row['id_member'] == User::$me->id) ? $row['poster_ip'] : null,
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'topic',
- 'attributes' => array('label' => Lang::$txt['topic']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['topic']],
+ 'content' => [
+ [
'tag' => 'id',
'content' => $row['id_topic'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0',
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'board',
- 'attributes' => array('label' => Lang::$txt['board']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['board']],
+ 'content' => [
+ [
'tag' => 'id',
'content' => $row['id_board'],
- ),
- array(
+ ],
+ [
'tag' => 'name',
'content' => $boardnames[$row['id_board']],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?board=' . $row['id_board'] . '.0',
- ),
- ),
- ),
- array(
+ ],
+ ],
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?msg=' . $row['id_msg'],
- ),
- array(
+ ],
+ [
'tag' => 'time',
- 'attributes' => array('label' => Lang::$txt['date'], 'UTC' => Time::gmstrftime('%F %T', $row['poster_time'])),
+ 'attributes' => ['label' => Lang::$txt['date'], 'UTC' => Time::gmstrftime('%F %T', $row['poster_time'])],
'content' => Utils::htmlspecialchars(strip_tags(Time::create('@' . $row['poster_time'], new \DateTimeZone(Config::$modSettings['default_timezone']))->format(null, false))),
- ),
- array(
+ ],
+ [
'tag' => 'modified_time',
- 'attributes' => !empty($row['modified_time']) ? array('label' => Lang::$txt['modified_time'], 'UTC' => Time::gmstrftime('%F %T', $row['modified_time'])) : null,
+ 'attributes' => !empty($row['modified_time']) ? ['label' => Lang::$txt['modified_time'], 'UTC' => Time::gmstrftime('%F %T', $row['modified_time'])] : null,
'content' => !empty($row['modified_time']) ? Utils::htmlspecialchars(strip_tags(Time::create('@' . $row['modified_time'], new \DateTimeZone(Config::$modSettings['default_timezone']))->format(null, false))) : null,
- ),
- array(
+ ],
+ [
'tag' => 'modified_by',
- 'attributes' => !empty($row['modified_name']) ? array('label' => Lang::$txt['modified_by']) : null,
+ 'attributes' => !empty($row['modified_name']) ? ['label' => Lang::$txt['modified_by']] : null,
'content' => !empty($row['modified_name']) ? $row['modified_name'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'modified_reason',
- 'attributes' => !empty($row['modified_reason']) ? array('label' => Lang::$txt['reason_for_edit']) : null,
+ 'attributes' => !empty($row['modified_reason']) ? ['label' => Lang::$txt['reason_for_edit']] : null,
'content' => !empty($row['modified_reason']) ? $row['modified_reason'] : null,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'likes',
- 'attributes' => array('label' => Lang::$txt['likes']),
+ 'attributes' => ['label' => Lang::$txt['likes']],
'content' => $row['likes'],
- ),
- array(
+ ],
+ [
'tag' => 'approval_status',
- 'attributes' => $show_all ? array('label' => Lang::$txt['approval_status']) : null,
+ 'attributes' => $show_all ? ['label' => Lang::$txt['approval_status']] : null,
'content' => $show_all ? $row['approved'] : null,
- ),
- array(
+ ],
+ [
'tag' => 'attachments',
- 'attributes' => array('label' => Lang::$txt['attachments']),
+ 'attributes' => ['label' => Lang::$txt['attachments']],
'content' => $attachments,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
}
Db::$db->free_result($request);
@@ -2471,10 +2375,11 @@ function($a, $b)
public function getXmlPMs(): array
{
// Personal messages are supposed to be private
- if (empty($this->member) || ($this->member != User::$me->id))
- return array();
+ if (empty($this->member) || ($this->member != User::$me->id)) {
+ return [];
+ }
- $data = array();
+ $data = [];
// Use a private-use Unicode character to separate member names.
// This ensures that the separator will not occur in the names themselves.
@@ -2482,10 +2387,11 @@ public function getXmlPMs(): array
$select_id_members_to = Db::$db->title === POSTGRE_TITLE ? "string_agg(pmr.id_member::text, ',')" : 'GROUP_CONCAT(pmr.id_member)';
- $select_to_names = Db::$db->title === POSTGRE_TITLE ? "string_agg(COALESCE(mem.real_name, mem.member_name), '$separator')" : "GROUP_CONCAT(COALESCE(mem.real_name, mem.member_name) SEPARATOR '$separator')";
+ $select_to_names = Db::$db->title === POSTGRE_TITLE ? "string_agg(COALESCE(mem.real_name, mem.member_name), '{$separator}')" : "GROUP_CONCAT(COALESCE(mem.real_name, mem.member_name) SEPARATOR '{$separator}')";
- $request = Db::$db->query('', '
- SELECT pm.id_pm, pm.msgtime, pm.subject, pm.body, pm.id_member_from, nis.from_name, nis.id_members_to, nis.to_names
+ $request = Db::$db->query(
+ '',
+ 'SELECT pm.id_pm, pm.msgtime, pm.subject, pm.body, pm.id_member_from, nis.from_name, nis.id_members_to, nis.to_names
FROM {db_prefix}personal_messages AS pm
INNER JOIN
(
@@ -2504,20 +2410,20 @@ public function getXmlPMs(): array
LIMIT {int:limit}
) AS nis ON pm.id_pm = nis.id_pm
ORDER BY pm.id_pm {raw:ascdesc}',
- array(
+ [
'limit' => $this->limit,
'start_after' => $this->start_after,
'uid' => $this->member,
'not_deleted' => 0,
'ascdesc' => !empty($this->ascending) ? 'ASC' : 'DESC',
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$this->start_after = $row['id_pm'];
// If any control characters slipped in somehow, kill the evil things
- $row = filter_var($row, FILTER_CALLBACK, array('options' => '\\SMF\\Utils::cleanXml'));
+ $row = filter_var($row, FILTER_CALLBACK, ['options' => '\\SMF\\Utils::cleanXml']);
// If using our own format, we want both the raw and the parsed content.
$row[$this->format === 'smf' ? 'body_html' : 'body'] = BBCodeParser::load()->parse($row['body']);
@@ -2527,218 +2433,208 @@ public function getXmlPMs(): array
// Create a GUID for this post using the tag URI scheme
$guid = 'tag:' . $this->host . ',' . gmdate('Y-m-d', $row['msgtime']) . ':pm=' . $row['id_pm'];
- if ($this->format == 'rss' || $this->format == 'rss2')
- {
- $item = array(
+ if ($this->format == 'rss' || $this->format == 'rss2') {
+ $item = [
'tag' => 'item',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'guid',
'content' => $guid,
- 'attributes' => array(
+ 'attributes' => [
'isPermaLink' => 'false',
- ),
- ),
- array(
+ ],
+ ],
+ [
'tag' => 'pubDate',
- 'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['msgtime']),
- ),
- array(
+ 'content' => gmdate('D, d M Y H:i:s \\G\\M\\T', $row['msgtime']),
+ ],
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'description',
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'smf:sender',
// This technically violates the RSS spec, but meh...
'content' => $row['from_name'],
'cdata' => true,
- ),
- ),
- );
+ ],
+ ],
+ ];
- foreach ($recipients as $recipient_id => $recipient_name)
- {
- $item['content'][] = array(
+ foreach ($recipients as $recipient_id => $recipient_name) {
+ $item['content'][] = [
'tag' => 'smf:recipient',
'content' => $recipient_name,
'cdata' => true,
- );
+ ];
}
$data[] = $item;
- }
- elseif ($this->format == 'rdf')
- {
- $data[] = array(
+ } elseif ($this->format == 'rdf') {
+ $data[] = [
'tag' => 'item',
- 'attributes' => array('rdf:about' => Config::$scripturl . '?action=pm#msg' . $row['id_pm']),
- 'content' => array(
- array(
+ 'attributes' => ['rdf:about' => Config::$scripturl . '?action=pm#msg' . $row['id_pm']],
+ 'content' => [
+ [
'tag' => 'dc:format',
'content' => 'text/html',
- ),
- array(
+ ],
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'link',
'content' => Config::$scripturl . '?action=pm#msg' . $row['id_pm'],
- ),
- array(
+ ],
+ [
'tag' => 'description',
'content' => $row['body'],
'cdata' => true,
- ),
- ),
- );
- }
- elseif ($this->format == 'atom')
- {
- $item = array(
+ ],
+ ],
+ ];
+ } elseif ($this->format == 'atom') {
+ $item = [
'tag' => 'entry',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'id',
'content' => $guid,
- ),
- array(
+ ],
+ [
'tag' => 'updated',
'content' => Time::gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['msgtime']),
- ),
- array(
+ ],
+ [
'tag' => 'title',
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'content',
- 'attributes' => array('type' => 'html'),
+ 'attributes' => ['type' => 'html'],
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'author',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'name',
'content' => $row['from_name'],
'cdata' => true,
- ),
- ),
- ),
- ),
- );
-
- foreach ($recipients as $recipient_id => $recipient_name)
- {
- $item['content'][] = array(
+ ],
+ ],
+ ],
+ ],
+ ];
+
+ foreach ($recipients as $recipient_id => $recipient_name) {
+ $item['content'][] = [
'tag' => 'contributor',
- 'content' => array(
- array(
+ 'content' => [
+ [
'tag' => 'smf:role',
'content' => 'recipient',
- ),
- array(
+ ],
+ [
'tag' => 'name',
'content' => $recipient_name,
'cdata' => true,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
$data[] = $item;
- }
- else
- {
+ } else {
Lang::load('PersonalMessage');
- $item = array(
+ $item = [
'tag' => 'personal_message',
- 'attributes' => array('label' => Lang::$txt['pm']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['pm']],
+ 'content' => [
+ [
'tag' => 'id',
'content' => $row['id_pm'],
- ),
- array(
+ ],
+ [
'tag' => 'sent_date',
- 'attributes' => array('label' => Lang::$txt['date'], 'UTC' => Time::gmstrftime('%F %T', $row['msgtime'])),
+ 'attributes' => ['label' => Lang::$txt['date'], 'UTC' => Time::gmstrftime('%F %T', $row['msgtime'])],
'content' => Utils::htmlspecialchars(strip_tags(Time::create('@' . $row['msgtime'], new \DateTimeZone(Config::$modSettings['default_timezone']))->format(null, false))),
- ),
- array(
+ ],
+ [
'tag' => 'subject',
- 'attributes' => array('label' => Lang::$txt['subject']),
+ 'attributes' => ['label' => Lang::$txt['subject']],
'content' => $row['subject'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'body',
- 'attributes' => array('label' => Lang::$txt['message']),
+ 'attributes' => ['label' => Lang::$txt['message']],
'content' => $row['body'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'body_html',
- 'attributes' => array('label' => Lang::$txt['html']),
+ 'attributes' => ['label' => Lang::$txt['html']],
'content' => $row['body_html'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'sender',
- 'attributes' => array('label' => Lang::$txt['author']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['author']],
+ 'content' => [
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $row['from_name'],
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $row['id_member_from'],
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?action=profile;u=' . $row['id_member_from'],
- ),
- ),
- ),
- ),
- );
-
- foreach ($recipients as $recipient_id => $recipient_name)
- {
- $item['content'][] = array(
+ ],
+ ],
+ ],
+ ],
+ ];
+
+ foreach ($recipients as $recipient_id => $recipient_name) {
+ $item['content'][] = [
'tag' => 'recipient',
- 'attributes' => array('label' => Lang::$txt['recipient']),
- 'content' => array(
- array(
+ 'attributes' => ['label' => Lang::$txt['recipient']],
+ 'content' => [
+ [
'tag' => 'name',
- 'attributes' => array('label' => Lang::$txt['name']),
+ 'attributes' => ['label' => Lang::$txt['name']],
'content' => $recipient_name,
'cdata' => true,
- ),
- array(
+ ],
+ [
'tag' => 'id',
'content' => $recipient_id,
- ),
- array(
+ ],
+ [
'tag' => 'link',
- 'attributes' => array('label' => Lang::$txt['url']),
+ 'attributes' => ['label' => Lang::$txt['url']],
'content' => Config::$scripturl . '?action=profile;u=' . $recipient_id,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
$data[] = $item;
@@ -2760,8 +2656,9 @@ public function getXmlPMs(): array
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -2799,25 +2696,24 @@ public static function build(string $format, array $data, array $metadata, strin
$namespaces['smf']['smf'] = sprintf($namespaces['smf']['smf'], $subaction);
// These sub-actions need the SMF namespace in other feed formats.
- if (in_array($subaction, array('profile', 'posts', 'personal_messages')))
- {
+ if (in_array($subaction, ['profile', 'posts', 'personal_messages'])) {
$namespaces['rss']['smf'] = $namespaces['smf']['smf'];
$namespaces['rss2']['smf'] = $namespaces['smf']['smf'];
$namespaces['atom']['smf'] = $namespaces['smf']['smf'];
}
// Allow mods to add extra feed-level tags to the feed/channel
- $extraFeedTags = array(
- 'rss' => array(),
- 'rss2' => array(),
- 'atom' => array(),
- 'rdf' => array(),
- 'smf' => array(),
- );
+ $extraFeedTags = [
+ 'rss' => [],
+ 'rss2' => [],
+ 'atom' => [],
+ 'rdf' => [],
+ 'smf' => [],
+ ];
// Allow mods to specify any keys that need special handling
- $forceCdataKeys = array();
- $nsKeys = array();
+ $forceCdataKeys = [];
+ $nsKeys = [];
// Maybe someone needs to insert a DOCTYPE declaration?
$doctype = '';
@@ -2827,44 +2723,45 @@ public static function build(string $format, array $data, array $metadata, strin
// If mods want to do something with this feed, let them do that now.
// Provide the feed's data, metadata, namespaces, extra feed-level tags, keys that need special handling, the feed format, and the requested subaction.
- IntegrationHook::call('integrate_xml_data', array(&$data, &$metadata, &$namespaces, &$extraFeedTags, &$forceCdataKeys, &$nsKeys, $format, $subaction, &$doctype));
+ IntegrationHook::call('integrate_xml_data', [&$data, &$metadata, &$namespaces, &$extraFeedTags, &$forceCdataKeys, &$nsKeys, $format, $subaction, &$doctype]);
// These can't be empty.
- foreach (array('title', 'desc', 'source', 'self') as $mkey)
+ foreach (['title', 'desc', 'source', 'self'] as $mkey) {
$metadata[$mkey] = !empty($metadata[$mkey]) ? $metadata[$mkey] : $orig_metadata[$mkey];
+ }
// Sanitize feed metadata values.
- foreach ($metadata as $mkey => $mvalue)
+ foreach ($metadata as $mkey => $mvalue) {
$metadata[$mkey] = self::cdataParse(self::fixPossibleUrl($mvalue));
+ }
$ns_string = '';
- if (!empty($namespaces[$format]))
- {
- foreach ($namespaces[$format] as $nsprefix => $nsurl)
- {
+
+ if (!empty($namespaces[$format])) {
+ foreach ($namespaces[$format] as $nsprefix => $nsurl) {
$ns_string .= ' xmlns' . ($nsprefix !== '' ? ':' : '') . $nsprefix . '="' . $nsurl . '"';
}
}
- $i = in_array($format, array('atom', 'smf')) ? 1 : 2;
+ $i = in_array($format, ['atom', 'smf']) ? 1 : 2;
$extraFeedTags_string = '';
- if (!empty($extraFeedTags[$format]))
- {
+
+ if (!empty($extraFeedTags[$format])) {
$indent = str_repeat("\t", $i);
- foreach ($extraFeedTags[$format] as $extraTag)
+ foreach ($extraFeedTags[$format] as $extraTag) {
$extraFeedTags_string .= "\n" . $indent . $extraTag;
+ }
}
- Utils::$context['feed'] = array();
+ Utils::$context['feed'] = [];
// First, output the xml header.
Utils::$context['feed']['header'] = '' . ($doctype !== '' ? "\n" . trim($doctype) : '');
// Are we outputting an rss feed or one with more information?
- if ($format == 'rss' || $format == 'rss2')
- {
+ if ($format == 'rss' || $format == 'rss2') {
// Start with an RSS 2.0 header.
Utils::$context['feed']['header'] .= '
@@ -2873,26 +2770,30 @@ public static function build(string $format, array $data, array $metadata, strin
' . $metadata['source'] . '
' . $metadata['desc'] . '';
- if (!empty($metadata['icon']))
+ if (!empty($metadata['icon'])) {
Utils::$context['feed']['header'] .= '
' . $metadata['icon'] . '
' . $metadata['title'] . '
' . $metadata['source'] . '
';
+ }
- if (!empty($metadata['rights']))
+ if (!empty($metadata['rights'])) {
Utils::$context['feed']['header'] .= '
' . $metadata['rights'] . '';
+ }
- if (!empty($metadata['language']))
+ if (!empty($metadata['language'])) {
Utils::$context['feed']['header'] .= '
' . $metadata['language'] . '';
+ }
// RSS2 calls for this.
- if ($format == 'rss2')
+ if ($format == 'rss2') {
Utils::$context['feed']['header'] .= '
';
+ }
Utils::$context['feed']['header'] .= $extraFeedTags_string;
@@ -2903,9 +2804,7 @@ public static function build(string $format, array $data, array $metadata, strin
Utils::$context['feed']['footer'] = '
';
- }
- elseif ($format == 'atom')
- {
+ } elseif ($format == 'atom') {
Utils::$context['feed']['header'] .= '
' . $metadata['title'] . '
@@ -2916,19 +2815,22 @@ public static function build(string $format, array $data, array $metadata, strin
' . $metadata['desc'] . '
SMF';
- if (!empty($metadata['icon']))
+ if (!empty($metadata['icon'])) {
Utils::$context['feed']['header'] .= '
' . $metadata['icon'] . '';
+ }
- if (!empty($metadata['author']))
+ if (!empty($metadata['author'])) {
Utils::$context['feed']['header'] .= '
' . $metadata['author'] . '
';
+ }
- if (!empty($metadata['rights']))
+ if (!empty($metadata['rights'])) {
Utils::$context['feed']['header'] .= '
' . $metadata['rights'] . '';
+ }
Utils::$context['feed']['header'] .= $extraFeedTags_string;
@@ -2936,9 +2838,7 @@ public static function build(string $format, array $data, array $metadata, strin
Utils::$context['feed']['footer'] = '
';
- }
- elseif ($format == 'rdf')
- {
+ } elseif ($format == 'rdf') {
Utils::$context['feed']['header'] .= '
@@ -2952,14 +2852,12 @@ public static function build(string $format, array $data, array $metadata, strin
';
- foreach ($data as $item)
- {
+ foreach ($data as $item) {
$link = array_filter(
$item['content'],
- function($e)
- {
+ function ($e) {
return ($e['tag'] == 'link');
- }
+ },
);
$link = array_pop($link);
@@ -2978,8 +2876,7 @@ function($e)
';
}
// Otherwise, we're using our proprietary formats - they give more data, though.
- else
- {
+ else {
Utils::$context['feed']['header'] .= '
';
@@ -3007,57 +2904,52 @@ function($e)
public static function cdataParse(string $data, string $ns = '', bool $force = false): string
{
// Do we even need to do this?
- if (strpbrk($data, '<>&') == false && $force !== true)
+ if (strpbrk($data, '<>&') == false && $force !== true) {
return $data;
+ }
$cdata = '', ']]]]><[CDATA[>', $data);
}
// Looks like we need to do it the hard way.
- else
- {
- for ($pos = 0, $n = strlen($data); $pos < $n; null)
- {
- $positions = array(
+ else {
+ for ($pos = 0, $n = strlen($data); $pos < $n; null) {
+ $positions = [
strpos($data, ']]>', $pos),
strpos($data, '<', $pos),
- );
+ ];
$positions = array_filter($positions, 'is_int');
$old = $pos;
$pos = empty($positions) ? $n : min($positions);
- if ($pos - $old > 0)
+ if ($pos - $old > 0) {
$cdata .= substr($data, $old, $pos - $old);
+ }
- if ($pos >= $n)
+ if ($pos >= $n) {
break;
+ }
- if (substr($data, $pos, 1) == '<')
- {
+ if (substr($data, $pos, 1) == '<') {
$pos2 = strpos($data, '>', $pos);
- if ($pos2 === false)
+ if ($pos2 === false) {
$pos2 = $n;
+ }
- if (substr($data, $pos + 1, 1) == '/')
- {
+ if (substr($data, $pos + 1, 1) == '/') {
$cdata .= ']]>' . $ns . ':' . substr($data, $pos + 2, $pos2 - $pos - 1) . '<' . $ns . ':' . substr($data, $pos + 1, $pos2 - $pos) . '')
- {
+ } elseif (substr($data, $pos, 3) == ']]>') {
$cdata .= ']]]]>';
$pos = $pos + 3;
}
@@ -3066,7 +2958,7 @@ public static function cdataParse(string $data, string $ns = '', bool $force = f
$cdata .= ']]>';
- return strtr($cdata, array('' => ''));
+ return strtr($cdata, ['' => '']);
}
/******************
@@ -3075,16 +2967,11 @@ public static function cdataParse(string $data, string $ns = '', bool $force = f
protected function setSubaction($subaction)
{
- if (isset($subaction) && isset(self::$subactions[$subaction]))
- {
+ if (isset($subaction, self::$subactions[$subaction])) {
$this->subaction = $subaction;
- }
- elseif (isset($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
- {
+ } elseif (isset($_GET['sa'], self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
- }
- else
- {
+ } else {
$this->subaction = array_key_first(self::$subactions);
}
}
@@ -3092,23 +2979,19 @@ protected function setSubaction($subaction)
protected function setMember($member)
{
// Member ID was passed to the constructor.
- if (isset($member))
- {
+ if (isset($member)) {
$this->member = $member;
}
// Member ID was set via Utils::$context.
- elseif (isset(Utils::$context['xmlnews_uid']))
- {
+ elseif (isset(Utils::$context['xmlnews_uid'])) {
$this->member = Utils::$context['xmlnews_uid'];
}
// Member ID was set via URL parameter.
- elseif (isset($_GET['u']))
- {
+ elseif (isset($_GET['u'])) {
$this->member = $_GET['u'];
}
// Default to current user.
- else
- {
+ else {
$this->member = User::$me->id;
}
@@ -3121,20 +3004,19 @@ protected function setMember($member)
protected function setFormat()
{
- if (isset($_GET['type']) && isset(self::XML_NAMESPACES[$_GET['type']]))
+ if (isset($_GET['type'], self::XML_NAMESPACES[$_GET['type']])) {
$this->format = $_GET['type'];
+ }
}
protected function setlimit()
{
// Limit was set via Utils::$context.
- if (isset(Utils::$context['xmlnews_limit']))
- {
+ if (isset(Utils::$context['xmlnews_limit'])) {
$this->limit = Utils::$context['xmlnews_limit'];
}
// Limit was set via URL parameter.
- elseif (isset($_GET['limit']))
- {
+ elseif (isset($_GET['limit'])) {
$this->limit = $_GET['limit'];
}
@@ -3148,14 +3030,14 @@ protected function setlimit()
protected function checkEnabled(): void
{
// Users can always export their own profile data.
- if (in_array($this->subaction, array('profile', 'posts', 'personal_messages')) && $this->member == User::$me->id && !User::$me->is_guest)
- {
+ if (in_array($this->subaction, ['profile', 'posts', 'personal_messages']) && $this->member == User::$me->id && !User::$me->is_guest) {
return;
}
// If it's not enabled, die.
- if (empty(Config::$modSettings['xmlnews_enable']))
+ if (empty(Config::$modSettings['xmlnews_enable'])) {
Utils::obExit(false);
+ }
}
/*************************
@@ -3175,21 +3057,22 @@ protected function checkEnabled(): void
* @param array $forceCdataKeys A list of keys on which to force cdata wrapping (used by mods, maybe)
* @param array $nsKeys Key-value pairs of namespace prefixes to pass to self::cdataParse() (used by mods, maybe)
*/
- protected static function dumpTags(array $data, int $i, string $format = '', array $forceCdataKeys = array(), array $nsKeys = array()): void
+ protected static function dumpTags(array $data, int $i, string $format = '', array $forceCdataKeys = [], array $nsKeys = []): void
{
- if (empty(Utils::$context['feed']['items']))
+ if (empty(Utils::$context['feed']['items'])) {
Utils::$context['feed']['items'] = '';
+ }
// For every array in the data...
- foreach ($data as $element)
- {
- $key = isset($element['tag']) ? $element['tag'] : null;
- $val = isset($element['content']) ? $element['content'] : null;
- $attrs = isset($element['attributes']) ? $element['attributes'] : null;
+ foreach ($data as $element) {
+ $key = $element['tag'] ?? null;
+ $val = $element['content'] ?? null;
+ $attrs = $element['attributes'] ?? null;
// Skip it, it's been set to null.
- if ($key === null || ($val === null && $attrs === null))
+ if ($key === null || ($val === null && $attrs === null)) {
continue;
+ }
$forceCdata = in_array($key, $forceCdataKeys);
$ns = !empty($nsKeys[$key]) ? $nsKeys[$key] : '';
@@ -3200,38 +3083,30 @@ protected static function dumpTags(array $data, int $i, string $format = '', arr
// Beginning tag.
Utils::$context['feed']['items'] .= '<' . $key;
- if (!empty($attrs))
- {
- foreach ($attrs as $attr_key => $attr_value)
- {
+ if (!empty($attrs)) {
+ foreach ($attrs as $attr_key => $attr_value) {
Utils::$context['feed']['items'] .= ' ' . $attr_key . '="' . self::fixPossibleUrl($attr_value) . '"';
}
}
// If it's empty, simply output an empty element.
- if (empty($val) && $val !== '0' && $val !== 0)
- {
+ if (empty($val) && $val !== '0' && $val !== 0) {
Utils::$context['feed']['items'] .= ' />';
- }
- else
- {
+ } else {
Utils::$context['feed']['items'] .= '>';
// The element's value.
- if (is_array($val))
- {
+ if (is_array($val)) {
// An array. Dump it, and then indent the tag.
self::dumpTags($val, $i + 1, $format, $forceCdataKeys, $nsKeys);
Utils::$context['feed']['items'] .= "\n" . str_repeat("\t", $i);
}
// A string with returns in it.... show this as a multiline element.
- elseif (strpos($val, "\n") !== false)
- {
+ elseif (strpos($val, "\n") !== false) {
Utils::$context['feed']['items'] .= "\n" . (!empty($element['cdata']) || $forceCdata ? self::cdataParse(self::fixPossibleUrl($val), $ns, $forceCdata) : self::fixPossibleUrl($val)) . "\n" . str_repeat("\t", $i);
}
// A simple string.
- else
- {
+ else {
Utils::$context['feed']['items'] .= !empty($element['cdata']) || $forceCdata ? self::cdataParse(self::fixPossibleUrl($val), $ns, $forceCdata) : self::fixPossibleUrl($val);
}
@@ -3250,10 +3125,11 @@ protected static function dumpTags(array $data, int $i, string $format = '', arr
*/
protected static function fixPossibleUrl($val)
{
- if (substr($val, 0, strlen(Config::$scripturl)) != Config::$scripturl)
+ if (substr($val, 0, strlen(Config::$scripturl)) != Config::$scripturl) {
return $val;
+ }
- IntegrationHook::call('integrate_fix_url', array(&$val));
+ IntegrationHook::call('integrate_fix_url', [&$val]);
if (
empty(Config::$modSettings['queryless_urls'])
@@ -3266,18 +3142,16 @@ protected static function fixPossibleUrl($val)
!Utils::$context['server']['is_apache']
&& !Utils::$context['server']['is_lighttpd']
)
- )
- {
+ ) {
return $val;
}
$val = preg_replace_callback(
'~\b' . preg_quote(Config::$scripturl, '~') . '\?((?:board|topic)=[^#"]+)(#[^"]*)?$~',
- function($m)
- {
- return Config::$scripturl . '/' . strtr("$m[1]", '&;=', '//,') . '.html' . (isset($m[2]) ? $m[2] : "");
+ function ($m) {
+ return Config::$scripturl . '/' . strtr("{$m[1]}", '&;=', '//,') . '.html' . ($m[2] ?? '');
},
- $val
+ $val,
);
return $val;
@@ -3285,7 +3159,8 @@ function($m)
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Feed::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Feed::exportStatic')) {
Feed::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/FindMember.php b/Sources/Actions/FindMember.php
index 7e4beaaa0e..08d0faf463 100644
--- a/Sources/Actions/FindMember.php
+++ b/Sources/Actions/FindMember.php
@@ -14,7 +14,6 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\PageIndex;
use SMF\Theme;
@@ -39,12 +38,11 @@ class FindMember implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'JSMembers',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -72,13 +70,14 @@ public function execute(): void
// Why is this in the Help template, you ask? Well, erm... it helps you. Does that work?
Theme::loadTemplate('Help');
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
Utils::$context['sub_template'] = 'find_members';
- if (isset($_REQUEST['search']))
+ if (isset($_REQUEST['search'])) {
Utils::$context['last_search'] = Utils::htmlspecialchars($_REQUEST['search'], ENT_QUOTES);
- else
+ } else {
$_REQUEST['start'] = 0;
+ }
// Allow the user to pass the input to be added to to the box.
Utils::$context['input_box_name'] = isset($_REQUEST['input']) && preg_match('~^[\w-]+$~', $_REQUEST['input']) === 1 ? $_REQUEST['input'] : 'to';
@@ -88,40 +87,39 @@ public function execute(): void
Utils::$context['quote_results'] = !empty($_REQUEST['quote']);
// List all the results.
- Utils::$context['results'] = array();
+ Utils::$context['results'] = [];
// Some buddy related settings ;)
Utils::$context['show_buddies'] = !empty(User::$me->buddies);
Utils::$context['buddy_search'] = isset($_REQUEST['buddies']);
// If the user has done a search, well - search.
- if (isset($_REQUEST['search']))
- {
+ if (isset($_REQUEST['search'])) {
$_REQUEST['search'] = Utils::htmlspecialchars($_REQUEST['search'], ENT_QUOTES);
- Utils::$context['results'] = User::find(array($_REQUEST['search']), true, Utils::$context['buddy_search']);
+ Utils::$context['results'] = User::find([$_REQUEST['search']], true, Utils::$context['buddy_search']);
$total_results = count(Utils::$context['results']);
Utils::$context['page_index'] = new PageIndex(Config::$scripturl . '?action=findmember;search=' . Utils::$context['last_search'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'] . ';input=' . Utils::$context['input_box_name'] . (Utils::$context['quote_results'] ? ';quote=1' : '') . (Utils::$context['buddy_search'] ? ';buddies' : ''), $_REQUEST['start'], $total_results, 7);
// Determine the navigation context.
$base_url = Config::$scripturl . '?action=findmember;search=' . urlencode(Utils::$context['last_search']) . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']) . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
- Utils::$context['links'] = array(
+ Utils::$context['links'] = [
'first' => $_REQUEST['start'] >= 7 ? $base_url . ';start=0' : '',
'prev' => $_REQUEST['start'] >= 7 ? $base_url . ';start=' . ($_REQUEST['start'] - 7) : '',
'next' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . ($_REQUEST['start'] + 7) : '',
'last' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . (floor(($total_results - 1) / 7) * 7) : '',
'up' => Config::$scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']),
- );
- Utils::$context['page_info'] = array(
+ ];
+ Utils::$context['page_info'] = [
'current_page' => $_REQUEST['start'] / 7 + 1,
- 'num_pages' => floor(($total_results - 1) / 7) + 1
- );
+ 'num_pages' => floor(($total_results - 1) / 7) + 1,
+ ];
Utils::$context['results'] = array_slice(Utils::$context['results'], $_REQUEST['start'], 7);
- }
- else
+ } else {
Utils::$context['links']['up'] = Config::$scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']);
+ }
}
/***********************
@@ -135,8 +133,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;
}
@@ -159,11 +158,11 @@ public static function call(): void
protected function __construct()
{
}
-
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\FindMember::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\FindMember::exportStatic')) {
FindMember::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Groups.php b/Sources/Actions/Groups.php
index 05b035472a..adc3a6dcfd 100644
--- a/Sources/Actions/Groups.php
+++ b/Sources/Actions/Groups.php
@@ -13,16 +13,16 @@
namespace SMF\Actions;
+use SMF\Actions\Moderation\Main as ModCenter;
use SMF\BackwardCompatibility;
-
use SMF\BBCodeParser;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Group;
use SMF\IntegrationHook;
use SMF\ItemList;
use SMF\Lang;
-use SMF\Logging;
use SMF\Menu;
use SMF\PageIndex;
use SMF\SecurityToken;
@@ -30,8 +30,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Actions\Moderation\Main as ModCenter;
-use SMF\Db\DatabaseApi as Db;
/**
* Shows group info and allows certain priviledged members to add/remove members.
@@ -45,12 +43,18 @@ class Groups implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'Groups',
- ),
- );
+ 'list_getMembergroups' => 'list_getMembergroups',
+ 'listMembergroupMembers_Href' => 'listMembergroupMembers_Href',
+ 'list_getGroupRequestCount' => 'list_getGroupRequestCount',
+ 'list_getGroupRequests' => 'list_getGroupRequests',
+ 'GroupList' => 'GroupList',
+ 'MembergroupMembers' => 'MembergroupMembers',
+ 'GroupRequests' => 'GroupRequests',
+ ],
+ ];
/*******************
* Public properties
@@ -73,11 +77,11 @@ class Groups implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'index' => 'index',
'members' => 'members',
'requests' => 'requests',
- );
+ ];
/*********************
* Internal properties
@@ -125,8 +129,7 @@ public function execute(): void
Theme::loadTemplate('ManageMembergroups');
// If needed, set the mod center menu.
- if (User::$me->allowedTo('access_mod_center') && (User::$me->mod_cache['gq'] != '0=1' || User::$me->allowedTo('manage_membergroups')) && !isset(Menu::$loaded['admin']) && !isset(Menu::$loaded['moderate']))
- {
+ if (User::$me->allowedTo('access_mod_center') && (User::$me->mod_cache['gq'] != '0=1' || User::$me->allowedTo('manage_membergroups')) && !isset(Menu::$loaded['admin']) && !isset(Menu::$loaded['moderate'])) {
$_GET['area'] = $this->subaction == 'requests' ? 'groups' : 'viewgroups';
$this->action_url = '?action=moderate;area=' . $_GET['area'];
@@ -134,22 +137,22 @@ public function execute(): void
ModCenter::load()->createMenu();
}
// Otherwise add something to the link tree, for normal people.
- else
- {
+ else {
User::$me->isAllowedTo('view_mlist');
$this->action_url = '?action=groups';
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . $this->action_url,
'name' => Lang::$txt['groups'],
- );
+ ];
}
- $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);
+ }
}
/**
@@ -160,97 +163,88 @@ public function index(): void
Utils::$context['page_title'] = Lang::$txt['viewing_groups'];
// Use the standard templates for showing this.
- $listOptions = array(
+ $listOptions = [
'id' => 'group_lists',
'title' => Utils::$context['page_title'],
'base_href' => Config::$scripturl . $this->action_url . ';sa=view',
'default_sort_col' => 'group',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getMembergroups',
- 'params' => array(
+ 'params' => [
'regular',
- ),
- ),
- 'columns' => array(
- 'group' => array(
- 'header' => array(
+ ],
+ ],
+ 'columns' => [
+ 'group' => [
+ 'header' => [
'value' => Lang::$txt['name'],
- ),
- 'data' => array(
- 'function' => function($rowData)
- {
+ ],
+ 'data' => [
+ 'function' => function ($rowData) {
// Since the moderator group has no explicit members, no link is needed.
- if ($rowData['id_group'] == 3)
- {
+ if ($rowData['id_group'] == 3) {
$group_name = $rowData['group_name'];
- }
- else
- {
+ } else {
$color_style = empty($rowData['online_color']) ? '' : sprintf(' style="color: %1$s;"', $rowData['online_color']);
$group_name = sprintf('%4$s', Config::$scripturl, $rowData['id_group'], $color_style, $rowData['group_name']);
}
// Add a help option for moderator and administrator.
- if ($rowData['id_group'] == 1)
- {
+ if ($rowData['id_group'] == 1) {
$group_name .= sprintf(' (?)', Config::$scripturl);
- }
- elseif ($rowData['id_group'] == 3)
- {
+ } elseif ($rowData['id_group'] == 3) {
$group_name .= sprintf(' (?)', Config::$scripturl);
}
return $group_name;
},
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, mg.group_name',
'reverse' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, mg.group_name DESC',
- ),
- ),
- 'icons' => array(
- 'header' => array(
+ ],
+ ],
+ 'icons' => [
+ 'header' => [
'value' => Lang::$txt['membergroups_icons'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'icons',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'mg.icons',
'reverse' => 'mg.icons DESC',
- )
- ),
- 'moderators' => array(
- 'header' => array(
+ ],
+ ],
+ 'moderators' => [
+ 'header' => [
'value' => Lang::$txt['moderators'],
- ),
- 'data' => array(
- 'function' => function($group)
- {
+ ],
+ 'data' => [
+ 'function' => function ($group) {
return empty($group['moderators']) ? '' . Lang::$txt['membergroups_new_copy_none'] . '' : implode(', ', $group['moderators']);
},
- ),
- ),
- 'members' => array(
- 'header' => array(
+ ],
+ ],
+ 'members' => [
+ 'header' => [
'value' => Lang::$txt['membergroups_members_top'],
- ),
- 'data' => array(
- 'function' => function($rowData)
- {
+ ],
+ 'data' => [
+ 'function' => function ($rowData) {
// No explicit members for the moderator group.
return $rowData['id_group'] == 3 ? Lang::$txt['membergroups_guests_na'] : Lang::numberFormat($rowData['num_members']);
},
'class' => 'centercol',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, 1',
'reverse' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, 1 DESC',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
// Create the request list.
new ItemList($listOptions);
@@ -277,109 +271,109 @@ public function members(): void
$_REQUEST['group'] = isset($_REQUEST['group']) ? (int) $_REQUEST['group'] : 0;
// No browsing of guests, membergroup 0 or moderators.
- if (in_array($_REQUEST['group'], array(-1, 0, 3)))
+ if (in_array($_REQUEST['group'], [-1, 0, 3])) {
ErrorHandler::fatalLang('membergroup_does_not_exist', false);
+ }
// Load up the group details.
@list($group) = Group::load($_REQUEST['group']);
- if (empty($group->id))
+ if (empty($group->id)) {
ErrorHandler::fatalLang('membergroup_does_not_exist', false);
+ }
Utils::$context['group'] = $group;
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . $this->action_url . ';sa=members;group=' . $group->id,
'name' => $group->name,
- );
+ ];
Utils::$context['can_send_email'] = User::$me->allowedTo('moderate_forum');
// Load all the group moderators, for fun.
User::load($group->loadModerators(), User::LOAD_BY_ID, 'minimal');
- foreach ($group->moderator_ids as $mod_id)
- {
- $group->moderators[] = array(
+ foreach ($group->moderator_ids as $mod_id) {
+ $group->moderators[] = [
'id' => $mod_id,
'name' => User::$loaded[$mod_id]->name,
- );
+ ];
}
// If this group is hidden then it can only "exist" if the user can moderate it!
- if ($group->hidden === Group::INVISIBLE && !$group->can_moderate)
+ if ($group->hidden === Group::INVISIBLE && !$group->can_moderate) {
ErrorHandler::fatalLang('membergroup_does_not_exist', false);
+ }
// Removing member from group?
- if (isset($_POST['remove']) && !empty($_REQUEST['rem']) && is_array($_REQUEST['rem']) && $group->assignable)
- {
+ if (isset($_POST['remove']) && !empty($_REQUEST['rem']) && is_array($_REQUEST['rem']) && $group->assignable) {
User::$me->checkSession();
SecurityToken::validate('mod-mgm');
$group->removeMembers($_REQUEST['rem'], true);
}
// Must be adding new members to the group...
- elseif (isset($_REQUEST['add']) && (!empty($_REQUEST['toAdd']) || !empty($_REQUEST['member_add'])) && $group->assignable)
- {
+ elseif (isset($_REQUEST['add']) && (!empty($_REQUEST['toAdd']) || !empty($_REQUEST['member_add'])) && $group->assignable) {
User::$me->checkSession();
SecurityToken::validate('mod-mgm');
- $member_query = array();
- $member_parameters = array();
+ $member_query = [];
+ $member_parameters = [];
// Get all the members to be added... taking into account names can be quoted ;)
- $_REQUEST['toAdd'] = strtr(Utils::htmlspecialchars($_REQUEST['toAdd'], ENT_QUOTES), array('"' => '"'));
+ $_REQUEST['toAdd'] = strtr(Utils::htmlspecialchars($_REQUEST['toAdd'], ENT_QUOTES), ['"' => '"']);
preg_match_all('~"([^"]+)"~', $_REQUEST['toAdd'], $matches);
$member_names = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_REQUEST['toAdd']))));
- foreach ($member_names as $index => $member_name)
- {
+ foreach ($member_names as $index => $member_name) {
$member_names[$index] = trim(Utils::strtolower($member_names[$index]));
- if (strlen($member_names[$index]) == 0)
+ if (strlen($member_names[$index]) == 0) {
unset($member_names[$index]);
+ }
}
// Any passed by ID?
- $member_ids = array();
- if (!empty($_REQUEST['member_add']))
- {
- foreach ($_REQUEST['member_add'] as $id)
- {
- if ($id > 0)
+ $member_ids = [];
+
+ if (!empty($_REQUEST['member_add'])) {
+ foreach ($_REQUEST['member_add'] as $id) {
+ if ($id > 0) {
$member_ids[] = (int) $id;
+ }
}
}
// Construct the query pelements.
- if (!empty($member_ids))
- {
+ if (!empty($member_ids)) {
$member_query[] = 'id_member IN ({array_int:member_ids})';
$member_parameters['member_ids'] = $member_ids;
}
- if (!empty($member_names))
- {
+
+ if (!empty($member_names)) {
$member_query[] = 'LOWER(member_name) IN ({array_string:member_names})';
$member_query[] = 'LOWER(real_name) IN ({array_string:member_names})';
$member_parameters['member_names'] = $member_names;
}
- $members = array();
- if (!empty($member_query))
- {
- $request = Db::$db->query('', '
- SELECT id_member
+ $members = [];
+
+ if (!empty($member_query)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}members
WHERE (' . implode(' OR ', $member_query) . ')
AND id_group != {int:id_group}
AND FIND_IN_SET({int:id_group}, additional_groups) = 0',
- array_merge($member_parameters, array(
+ array_merge($member_parameters, [
'id_group' => $_REQUEST['group'],
- ))
+ ]),
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$members[] = $row['id_member'];
}
Db::$db->free_result($request);
@@ -388,35 +382,31 @@ public function members(): void
// @todo Add $_POST['additional'] to templates!
// Do the updates...
- if (!empty($members))
- {
+ if (!empty($members)) {
@list($group) = Group::load((int) $_REQUEST['group']);
- if ($group instanceof Group)
- {
+ if ($group instanceof Group) {
$group->addMembers($members, isset($_POST['additional']) ? 'only_additional' : 'auto', true);
}
}
}
// Sort out the sorting!
- $sort_methods = array(
+ $sort_methods = [
'name' => 'real_name',
'email' => 'email_address',
'active' => 'last_login',
'registered' => 'date_registered',
'posts' => 'posts',
- );
+ ];
// They didn't pick one, default to by name..
- if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']]))
- {
+ if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']])) {
Utils::$context['sort_by'] = 'name';
$querySort = 'real_name';
}
// Otherwise default to ascending.
- else
- {
+ else {
Utils::$context['sort_by'] = $_REQUEST['sort'];
$querySort = $sort_methods[$_REQUEST['sort']];
}
@@ -433,12 +423,12 @@ public function members(): void
Utils::$context['can_moderate_forum'] = User::$me->allowedTo('moderate_forum');
// Load up all members of this group.
- Utils::$context['members'] = array();
+ Utils::$context['members'] = [];
- if ($group->loadMembers() !== array())
- {
- foreach (User::load($group->members, User::LOAD_BY_ID, 'normal') as $member)
+ if ($group->loadMembers() !== []) {
+ foreach (User::load($group->members, User::LOAD_BY_ID, 'normal') as $member) {
Utils::$context['members'][] = $member->format();
+ }
}
// Select the template.
@@ -446,9 +436,8 @@ public function members(): void
Utils::$context['page_title'] = Lang::$txt['membergroups_members_title'] . ': ' . $group->name;
SecurityToken::create('mod-mgm');
- if ($group->assignable)
- {
- Theme::loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
+ if ($group->assignable) {
+ Theme::loadJavaScriptFile('suggest.js', ['defer' => false, 'minimize' => true], 'smf_suggest');
}
}
@@ -462,33 +451,33 @@ public function requests(): void
Utils::$context['sub_template'] = 'show_list';
// Verify we can be here.
- if (User::$me->mod_cache['gq'] == '0=1')
+ if (User::$me->mod_cache['gq'] == '0=1') {
User::$me->isAllowedTo('manage_membergroups');
+ }
// Normally, we act normally...
$where = (User::$me->mod_cache['gq'] == '1=1' || User::$me->mod_cache['gq'] == '0=1' ? User::$me->mod_cache['gq'] : 'lgr.' . User::$me->mod_cache['gq']);
$where .= ' AND lgr.status ' . (isset($_GET['closed']) ? '!=' : '=') . ' {int:status_open}';
- $where_parameters = array(
+ $where_parameters = [
'status_open' => 0,
- );
+ ];
// We've submitted?
- if (isset($_POST[Utils::$context['session_var']]) && !empty($_POST['groupr']) && !empty($_POST['req_action']))
- {
+ if (isset($_POST[Utils::$context['session_var']]) && !empty($_POST['groupr']) && !empty($_POST['req_action'])) {
User::$me->checkSession();
SecurityToken::validate('mod-gr');
// Clean the values.
- foreach ($_POST['groupr'] as $k => $request)
+ foreach ($_POST['groupr'] as $k => $request) {
$_POST['groupr'][$k] = (int) $request;
+ }
- $log_changes = array();
+ $log_changes = [];
// If we are giving a reason (And why shouldn't we?), then we don't actually do much.
- if ($_POST['req_action'] == 'reason')
- {
+ if ($_POST['req_action'] == 'reason') {
// Different sub template...
Utils::$context['sub_template'] = 'group_request_reason';
@@ -505,96 +494,92 @@ public function requests(): void
Utils::obExit();
}
// Otherwise we do something!
- else
- {
- $request_list = array();
+ else {
+ $request_list = [];
- $members_to_add = array();
+ $members_to_add = [];
- $request = Db::$db->query('', '
- SELECT lgr.id_request
+ $request = Db::$db->query(
+ '',
+ 'SELECT lgr.id_request
FROM {db_prefix}log_group_requests AS lgr
WHERE ' . $where . '
AND lgr.id_request IN ({array_int:request_list})',
- array(
+ [
'request_list' => $_POST['groupr'],
'status_open' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if ($_POST['req_action'] === 'approve')
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if ($_POST['req_action'] === 'approve') {
$members_to_add[$row['id_group']] = $row['id_member'];
+ }
- if (!isset($log_changes[$row['id_request']]))
- {
- $log_changes[$row['id_request']] = array(
+ if (!isset($log_changes[$row['id_request']])) {
+ $log_changes[$row['id_request']] = [
'id_request' => $row['id_request'],
'status' => $_POST['req_action'] == 'approve' ? 1 : 2, // 1 = approved, 2 = rejected
'id_member_acted' => User::$me->id,
'member_name_acted' => User::$me->name,
'time_acted' => time(),
'act_reason' => $_POST['req_action'] != 'approve' && !empty($_POST['groupreason']) && !empty($_POST['groupreason'][$row['id_request']]) ? Utils::htmlspecialchars($_POST['groupreason'][$row['id_request']], ENT_QUOTES) : '',
- );
+ ];
}
$request_list[] = $row['id_request'];
}
Db::$db->free_result($request);
- if (!empty($members_to_add))
- {
- foreach ($members_to_add as $group_id => $members)
- {
+ if (!empty($members_to_add)) {
+ foreach ($members_to_add as $group_id => $members) {
@list($group) = Group::load((int) $group_id);
- if ($group instanceof Group)
+ if ($group instanceof Group) {
$group->addMembers($members);
+ }
}
}
// Add a background task to handle notifying people of this request
- $data = Utils::jsonEncode(array(
+ $data = Utils::jsonEncode([
'member_id' => User::$me->id,
'member_ip' => User::$me->ip,
'request_list' => $request_list,
'status' => $_POST['req_action'],
- 'reason' => isset($_POST['groupreason']) ? $_POST['groupreason'] : '',
+ 'reason' => $_POST['groupreason'] ?? '',
'time' => time(),
- ));
+ ]);
Db::$db->insert(
'insert',
'{db_prefix}background_tasks',
- array(
- 'task_file' => 'string-255',
+ [
'task_class' => 'string-255',
'task_data' => 'string',
'claimed_time' => 'int',
- ),
- array(
- '$sourcedir/tasks/GroupAct_Notify.php',
- 'SMF\Tasks\GroupAct_Notify',
+ ],
+ [
+ 'SMF\\Tasks\\GroupAct_Notify',
$data,
0,
- ),
- array()
+ ],
+ [],
);
// Some changes to log?
- if (!empty($log_changes))
- {
- foreach ($log_changes as $id_request => $details)
- {
- Db::$db->query('', '
- UPDATE {db_prefix}log_group_requests
+ if (!empty($log_changes)) {
+ foreach ($log_changes as $id_request => $details) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_group_requests
SET status = {int:status},
id_member_acted = {int:id_member_acted},
member_name_acted = {string:member_name_acted},
time_acted = {int:time_acted},
act_reason = {string:act_reason}
WHERE id_request = {int:id_request}',
- $details
+ $details,
);
}
}
@@ -602,97 +587,97 @@ public function requests(): void
}
// This is all the information required for a group listing.
- $listOptions = array(
+ $listOptions = [
'id' => 'group_request_list',
'width' => '100%',
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['mc_groupr_none_found'],
'base_href' => Config::$scripturl . $this->action_url . ';sa=requests',
'default_sort_col' => 'member',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getGroupRequests',
- 'params' => array(
+ 'params' => [
$where,
$where_parameters,
- ),
- ),
- 'get_count' => array(
+ ],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getGroupRequestCount',
- 'params' => array(
+ 'params' => [
$where,
$where_parameters,
- ),
- ),
- 'columns' => array(
- 'member' => array(
- 'header' => array(
+ ],
+ ],
+ 'columns' => [
+ 'member' => [
+ 'header' => [
'value' => Lang::$txt['mc_groupr_member'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'member_link',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'mem.member_name',
'reverse' => 'mem.member_name DESC',
- ),
- ),
- 'group' => array(
- 'header' => array(
+ ],
+ ],
+ 'group' => [
+ 'header' => [
'value' => Lang::$txt['mc_groupr_group'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'group_link',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'mg.group_name',
'reverse' => 'mg.group_name DESC',
- ),
- ),
- 'reason' => array(
- 'header' => array(
+ ],
+ ],
+ 'reason' => [
+ 'header' => [
'value' => Lang::$txt['mc_groupr_reason'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'reason',
- ),
- ),
- 'date' => array(
- 'header' => array(
+ ],
+ ],
+ 'date' => [
+ 'header' => [
'value' => Lang::$txt['date'],
'style' => 'width: 18%; white-space:nowrap;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time_submitted',
- ),
- ),
- 'action' => array(
- 'header' => array(
+ ],
+ ],
+ 'action' => [
+ 'header' => [
'value' => '',
'style' => 'width: 4%;',
'class' => 'centercol',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => '',
- 'params' => array(
+ 'params' => [
'id' => false,
- ),
- ),
+ ],
+ ],
'class' => 'centercol',
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . $this->action_url . ';sa=requests',
'include_sort' => true,
'include_start' => true,
- 'hidden_fields' => array(
+ 'hidden_fields' => [
Utils::$context['session_var'] => Utils::$context['session_id'],
- ),
+ ],
'token' => 'mod-gr',
- ),
- 'additional_rows' => array(
- array(
+ ],
+ 'additional_rows' => [
+ [
'position' => 'bottom_of_list',
'value' => '
',
'class' => 'floatright',
- ),
- ),
- );
+ ],
+ ],
+ ];
- if (isset($_GET['closed']))
- {
+ if (isset($_GET['closed'])) {
// Closed requests don't require interaction.
unset($listOptions['columns']['action'], $listOptions['form'], $listOptions['additional_rows'][0]);
$listOptions['base_href'] .= 'closed';
@@ -720,9 +704,9 @@ public function requests(): void
new ItemList($listOptions);
Utils::$context['default_list'] = 'group_request_list';
- Menu::$loaded['moderate']->tab_data = array(
+ Menu::$loaded['moderate']->tab_data = [
'title' => Lang::$txt['mc_group_requests'],
- );
+ ];
}
/***********************
@@ -736,8 +720,9 @@ public function requests(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -762,31 +747,30 @@ public static function call(): void
public static function list_getMembergroups($start, $items_per_page, $sort, $membergroup_type): array
{
// Start collecting the data.
- $groups = array();
- $group_ids = array();
+ $groups = [];
+ $group_ids = [];
Utils::$context['can_moderate'] = User::$me->allowedTo('manage_membergroups');
- $query_customizations = array(
- 'where' => array(
+ $query_customizations = [
+ 'where' => [
'mg.min_posts' . ($membergroup_type === 'post_count' ? '!= ' : '= ') . '-1',
- ),
+ ],
'order' => (array) $sort,
- );
+ ];
- if (!User::$me->allowedTo('admin_forum'))
- {
+ if (!User::$me->allowedTo('admin_forum')) {
$query_customizations['where'][] = 'mg.id_group != {int:mod_group}';
$query_customizations['params']['mod_group'] = Group::MOD;
}
- $temp = Group::load(array(), $query_customizations);
- Group::loadModeratorsBatch(array_map(fn($group) => $group->id, $temp));
+ $temp = Group::load([], $query_customizations);
+ Group::loadModeratorsBatch(array_map(fn ($group) => $group->id, $temp));
- foreach ($temp as $group)
- {
+ foreach ($temp as $group) {
// We only list the groups they can see.
- if ($group->hidden === Group::INVISIBLE && !$group->can_moderate)
+ if ($group->hidden === Group::INVISIBLE && !$group->can_moderate) {
continue;
+ }
Utils::$context['can_moderate'] |= $group->can_moderate;
@@ -797,19 +781,17 @@ public static function list_getMembergroups($start, $items_per_page, $sort, $mem
}
// If we found any membergroups, get the amount of members in them.
- if (!empty($group_ids))
- {
+ if (!empty($group_ids)) {
Group::countMembersBatch($group_ids);
Group::loadModeratorsBatch($group_ids);
- foreach ($group_ids as $group_id)
- {
+ foreach ($group_ids as $group_id) {
User::load(Group::$loaded[$group_id]->moderator_ids);
- foreach (Group::$loaded[$group_id]->moderator_ids as $mod_id)
- {
- if (!isset(User::$loaded[$mod_id]))
+ foreach (Group::$loaded[$group_id]->moderator_ids as $mod_id) {
+ if (!isset(User::$loaded[$mod_id])) {
continue;
+ }
Group::$loaded[$group_id]->moderators[] = '' . User::$loaded[$mod_id]->name . '';
}
@@ -817,12 +799,12 @@ public static function list_getMembergroups($start, $items_per_page, $sort, $mem
}
// Apply manual sorting if the 'number of members' column is selected.
- if (substr($sort, 0, 1) == '1' || strpos($sort, ', 1') !== false)
- {
+ if (substr($sort, 0, 1) == '1' || strpos($sort, ', 1') !== false) {
$sort_ascending = strpos($sort, 'DESC') === false;
- foreach ($groups as $group)
+ foreach ($groups as $group) {
$sort_array[] = $group->id_group != Group::MOD ? (int) $group->num_members : Group::GUEST;
+ }
array_multisort($sort_array, $sort_ascending ? SORT_ASC : SORT_DESC, SORT_REGULAR, $groups);
}
@@ -841,33 +823,32 @@ public static function list_getMembergroups($start, $items_per_page, $sort, $mem
*/
public static function listMembergroupMembers_Href(&$members, $membergroup, $limit = null): bool
{
- $members = array();
+ $members = [];
- $request = Db::$db->query('', '
- SELECT id_member, real_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name
FROM {db_prefix}members
WHERE id_group = {int:id_group} OR FIND_IN_SET({int:id_group}, additional_groups) != 0' . ($limit === null ? '' : '
LIMIT ' . ($limit + 1)),
- array(
+ [
'id_group' => $membergroup,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$members[$row['id_member']] = '' . $row['real_name'] . '';
}
Db::$db->free_result($request);
// If there are more than $limit members, add a 'more' link.
- if ($limit !== null && count($members) > $limit)
- {
+ if ($limit !== null && count($members) > $limit) {
array_pop($members);
+
return true;
}
- else
- {
- return false;
- }
+
+ return false;
}
/**
@@ -879,12 +860,13 @@ public static function listMembergroupMembers_Href(&$members, $membergroup, $lim
*/
public static function list_getGroupRequestCount($where, $where_parameters): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_group_requests AS lgr
WHERE ' . $where,
- array_merge($where_parameters, array(
- ))
+ array_merge($where_parameters, [
+ ]),
);
list($totalRequests) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -910,10 +892,11 @@ public static function list_getGroupRequestCount($where, $where_parameters): int
*/
public static function list_getGroupRequests($start, $items_per_page, $sort, $where, $where_parameters): array
{
- $group_requests = array();
+ $group_requests = [];
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
lgr.id_request, lgr.id_member, lgr.id_group, lgr.time_applied, lgr.reason,
lgr.status, lgr.id_member_acted, lgr.member_name_acted, lgr.time_acted, lgr.act_reason,
mem.member_name, mg.group_name, mg.online_color, mem.real_name
@@ -923,47 +906,41 @@ public static function list_getGroupRequests($start, $items_per_page, $sort, $wh
WHERE ' . $where . '
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array_merge($where_parameters, array(
+ array_merge($where_parameters, [
'sort' => $sort,
'start' => $start,
'max' => $items_per_page,
- ))
+ ]),
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (empty($row['reason']))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (empty($row['reason'])) {
$reason = '(' . Lang::$txt['mc_groupr_no_reason'] . ')';
- }
- else
- {
+ } else {
$reason = Lang::censorText($row['reason']);
}
- if (isset($_GET['closed']))
- {
- if ($row['status'] == 1)
- {
+ if (isset($_GET['closed'])) {
+ if ($row['status'] == 1) {
$reason .= '
' . Lang::$txt['mc_groupr_approved'] . '';
- }
- elseif ($row['status'] == 2)
- {
+ } elseif ($row['status'] == 2) {
$reason .= '
' . Lang::$txt['mc_groupr_rejected'] . '';
}
$reason .= ' (' . Time::create('@' . $row['time_acted'])->format() . ')';
- if (!empty($row['act_reason']))
+ if (!empty($row['act_reason'])) {
$reason .= '
' . Lang::censorText($row['act_reason']);
+ }
}
- $group_requests[] = array(
+ $group_requests[] = [
'id' => $row['id_request'],
'member_link' => '' . $row['real_name'] . '',
'group_link' => '' . $row['group_name'] . '',
'reason' => $reason,
'time_submitted' => Time::create('@' . $row['time_applied'])->format(),
- );
+ ];
}
Db::$db->free_result($request);
@@ -1009,15 +986,17 @@ public static function GroupRequests(): void
*/
protected function __construct()
{
- IntegrationHook::call('integrate_manage_groups', array(&self::$subactions));
+ IntegrationHook::call('integrate_manage_groups', [&self::$subactions]);
- if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
+ if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Groups::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Groups::exportStatic')) {
Groups::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Help.php b/Sources/Actions/Help.php
index 1ed4956eaa..5d5742a0d0 100644
--- a/Sources/Actions/Help.php
+++ b/Sources/Actions/Help.php
@@ -14,7 +14,6 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -33,12 +32,12 @@ class Help implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ShowHelp',
- ),
- );
+ 'HelpIndex' => 'HelpIndex',
+ ],
+ ];
/*******************
* Public properties
@@ -61,9 +60,9 @@ class Help implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'index' => 'index',
- );
+ ];
/****************************
* Internal static properties
@@ -86,10 +85,11 @@ class Help 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);
+ }
}
/**
@@ -104,7 +104,7 @@ public function index()
Utils::$context['canonical_url'] = Config::$scripturl . '?action=help';
// Sections were are going to link...
- Utils::$context['manual_sections'] = array(
+ Utils::$context['manual_sections'] = [
'registering' => 'Registering',
'logging_in' => 'Logging_In',
'profile' => 'Profile',
@@ -115,13 +115,13 @@ public function index()
'memberlist' => 'Memberlist',
'calendar' => 'Calendar',
'features' => 'Features',
- );
+ ];
// Build the link tree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=help',
'name' => Lang::$txt['help'],
- );
+ ];
// Lastly, some minor template stuff.
Utils::$context['page_title'] = Lang::$txt['manual_smf_user_help'];
@@ -139,8 +139,9 @@ public function index()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -182,15 +183,17 @@ protected function __construct()
Lang::load('Manual');
// CRUD $subactions as needed.
- IntegrationHook::call('integrate_manage_help', array(&$subactions));
+ IntegrationHook::call('integrate_manage_help', [&$subactions]);
- if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
+ if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Help::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Help::exportStatic')) {
Help::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/HelpAdmin.php b/Sources/Actions/HelpAdmin.php
index a73af97a81..0219386c03 100644
--- a/Sources/Actions/HelpAdmin.php
+++ b/Sources/Actions/HelpAdmin.php
@@ -14,7 +14,6 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
@@ -36,12 +35,11 @@ class HelpAdmin implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ShowAdminHelp',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -71,15 +69,17 @@ class HelpAdmin implements ActionInterface
*/
public function execute(): void
{
- if (!isset($_GET['help']) || !is_string($_GET['help']))
+ if (!isset($_GET['help']) || !is_string($_GET['help'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Load the admin help language file and template.
Lang::load('Help');
// Permission specific help?
- if (isset($_GET['help']) && substr($_GET['help'], 0, 14) == 'permissionhelp')
+ if (isset($_GET['help']) && substr($_GET['help'], 0, 14) == 'permissionhelp') {
Lang::load('ManagePermissions');
+ }
Theme::loadTemplate('Help');
@@ -87,21 +87,15 @@ public function execute(): void
IntegrationHook::call('integrate_helpadmin');
// What help string should be used?
- if (isset(Lang::$helptxt[$_GET['help']]))
- {
+ if (isset(Lang::$helptxt[$_GET['help']])) {
Utils::$context['help_text'] = Lang::$helptxt[$_GET['help']];
- }
- elseif (isset(Lang::$txt[$_GET['help']]))
- {
+ } elseif (isset(Lang::$txt[$_GET['help']])) {
Utils::$context['help_text'] = Lang::$txt[$_GET['help']];
- }
- else
- {
- ErrorHandler::fatalLang('not_found', false, array(), 404);
+ } else {
+ ErrorHandler::fatalLang('not_found', false, [], 404);
}
- switch ($_GET['help'])
- {
+ switch ($_GET['help']) {
case 'cal_short_months':
Utils::$context['help_text'] = sprintf(Utils::$context['help_text'], Lang::$txt['months_short'][1], Lang::$txt['months_titles'][1]);
break;
@@ -120,8 +114,7 @@ public function execute(): void
}
// Does this text contain a link that we should fill in?
- if (preg_match('~%([0-9]+\$)?s\?~', Utils::$context['help_text'], $match))
- {
+ if (preg_match('~%([0-9]+\$)?s\?~', Utils::$context['help_text'], $match)) {
Utils::$context['help_text'] = sprintf(Utils::$context['help_text'], Config::$scripturl, Utils::$context['session_id'], Utils::$context['session_var']);
}
@@ -129,7 +122,7 @@ public function execute(): void
Utils::$context['page_title'] = Utils::$context['forum_name'] . ' - ' . Lang::$txt['help'];
// Don't show any template layers, just the popup sub template.
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
Utils::$context['sub_template'] = 'popup';
}
@@ -144,8 +137,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;
}
@@ -171,7 +165,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\HelpAdmin::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\HelpAdmin::exportStatic')) {
HelpAdmin::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/JavaScriptModify.php b/Sources/Actions/JavaScriptModify.php
index 0501a57293..953c13ddb5 100644
--- a/Sources/Actions/JavaScriptModify.php
+++ b/Sources/Actions/JavaScriptModify.php
@@ -14,10 +14,11 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\BBCodeParser;
use SMF\Board;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -27,9 +28,6 @@
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
-
/**
* Used to edit the body or subject of a message inline.
@@ -45,12 +43,11 @@ class JavaScriptModify implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'JavaScriptModify',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -74,8 +71,9 @@ class JavaScriptModify implements ActionInterface
public function execute(): void
{
// Assume the first message if no message ID was given.
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
t.locked, t.num_replies, t.id_member_started, t.id_first_msg,
m.id_msg, m.id_member, m.poster_time, m.subject, m.smileys_enabled, m.body, m.icon,
m.modified_time, m.modified_name, m.modified_reason, m.approved,
@@ -86,49 +84,40 @@ public function execute(): void
AND m.id_topic = {int:current_topic}' . (User::$me->allowedTo('modify_any') || User::$me->allowedTo('approve_posts') ? '' : (!Config::$modSettings['postmod_active'] ? '
AND (m.id_member != {int:guest_id} AND m.id_member = {int:current_member})' : '
AND (m.approved = {int:is_approved} OR (m.id_member != {int:guest_id} AND m.id_member = {int:current_member}))')),
- array(
+ [
'current_member' => User::$me->id,
'current_topic' => Topic::$topic_id,
'id_msg' => empty($_REQUEST['msg']) ? 't.id_first_msg' : (int) $_REQUEST['msg'],
'is_approved' => 1,
'guest_id' => 0,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('no_board', false);
}
$row = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
// Change either body or subject requires permissions to modify messages.
- if (isset($_POST['message']) || isset($_POST['subject']) || isset($_REQUEST['icon']))
- {
- if (!empty($row['locked']))
+ if (isset($_POST['message']) || isset($_POST['subject']) || isset($_REQUEST['icon'])) {
+ if (!empty($row['locked'])) {
User::$me->isAllowedTo('moderate_board');
+ }
- if ($row['id_member'] == User::$me->id && !User::$me->allowedTo('modify_any'))
- {
- if ((!Config::$modSettings['postmod_active'] || $row['approved']) && !empty(Config::$modSettings['edit_disable_time']) && $row['poster_time'] + (Config::$modSettings['edit_disable_time'] + 5) * 60 < time())
- {
+ if ($row['id_member'] == User::$me->id && !User::$me->allowedTo('modify_any')) {
+ if ((!Config::$modSettings['postmod_active'] || $row['approved']) && !empty(Config::$modSettings['edit_disable_time']) && $row['poster_time'] + (Config::$modSettings['edit_disable_time'] + 5) * 60 < time()) {
ErrorHandler::fatalLang('modify_post_time_passed', false);
- }
- elseif ($row['id_member_started'] == User::$me->id && !User::$me->allowedTo('modify_own'))
- {
+ } elseif ($row['id_member_started'] == User::$me->id && !User::$me->allowedTo('modify_own')) {
User::$me->isAllowedTo('modify_replies');
- }
- else
- {
+ } else {
User::$me->isAllowedTo('modify_own');
}
}
// Otherwise, they're locked out; someone who can modify the replies is needed.
- elseif ($row['id_member_started'] == User::$me->id && !User::$me->allowedTo('modify_any'))
- {
+ elseif ($row['id_member_started'] == User::$me->id && !User::$me->allowedTo('modify_any')) {
User::$me->isAllowedTo('modify_replies');
- }
- else
- {
+ } else {
User::$me->isAllowedTo('modify_any');
}
@@ -136,152 +125,124 @@ public function execute(): void
$moderationAction = $row['id_member'] != User::$me->id;
}
- $post_errors = array();
- if (isset($_POST['subject']) && Utils::htmlTrim(Utils::htmlspecialchars($_POST['subject'])) !== '')
- {
- $_POST['subject'] = strtr(Utils::htmlspecialchars($_POST['subject']), array("\r" => '', "\n" => '', "\t" => ''));
+ $post_errors = [];
+
+ if (isset($_POST['subject']) && Utils::htmlTrim(Utils::htmlspecialchars($_POST['subject'])) !== '') {
+ $_POST['subject'] = strtr(Utils::htmlspecialchars($_POST['subject']), ["\r" => '', "\n" => '', "\t" => '']);
// Maximum number of characters.
- if (Utils::entityStrlen($_POST['subject']) > 100)
+ if (Utils::entityStrlen($_POST['subject']) > 100) {
$_POST['subject'] = Utils::entitySubstr($_POST['subject'], 0, 100);
- }
- elseif (isset($_POST['subject']))
- {
+ }
+ } elseif (isset($_POST['subject'])) {
$post_errors[] = 'no_subject';
unset($_POST['subject']);
}
- if (isset($_POST['message']))
- {
- if (Utils::htmlTrim(Utils::htmlspecialchars($_POST['message'])) === '')
- {
+ if (isset($_POST['message'])) {
+ if (Utils::htmlTrim(Utils::htmlspecialchars($_POST['message'])) === '') {
$post_errors[] = 'no_message';
unset($_POST['message']);
- }
- elseif (!empty(Config::$modSettings['max_messageLength']) && Utils::entityStrlen($_POST['message']) > Config::$modSettings['max_messageLength'])
- {
+ } elseif (!empty(Config::$modSettings['max_messageLength']) && Utils::entityStrlen($_POST['message']) > Config::$modSettings['max_messageLength']) {
$post_errors[] = 'long_message';
unset($_POST['message']);
- }
- else
- {
+ } else {
$_POST['message'] = Utils::htmlspecialchars($_POST['message'], ENT_QUOTES);
Msg::preparsecode($_POST['message']);
- if (Utils::htmlTrim(strip_tags(BBCodeParser::load()->parse($_POST['message'], false), implode('', Utils::$context['allowed_html_tags']))) === '')
- {
+ if (Utils::htmlTrim(strip_tags(BBCodeParser::load()->parse($_POST['message'], false), implode('', Utils::$context['allowed_html_tags']))) === '') {
$post_errors[] = 'no_message';
unset($_POST['message']);
}
}
}
- IntegrationHook::call('integrate_post_JavascriptModify', array(&$post_errors, $row));
+ IntegrationHook::call('integrate_post_JavascriptModify', [&$post_errors, $row]);
- if (isset($_POST['lock']))
- {
- if (!User::$me->allowedTo(array('lock_any', 'lock_own')) || (!User::$me->allowedTo('lock_any') && User::$me->id != $row['id_member']))
- {
+ if (isset($_POST['lock'])) {
+ if (!User::$me->allowedTo(['lock_any', 'lock_own']) || (!User::$me->allowedTo('lock_any') && User::$me->id != $row['id_member'])) {
unset($_POST['lock']);
- }
- elseif (!User::$me->allowedTo('lock_any'))
- {
- if ($row['locked'] == 1)
- {
+ } elseif (!User::$me->allowedTo('lock_any')) {
+ if ($row['locked'] == 1) {
unset($_POST['lock']);
- }
- else
- {
+ } else {
$_POST['lock'] = empty($_POST['lock']) ? 0 : 2;
}
- }
- elseif (!empty($row['locked']) && !empty($_POST['lock']) || $_POST['lock'] == $row['locked'])
- {
+ } elseif (!empty($row['locked']) && !empty($_POST['lock']) || $_POST['lock'] == $row['locked']) {
unset($_POST['lock']);
- }
- else
- {
+ } else {
$_POST['lock'] = empty($_POST['lock']) ? 0 : 1;
}
}
- if (isset($_POST['sticky']) && !User::$me->allowedTo('make_sticky'))
+ if (isset($_POST['sticky']) && !User::$me->allowedTo('make_sticky')) {
unset($_POST['sticky']);
+ }
- if (isset($_POST['modify_reason']))
- {
- $_POST['modify_reason'] = strtr(Utils::htmlspecialchars($_POST['modify_reason']), array("\r" => '', "\n" => '', "\t" => ''));
+ if (isset($_POST['modify_reason'])) {
+ $_POST['modify_reason'] = strtr(Utils::htmlspecialchars($_POST['modify_reason']), ["\r" => '', "\n" => '', "\t" => '']);
// Maximum number of characters.
- if (Utils::entityStrlen($_POST['modify_reason']) > 100)
+ if (Utils::entityStrlen($_POST['modify_reason']) > 100) {
$_POST['modify_reason'] = Utils::entitySubstr($_POST['modify_reason'], 0, 100);
+ }
}
- if (empty($post_errors))
- {
- $msgOptions = array(
+ if (empty($post_errors)) {
+ $msgOptions = [
'id' => $row['id_msg'],
- 'subject' => isset($_POST['subject']) ? $_POST['subject'] : null,
- 'body' => isset($_POST['message']) ? $_POST['message'] : null,
+ 'subject' => $_POST['subject'] ?? null,
+ 'body' => $_POST['message'] ?? null,
'icon' => isset($_REQUEST['icon']) ? preg_replace('~[\./\\\\*\':"<>]~', '', $_REQUEST['icon']) : null,
- 'modify_reason' => (isset($_POST['modify_reason']) ? $_POST['modify_reason'] : ''),
- 'approved' => (isset($row['approved']) ? $row['approved'] : null),
- );
+ 'modify_reason' => ($_POST['modify_reason'] ?? ''),
+ 'approved' => ($row['approved'] ?? null),
+ ];
- $topicOptions = array(
+ $topicOptions = [
'id' => Topic::$topic_id,
'board' => Board::$info->id,
'lock_mode' => isset($_POST['lock']) ? (int) $_POST['lock'] : null,
'sticky_mode' => isset($_POST['sticky']) ? (int) $_POST['sticky'] : null,
'mark_as_read' => true,
- );
+ ];
- $posterOptions = array(
+ $posterOptions = [
'id' => User::$me->id,
'name' => $row['poster_name'],
'email' => $row['poster_email'],
'update_post_count' => !User::$me->is_guest && !isset($_REQUEST['msg']) && Board::$info->posts_count,
- );
+ ];
// Only consider marking as editing if they have edited the subject, message or icon.
- if ((isset($_POST['subject']) && $_POST['subject'] != $row['subject']) || (isset($_POST['message']) && $_POST['message'] != $row['body']) || (isset($_REQUEST['icon']) && $_REQUEST['icon'] != $row['icon']))
- {
+ if ((isset($_POST['subject']) && $_POST['subject'] != $row['subject']) || (isset($_POST['message']) && $_POST['message'] != $row['body']) || (isset($_REQUEST['icon']) && $_REQUEST['icon'] != $row['icon'])) {
// And even then only if the time has passed...
- if (time() - $row['poster_time'] > Config::$modSettings['edit_wait_time'] || User::$me->id != $row['id_member'])
- {
+ if (time() - $row['poster_time'] > Config::$modSettings['edit_wait_time'] || User::$me->id != $row['id_member']) {
$msgOptions['modify_time'] = time();
$msgOptions['modify_name'] = User::$me->name;
}
}
// If nothing was changed there's no need to add an entry to the moderation log.
- else
- {
+ else {
$moderationAction = false;
}
Msg::modify($msgOptions, $topicOptions, $posterOptions);
// If we didn't change anything this time but had before put back the old info.
- if (!isset($msgOptions['modify_time']) && !empty($row['modified_time']))
- {
+ if (!isset($msgOptions['modify_time']) && !empty($row['modified_time'])) {
$msgOptions['modify_time'] = $row['modified_time'];
$msgOptions['modify_name'] = $row['modified_name'];
$msgOptions['modify_reason'] = $row['modified_reason'];
}
// Changing the first subject updates other subjects to 'Re: new_subject'.
- if (isset($_POST['subject']) && isset($_REQUEST['change_all_subjects']) && $row['id_first_msg'] == $row['id_msg'] && !empty($row['num_replies']) && (User::$me->allowedTo('modify_any') || ($row['id_member_started'] == User::$me->id && User::$me->allowedTo('modify_replies'))))
- {
+ if (isset($_POST['subject'], $_REQUEST['change_all_subjects']) && $row['id_first_msg'] == $row['id_msg'] && !empty($row['num_replies']) && (User::$me->allowedTo('modify_any') || ($row['id_member_started'] == User::$me->id && User::$me->allowedTo('modify_replies')))) {
// Get the proper (default language) response prefix first.
- if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix')))
- {
- if (Lang::$default === User::$me->language)
- {
+ if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix'))) {
+ if (Lang::$default === User::$me->language) {
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
- }
- else
- {
+ } else {
Lang::load('index', Lang::$default, false);
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
Lang::load('index');
@@ -289,43 +250,41 @@ public function execute(): void
CacheApi::put('response_prefix', Utils::$context['response_prefix'], 600);
}
- Db::$db->query('', '
- UPDATE {db_prefix}messages
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}messages
SET subject = {string:subject}
WHERE id_topic = {int:current_topic}
AND id_msg != {int:id_first_msg}',
- array(
+ [
'current_topic' => Topic::$topic_id,
'id_first_msg' => $row['id_first_msg'],
'subject' => Utils::$context['response_prefix'] . $_POST['subject'],
- )
+ ],
);
}
- if (!empty($moderationAction))
- {
- Logging::logAction('modify', array('topic' => Topic::$topic_id, 'message' => $row['id_msg'], 'member' => $row['id_member'], 'board' => Board::$info->id));
+ if (!empty($moderationAction)) {
+ Logging::logAction('modify', ['topic' => Topic::$topic_id, 'message' => $row['id_msg'], 'member' => $row['id_member'], 'board' => Board::$info->id]);
}
}
- if (isset($_REQUEST['xml']))
- {
+ if (isset($_REQUEST['xml'])) {
Utils::$context['sub_template'] = 'modifydone';
- if (empty($post_errors) && isset($msgOptions['subject']) && isset($msgOptions['body']))
- {
- Utils::$context['message'] = array(
+ if (empty($post_errors) && isset($msgOptions['subject'], $msgOptions['body'])) {
+ Utils::$context['message'] = [
'id' => $row['id_msg'],
- 'modified' => array(
+ 'modified' => [
'time' => isset($msgOptions['modify_time']) ? Time::create('@' . $msgOptions['modify_time'])->format() : '',
- 'timestamp' => isset($msgOptions['modify_time']) ? $msgOptions['modify_time'] : 0,
+ 'timestamp' => $msgOptions['modify_time'] ?? 0,
'name' => isset($msgOptions['modify_time']) ? $msgOptions['modify_name'] : '',
'reason' => $msgOptions['modify_reason'],
- ),
+ ],
'subject' => $msgOptions['subject'],
'first_in_topic' => $row['id_msg'] == $row['id_first_msg'],
- 'body' => strtr($msgOptions['body'], array(']]>' => ']]]]>')),
- );
+ 'body' => strtr($msgOptions['body'], [']]>' => ']]]]>']),
+ ];
Lang::censorText(Utils::$context['message']['subject']);
Lang::censorText(Utils::$context['message']['body']);
@@ -333,46 +292,41 @@ public function execute(): void
Utils::$context['message']['body'] = BBCodeParser::load()->parse(Utils::$context['message']['body'], $row['smileys_enabled'], $row['id_msg']);
}
// Topic?
- elseif (empty($post_errors))
- {
+ elseif (empty($post_errors)) {
Utils::$context['sub_template'] = 'modifytopicdone';
- Utils::$context['message'] = array(
+ Utils::$context['message'] = [
'id' => $row['id_msg'],
- 'modified' => array(
+ 'modified' => [
'time' => isset($msgOptions['modify_time']) ? Time::create('@' . $msgOptions['modify_time'])->format() : '',
- 'timestamp' => isset($msgOptions['modify_time']) ? $msgOptions['modify_time'] : 0,
+ 'timestamp' => $msgOptions['modify_time'] ?? 0,
'name' => isset($msgOptions['modify_time']) ? $msgOptions['modify_name'] : '',
- ),
- 'subject' => isset($msgOptions['subject']) ? $msgOptions['subject'] : '',
- );
+ ],
+ 'subject' => $msgOptions['subject'] ?? '',
+ ];
Lang::censorText(Utils::$context['message']['subject']);
- }
- else
- {
- Utils::$context['message'] = array(
+ } else {
+ Utils::$context['message'] = [
'id' => $row['id_msg'],
- 'errors' => array(),
+ 'errors' => [],
'error_in_subject' => in_array('no_subject', $post_errors),
'error_in_body' => in_array('no_message', $post_errors) || in_array('long_message', $post_errors),
- );
+ ];
Lang::load('Errors');
- foreach ($post_errors as $post_error)
- {
- if ($post_error == 'long_message')
+ foreach ($post_errors as $post_error) {
+ if ($post_error == 'long_message') {
Utils::$context['message']['errors'][] = sprintf(Lang::$txt['error_' . $post_error], Config::$modSettings['max_messageLength']);
- else
+ } else {
Utils::$context['message']['errors'][] = Lang::$txt['error_' . $post_error];
+ }
}
}
// Allow mods to do something with Utils::$context before we return.
IntegrationHook::call('integrate_jsmodify_xml');
- }
- else
- {
+ } else {
Utils::obExit(false);
}
}
@@ -388,8 +342,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;
}
@@ -412,15 +367,17 @@ public static function call(): void
protected function __construct()
{
// We have to have a topic!
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
Utils::obExit(false);
+ }
User::$me->checkSession('get');
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\JavaScriptModify::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\JavaScriptModify::exportStatic')) {
JavaScriptModify::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Like.php b/Sources/Actions/Like.php
index 1ad185bd56..7b844c79c4 100644
--- a/Sources/Actions/Like.php
+++ b/Sources/Actions/Like.php
@@ -14,15 +14,15 @@
namespace SMF\Actions;
use SMF\Alert;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Theme;
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* Handles liking posts and displaying the list of who liked a post.
@@ -55,20 +55,20 @@ class Like implements ActionInterface
* called internally by the like() method. Moreover, the control flow
* regarding hooks, etc., assumes that they are only called by like().
*/
- public static array $subactions = array(
+ public static array $subactions = [
'like' => 'like',
'view' => 'view',
'delete' => 'delete',
'insert' => 'insert',
'count' => 'count',
- );
+ ];
/*********************
* Internal properties
*********************/
/**
- * @var boolean
+ * @var bool
*
* Know if a request comes from an ajax call or not.
* Depends on $_GET['js'] been set.
@@ -100,21 +100,21 @@ class Like implements ActionInterface
protected $extra = false;
/**
- * @var integer
+ * @var int
*
* A valid ID to identify the content being liked.
*/
protected $content = 0;
/**
- * @var integer
+ * @var int
*
* The number of times the content has been liked.
*/
protected $num_likes = 0;
/**
- * @var boolean
+ * @var bool
*
* If the current user has already liked this content.
*/
@@ -147,24 +147,24 @@ class Like implements ActionInterface
* 'json' bool If true, the class will return a JSON object as
* a response instead of HTML. Default: false.
*/
- protected $valid_likes = array(
+ protected $valid_likes = [
'can_like' => false,
'redirect' => '',
'type' => '',
'flush_cache' => '',
'callback' => false,
'json' => false,
- );
+ ];
/**
- * @var integer
+ * @var int
*
* The topic ID. Used for liking messages.
*/
protected $id_topic = 0;
/**
- * @var boolean
+ * @var bool
*
* Whether respond() will be executed as normal.
*
@@ -208,30 +208,27 @@ public function execute(): void
// Make sure the user can see and like your content.
$this->check();
- if (is_string($this->error))
- {
+ if (is_string($this->error)) {
$this->respond();
+
return;
}
// So at this point, whatever type of like the user supplied and the
// item of content in question, we know it exists.
// Now we need to figure out what we're doing with that.
- if (isset(self::$subactions[$this->subaction]))
- {
+ if (isset(self::$subactions[$this->subaction])) {
// Guest can only view likes.
- if ($this->subaction != 'view')
+ if ($this->subaction != 'view') {
User::$me->kickIfGuest();
+ }
User::$me->checkSession('get');
// Call the appropriate method.
- if (method_exists($this, self::$subactions[$this->subaction]))
- {
- call_user_func(array($this, self::$subactions[$this->subaction]));
- }
- else
- {
+ if (method_exists($this, self::$subactions[$this->subaction])) {
+ call_user_func([$this, self::$subactions[$this->subaction]]);
+ } else {
call_user_func(self::$subactions[$this->subaction]);
}
}
@@ -265,8 +262,9 @@ public function get($property = ''): mixed
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -289,11 +287,13 @@ public static function call(): void
*/
protected function __construct()
{
- if (!empty($_REQUEST['sa']) && $_REQUEST['sa'] === '_count')
+ if (!empty($_REQUEST['sa']) && $_REQUEST['sa'] === '_count') {
$_REQUEST['sa'] = 'count';
+ }
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
+ }
$this->type = $_GET['ltype'] ?? '';
$this->content = (int) ($_GET['like'] ?? 0);
@@ -301,8 +301,9 @@ protected function __construct()
$this->extra = $_GET['extra'] ?? false;
// We do not want to output debug information here.
- if ($this->js)
+ if ($this->js) {
Config::$db_show_debug = false;
+ }
}
/**
@@ -314,50 +315,50 @@ protected function __construct()
protected function check(): void
{
// This feature is currently disable.
- if (empty(Config::$modSettings['enable_likes']))
- {
+ if (empty(Config::$modSettings['enable_likes'])) {
$this->error = 'like_disable';
+
return;
}
// Zerothly, they did indicate some kind of content to like, right?
preg_match('~^([a-z0-9\-\_]{1,6})~i', $this->type, $matches);
- $this->type = isset($matches[1]) ? $matches[1] : '';
+ $this->type = $matches[1] ?? '';
- if ($this->type == '' || $this->content <= 0)
- {
+ if ($this->type == '' || $this->content <= 0) {
$this->error = 'cannot_';
+
return;
}
// First we need to verify whether the user can see the type of content.
// This is set up to be extensible, so we'll check for the one type we
// do know about, and if it's not that, we'll defer to any hooks.
- if ($this->type == 'msg')
- {
+ if ($this->type == 'msg') {
// So we're doing something off a like. We need to verify that it
// exists, and that the current user can see it. Fortunately, this
// is quite easy to do for messages - and we'll get the topic ID
// while we're at it, because we need it later for other things.
- $request = Db::$db->query('', '
- SELECT m.id_topic, m.id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_topic, m.id_member
FROM {db_prefix}messages AS m
WHERE {query_see_message_board}
AND m.id_msg = {int:msg}',
- array(
+ [
'msg' => $this->content,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 1)
- {
+
+ if (Db::$db->num_rows($request) == 1) {
list($this->id_topic, $topicOwner) = Db::$db->fetch_row($request);
}
Db::$db->free_result($request);
- if (empty($this->id_topic))
- {
+ if (empty($this->id_topic)) {
$this->error = 'cannot_';
+
return;
}
@@ -368,9 +369,7 @@ protected function check(): void
$this->valid_likes['redirect'] = 'topic=' . $this->id_topic . '.msg' . $this->content . '#msg' . $this->content;
$this->valid_likes['can_like'] = (User::$me->id == $topicOwner ? 'cannot_like_content' : (User::$me->allowedTo('likes_like') ? true : 'cannot_like_content'));
- }
- else
- {
+ } else {
/*
* MOD AUTHORS: This will give you whatever the user offers up in
* terms of liking, e.g. $this->type=msg, $this->content=1.
@@ -388,22 +387,19 @@ protected function check(): void
*
* See also issueLike() for further notes.
*/
- $can_like = IntegrationHook::call('integrate_valid_likes', array($this->type, $this->content, $this->subaction, $this->js, $this->extra));
+ $can_like = IntegrationHook::call('integrate_valid_likes', [$this->type, $this->content, $this->subaction, $this->js, $this->extra]);
$found = false;
- if (!empty($can_like))
- {
+ if (!empty($can_like)) {
$can_like = (array) $can_like;
- foreach ($can_like as $result)
- {
- if ($result !== false)
- {
+ foreach ($can_like as $result) {
+ if ($result !== false) {
// Match the type with what we already have.
- if (!isset($result['type']) || $result['type'] != $this->type)
- {
+ if (!isset($result['type']) || $result['type'] != $this->type) {
$this->error = 'not_valid_like_type';
+
return;
}
@@ -412,24 +408,23 @@ protected function check(): void
$this->valid_likes = array_merge($this->valid_likes, $result);
$found = true;
-
break;
}
}
}
- if (!$found)
- {
+ if (!$found) {
$this->error = 'cannot_';
+
return;
}
}
// Is the user able to like this?
// Viewing a list of likes doesn't require this permission.
- if ($this->subaction != 'view' && isset($this->valid_likes['can_like']) && is_string($this->valid_likes['can_like']))
- {
+ if ($this->subaction != 'view' && isset($this->valid_likes['can_like']) && is_string($this->valid_likes['can_like'])) {
$this->error = $this->valid_likes['can_like'];
+
return;
}
}
@@ -439,38 +434,40 @@ protected function check(): void
*/
protected function delete(): void
{
- Db::$db->query('', '
- DELETE FROM {db_prefix}user_likes
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}user_likes
WHERE content_id = {int:like_content}
AND content_type = {string:like_type}
AND id_member = {int:id_member}',
- array(
+ [
'like_content' => $this->content,
'like_type' => $this->type,
'id_member' => User::$me->id,
- )
+ ],
);
// Are we calling this directly? If so, set the data for the response.
- if ($this->subaction == __FUNCTION__)
+ if ($this->subaction == __FUNCTION__) {
$this->data = __FUNCTION__;
+ }
// Check to see if there is an unread alert to delete as well...
Alert::deleteWhere(
- array(
+ [
'content_id = {int:like_content}',
'content_type = {string:like_type}',
'id_member_started = {int:id_member_started}',
'content_action = {string:content_action}',
- 'is_read = {int:unread}'
- ),
- array(
+ 'is_read = {int:unread}',
+ ],
+ [
'like_content' => $this->content,
'like_type' => $this->type,
'id_member_started' => User::$me->id,
'content_action' => 'like',
'unread' => 0,
- )
+ ],
);
}
@@ -488,63 +485,63 @@ protected function insert(): void
$user = (array) User::$me;
$time = time();
- IntegrationHook::call('integrate_issue_like_before', array(&$type, &$content, &$user, &$time));
+ IntegrationHook::call('integrate_issue_like_before', [&$type, &$content, &$user, &$time]);
// Insert the like.
- Db::$db->insert('insert',
+ Db::$db->insert(
+ 'insert',
'{db_prefix}user_likes',
- array(
+ [
'content_id' => 'int',
'content_type' => 'string-6',
'id_member' => 'int',
'like_time' => 'int',
- ),
- array(
+ ],
+ [
$content,
$type,
$user['id'],
$time,
- ),
- array(
+ ],
+ [
'content_id',
'content_type',
'id_member',
- )
+ ],
);
// Add a background task to process sending alerts.
// MOD AUTHORS: you can add your own background task for your own custom
// like event using the "integrate_issue_like" hook or your callback,
// both are immediately called after this.
- if ($this->type == 'msg')
- {
- Db::$db->insert('insert',
+ if ($this->type == 'msg') {
+ Db::$db->insert(
+ 'insert',
'{db_prefix}background_tasks',
- array(
- 'task_file' => 'string',
+ [
'task_class' => 'string',
'task_data' => 'string',
'claimed_time' => 'int',
- ),
- array(
- '$sourcedir/tasks/Likes_Notify.php',
- 'SMF\Tasks\Likes_Notify',
- Utils::jsonEncode(array(
+ ],
+ [
+ 'SMF\\Tasks\\Likes_Notify',
+ Utils::jsonEncode([
'content_id' => $content,
'content_type' => $type,
'sender_id' => $user['id'],
'sender_name' => $user['name'],
'time' => $time,
- )),
+ ]),
0,
- ),
- array('id_task')
+ ],
+ ['id_task'],
);
}
// Are we calling this directly? If so, set the data for the response.
- if ($this->subaction == __FUNCTION__)
+ if ($this->subaction == __FUNCTION__) {
$this->data = __FUNCTION__;
+ }
}
/**
@@ -552,21 +549,23 @@ protected function insert(): void
*/
protected function count(): void
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}user_likes
WHERE content_id = {int:like_content}
AND content_type = {string:like_type}',
- array(
+ [
'like_content' => $this->content,
'like_type' => $this->type,
- )
+ ],
);
list($this->num_likes) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- if ($this->subaction == __FUNCTION__)
+ if ($this->subaction == __FUNCTION__) {
$this->data = $this->num_likes;
+ }
}
/**
@@ -577,34 +576,32 @@ protected function count(): void
protected function like(): void
{
// Safety first!
- if (empty($this->type) || empty($this->content))
- {
+ if (empty($this->type) || empty($this->content)) {
$this->error = 'cannot_';
+
return;
}
// Do we already like this?
- $request = Db::$db->query('', '
- SELECT content_id, content_type, id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT content_id, content_type, id_member
FROM {db_prefix}user_likes
WHERE content_id = {int:like_content}
AND content_type = {string:like_type}
AND id_member = {int:id_member}',
- array(
+ [
'like_content' => $this->content,
'like_type' => $this->type,
'id_member' => User::$me->id,
- )
+ ],
);
$this->already_liked = Db::$db->num_rows($request) != 0;
Db::$db->free_result($request);
- if ($this->already_liked)
- {
+ if ($this->already_liked) {
$this->delete();
- }
- else
- {
+ } else {
$this->insert();
}
@@ -613,47 +610,48 @@ protected function like(): void
$this->count();
// Update the likes count for messages.
- if ($this->type == 'msg')
- {
- Db::$db->query('', '
- UPDATE {db_prefix}messages
+ if ($this->type == 'msg') {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}messages
SET likes = {int:num_likes}
WHERE id_msg = {int:id_msg}',
- array(
+ [
'id_msg' => $this->content,
'num_likes' => $this->num_likes,
- )
+ ],
);
}
// Any callbacks?
- elseif (!empty($this->valid_likes['callback']))
- {
+ elseif (!empty($this->valid_likes['callback'])) {
$call = Utils::getCallable($this->valid_likes['callback']);
- if (!empty($call))
- call_user_func_array($call, array($this));
+ if (!empty($call)) {
+ call_user_func_array($call, [$this]);
+ }
}
// Sometimes there might be other things that need updating after we do this like.
- IntegrationHook::call('integrate_issue_like', array($this));
+ IntegrationHook::call('integrate_issue_like', [$this]);
// Now some clean up. This is provided here for any like handlers that
// want to do any cache flushing.
// This way a like handler doesn't need to explicitly declare anything
// in integrate_issue_like, but do so in integrate_valid_likes where it
// absolutely has to exist.
- if (!empty($this->valid_likes['flush_cache']))
+ if (!empty($this->valid_likes['flush_cache'])) {
CacheApi::put($this->valid_likes['flush_cache'], null);
+ }
// All done, start building the data to pass as response.
- $this->data = array(
+ $this->data = [
'id_topic' => !empty($this->id_topic) ? $this->id_topic : 0,
'id_content' => $this->content,
'count' => $this->num_likes,
'can_like' => $this->valid_likes['can_like'],
'already_liked' => empty($this->already_liked),
'type' => $this->type,
- );
+ ];
}
/**
@@ -667,22 +665,23 @@ protected function like(): void
protected function view(): void
{
// Firstly, load what we need. We already know we can see this, so that's something.
- Utils::$context['likers'] = array();
+ Utils::$context['likers'] = [];
- $request = Db::$db->query('', '
- SELECT id_member, like_time
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, like_time
FROM {db_prefix}user_likes
WHERE content_id = {int:like_content}
AND content_type = {string:like_type}
ORDER BY like_time DESC',
- array(
+ [
'like_content' => $this->content,
'like_type' => $this->type,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- Utils::$context['likers'][$row['id_member']] = array('timestamp' => $row['like_time']);
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ Utils::$context['likers'][$row['id_member']] = ['timestamp' => $row['like_time']];
}
Db::$db->free_result($request);
@@ -690,19 +689,18 @@ protected function view(): void
$members = array_keys(Utils::$context['likers']);
$loaded = User::load($members);
- if (count($loaded) != count($members))
- {
- $members = array_diff($members, array_map(fn($member) => $member->id, $loaded));
+ if (count($loaded) != count($members)) {
+ $members = array_diff($members, array_map(fn ($member) => $member->id, $loaded));
- foreach ($members as $not_loaded)
+ foreach ($members as $not_loaded) {
unset(Utils::$context['likers'][$not_loaded]);
+ }
}
- foreach (Utils::$context['likers'] as $liker => $dummy)
- {
- if (!isset(User::$loaded[$liker]))
- {
+ foreach (Utils::$context['likers'] as $liker => $dummy) {
+ if (!isset(User::$loaded[$liker])) {
unset(Utils::$context['likers'][$liker]);
+
continue;
}
@@ -717,7 +715,7 @@ protected function view(): void
// Lastly, setting up for display.
Theme::loadTemplate('Likes');
Lang::load('Help'); // For the close window button.
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
Utils::$context['sub_template'] = 'popup';
// We already took care of our response so there is no need to bother with respond().
@@ -732,68 +730,61 @@ protected function view(): void
protected function respond(): void
{
// Don't do anything if someone else has already take care of the response.
- if (!$this->set_response)
+ if (!$this->set_response) {
return;
+ }
// Want a JSON response, do they?
- if ($this->valid_likes['json'])
- {
+ if ($this->valid_likes['json']) {
$this->sendJsonReponse();
+
return;
}
// Set everything up for display.
Theme::loadTemplate('Likes');
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
// If there are any errors, process them first.
- if ($this->error)
- {
+ if ($this->error) {
// If this is a generic error, set it up good.
- if ($this->error == 'cannot_')
- {
+ if ($this->error == 'cannot_') {
$this->error = $this->subaction == 'view' ? 'cannot_view_likes' : 'cannot_like_content';
}
// Is this request coming from an AJAX call?
- if ($this->js)
- {
+ if ($this->js) {
Utils::$context['sub_template'] = 'generic';
- Utils::$context['data'] = isset(Lang::$txt[$this->error]) ? Lang::$txt[$this->error] : Lang::$txt['like_error'];
+ Utils::$context['data'] = Lang::$txt[$this->error] ?? Lang::$txt['like_error'];
}
// Nope? Then just do a redirect to whatever URL was provided.
- else
- {
+ else {
Utils::redirectexit(!empty($this->valid_likes['redirect']) ? $this->valid_likes['redirect'] . ';error=' . $this->error : '');
}
return;
}
+
// A like operation.
- else
- {
- // Not an AJAX request so send the user back to the previous
- // location or the main page.
- if (!$this->js)
- {
- Utils::redirectexit(!empty($this->valid_likes['redirect']) ? $this->valid_likes['redirect'] : '');
- }
- // These fine gentlemen all share the same template.
- $generic = array('delete', 'insert', 'count');
+ // Not an AJAX request so send the user back to the previous
+ // location or the main page.
+ if (!$this->js) {
+ Utils::redirectexit(!empty($this->valid_likes['redirect']) ? $this->valid_likes['redirect'] : '');
+ }
- if (in_array($this->subaction, $generic))
- {
- Utils::$context['sub_template'] = 'generic';
- Utils::$context['data'] = isset(Lang::$txt['like_' . $this->data]) ? Lang::$txt['like_' . $this->data] : $this->data;
- }
- // Directly pass the current called sub-action and the data
- // generated by its associated Method.
- else
- {
- Utils::$context['sub_template'] = $this->subaction;
- Utils::$context['data'] = $this->data;
- }
+ // These fine gentlemen all share the same template.
+ $generic = ['delete', 'insert', 'count'];
+
+ if (in_array($this->subaction, $generic)) {
+ Utils::$context['sub_template'] = 'generic';
+ Utils::$context['data'] = Lang::$txt['like_' . $this->data] ?? $this->data;
+ }
+ // Directly pass the current called sub-action and the data
+ // generated by its associated Method.
+ else {
+ Utils::$context['sub_template'] = $this->subaction;
+ Utils::$context['data'] = $this->data;
}
}
@@ -802,15 +793,13 @@ protected function respond(): void
*/
protected function sendJsonReponse(): void
{
- $print = array(
+ $print = [
'data' => $this->data,
- );
+ ];
// If there is an error, send it.
- if ($this->error)
- {
- if ($this->error == 'cannot_')
- {
+ if ($this->error) {
+ if ($this->error == 'cannot_') {
$this->error = $this->subaction == 'view' ? 'cannot_view_likes' : 'cannot_like_content';
}
@@ -818,10 +807,11 @@ protected function sendJsonReponse(): void
}
// Do you want to add something at the very last minute?
- IntegrationHook::call('integrate_likes_json_response', array(&$print));
+ IntegrationHook::call('integrate_likes_json_response', [&$print]);
// Print the data.
Utils::serverResponse(Utils::jsonEncode($print));
+
die;
}
@@ -849,33 +839,36 @@ public static function BookOfUnknown()
';
- if (!isset($_GET['verse']) || ($_GET['verse'] != '2:18' && $_GET['verse'] != '22:1-2'))
+ if (!isset($_GET['verse']) || ($_GET['verse'] != '2:18' && $_GET['verse'] != '22:1-2')) {
$_GET['verse'] = '4:16';
+ }
- if ($_GET['verse'] == '2:18')
+ if ($_GET['verse'] == '2:18') {
echo '
Woe, it was that his name wasn\'t known, that he came in mystery, and was recognized by none. And it became to be in those days something. Something not yet unknown to mankind. And thus what was to be known the secret project began into its existence. Henceforth the opposition was only weary and fearful, for now their match was at arms against them.';
- elseif ($_GET['verse'] == '4:16')
+ } elseif ($_GET['verse'] == '4:16') {
echo '
And it came to pass that the unbelievers dwindled in number and saw rise of many proselytizers, and the opposition found fear in the face of the x and the j while those who stood with the something grew stronger and came together. Still, this was only the beginning, and what lay in the future was unknown to all, even those on the right side.';
- elseif ($_GET['verse'] == '22:1-2')
+ } elseif ($_GET['verse'] == '22:1-2') {
echo '
Now behold, that which was once the secret project was unknown no longer. Alas, it needed more than only one, but yet even thought otherwise. It became that the opposition rumored and lied, but still to no avail. Their match, though not perfect, had them outdone.
Let it continue. The end. ';
+ }
echo '
';
- if ($_GET['verse'] == '2:18')
+ if ($_GET['verse'] == '2:18') {
echo '
from The Book of Unknown, 2:18';
- elseif ($_GET['verse'] == '4:16')
+ } elseif ($_GET['verse'] == '4:16') {
echo '
from The Book of Unknown, 4:16';
- elseif ($_GET['verse'] == '22:1-2')
+ } elseif ($_GET['verse'] == '22:1-2') {
echo '
from The Book of Unknown, 22:1-2';
+ }
echo '
diff --git a/Sources/Actions/Login.php b/Sources/Actions/Login.php
index 08649184bf..e955bb845a 100644
--- a/Sources/Actions/Login.php
+++ b/Sources/Actions/Login.php
@@ -14,7 +14,6 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\Lang;
use SMF\SecurityToken;
@@ -34,12 +33,11 @@ class Login extends Login2
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'Login',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -69,15 +67,11 @@ class Login extends Login2
public function execute(): void
{
// You are already logged in, go take a tour of the boards
- if (!empty(User::$me->id))
- {
- // This came from a valid hashed return url. Or something that knows our secrets...
- if (!empty($_REQUEST['return_hash']) && !empty($_REQUEST['return_to']) && hash_hmac('sha1', Utils::htmlspecialcharsDecode($_REQUEST['return_to']), Config::getAuthSecret()) == $_REQUEST['return_hash'])
- {
+ if (!empty(User::$me->id)) {
+ // This came from a valid hashed return url. Or something that knows our secrets...
+ if (!empty($_REQUEST['return_hash']) && !empty($_REQUEST['return_to']) && hash_hmac('sha1', Utils::htmlspecialcharsDecode($_REQUEST['return_to']), Config::getAuthSecret()) == $_REQUEST['return_hash']) {
Utils::redirectexit(Utils::htmlspecialcharsDecode($_REQUEST['return_to']));
- }
- else
- {
+ } else {
Utils::redirectexit();
}
}
@@ -97,23 +91,19 @@ public function execute(): void
Utils::$context['never_expire'] = false;
// Add the login chain to the link tree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=login',
'name' => Lang::$txt['login'],
- );
+ ];
// Set the login URL - will be used when the login process is done (but careful not to send us to an attachment).
- if (isset($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'dlattach') === false && preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0)
- {
+ if (isset($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'dlattach') === false && preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0) {
$_SESSION['login_url'] = $_SESSION['old_url'];
}
// This came from a valid hashed return url. Or something that knows our secrets...
- elseif (!empty($_REQUEST['return_hash']) && !empty($_REQUEST['return_to']) && hash_hmac('sha1', Utils::htmlspecialcharsDecode($_REQUEST['return_to']), Config::getAuthSecret()) == $_REQUEST['return_hash'])
- {
+ elseif (!empty($_REQUEST['return_hash']) && !empty($_REQUEST['return_to']) && hash_hmac('sha1', Utils::htmlspecialcharsDecode($_REQUEST['return_to']), Config::getAuthSecret()) == $_REQUEST['return_hash']) {
$_SESSION['login_url'] = Utils::htmlspecialcharsDecode($_REQUEST['return_to']);
- }
- elseif (isset($_SESSION['login_url']) && strpos($_SESSION['login_url'], 'dlattach') !== false)
- {
+ } elseif (isset($_SESSION['login_url']) && strpos($_SESSION['login_url'], 'dlattach') !== false) {
unset($_SESSION['login_url']);
}
@@ -132,8 +122,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;
}
@@ -159,7 +150,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Login::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Login::exportStatic')) {
Login::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Login2.php b/Sources/Actions/Login2.php
index 66345bfa7b..390fccd62d 100644
--- a/Sources/Actions/Login2.php
+++ b/Sources/Actions/Login2.php
@@ -14,9 +14,9 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\Cookie;
+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;
/**
* Validates the submitted credentials and logs the user in if they pass.
@@ -39,12 +38,13 @@ class Login2 implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'Login2',
- ),
- );
+ 'checkAjax' => 'checkAjax',
+ 'validatePasswordFlood' => 'validatePasswordFlood',
+ ],
+ ];
/*******************
* Public properties
@@ -67,11 +67,11 @@ class Login2 implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'main' => 'main',
'salt' => 'updateSalt',
'check' => 'checkCookie',
- );
+ ];
/****************************
* Internal static properties
@@ -105,15 +105,17 @@ class Login2 implements ActionInterface
public function execute(): void
{
// Check to ensure we're forcing SSL for authentication
- if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn())
+ if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn()) {
ErrorHandler::fatalLang('login_ssl_required', false);
+ }
self::checkAjax();
- $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);
+ }
}
/**
@@ -121,42 +123,36 @@ public function execute(): void
*/
public function updateSalt(): void
{
- if (User::$me->is_guest)
+ if (User::$me->is_guest) {
return;
+ }
// First check for 2.1 json-format cookie in $_COOKIE
- if (isset($_COOKIE[Config::$cookiename]) && preg_match('~^{"0":\d+,"1":"[0-9a-f]*","2":\d+~', $_COOKIE[Config::$cookiename]) === 1)
- {
- list(,, $timeout) = Utils::jsonDecode($_COOKIE[Config::$cookiename], true);
+ if (isset($_COOKIE[Config::$cookiename]) && preg_match('~^{"0":\d+,"1":"[0-9a-f]*","2":\d+~', $_COOKIE[Config::$cookiename]) === 1) {
+ list(, , $timeout) = Utils::jsonDecode($_COOKIE[Config::$cookiename], true);
}
// Try checking for 2.1 json-format cookie in $_SESSION
- elseif (isset($_SESSION['login_' . Config::$cookiename]) && preg_match('~^{"0":\d+,"1":"[0-9a-f]*","2":\d+~', $_SESSION['login_' . Config::$cookiename]) === 1)
- {
- list(,, $timeout) = Utils::jsonDecode($_SESSION['login_' . Config::$cookiename]);
+ elseif (isset($_SESSION['login_' . Config::$cookiename]) && preg_match('~^{"0":\d+,"1":"[0-9a-f]*","2":\d+~', $_SESSION['login_' . Config::$cookiename]) === 1) {
+ list(, , $timeout) = Utils::jsonDecode($_SESSION['login_' . Config::$cookiename]);
}
// Next, try checking for 2.0 serialized string cookie in $_COOKIE
- elseif (isset($_COOKIE[Config::$cookiename]) && preg_match('~^a:[34]:\{i:0;i:\d+;i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d+;~', $_COOKIE[Config::$cookiename]) === 1)
- {
- list(,, $timeout) = Utils::safeUnserialize($_COOKIE[Config::$cookiename]);
+ elseif (isset($_COOKIE[Config::$cookiename]) && preg_match('~^a:[34]:\{i:0;i:\d+;i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d+;~', $_COOKIE[Config::$cookiename]) === 1) {
+ list(, , $timeout) = Utils::safeUnserialize($_COOKIE[Config::$cookiename]);
}
// Last, see if you need to fall back on checking for 2.0 serialized string cookie in $_SESSION
- elseif (isset($_SESSION['login_' . Config::$cookiename]) && preg_match('~^a:[34]:\{i:0;i:\d+;i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d+;~', $_SESSION['login_' . Config::$cookiename]) === 1)
- {
- list(,, $timeout) = Utils::safeUnserialize($_SESSION['login_' . Config::$cookiename]);
- }
- else
- {
+ elseif (isset($_SESSION['login_' . Config::$cookiename]) && preg_match('~^a:[34]:\{i:0;i:\d+;i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d+;~', $_SESSION['login_' . Config::$cookiename]) === 1) {
+ list(, , $timeout) = Utils::safeUnserialize($_SESSION['login_' . Config::$cookiename]);
+ } else {
Lang::load('Errors');
trigger_error(Lang::$txt['login_no_session_cookie'], E_USER_ERROR);
}
User::$me->password_salt = bin2hex(Utils::randomBytes(16));
- User::updateMemberData(User::$me->id, array('password_salt' => User::$me->password_salt));
+ User::updateMemberData(User::$me->id, ['password_salt' => User::$me->password_salt]);
// Preserve the 2FA cookie?
- if (!empty(Config::$modSettings['tfa_mode']) && !empty($_COOKIE[Config::$cookiename . '_tfa']))
- {
- list(,, $exp) = Utils::jsonDecode($_COOKIE[Config::$cookiename . '_tfa'], true);
+ if (!empty(Config::$modSettings['tfa_mode']) && !empty($_COOKIE[Config::$cookiename . '_tfa'])) {
+ list(, , $exp) = Utils::jsonDecode($_COOKIE[Config::$cookiename . '_tfa'], true);
Cookie::setTFACookie((int) $exp - time(), User::$me->password_salt, Cookie::encrypt(User::$me->tfa_backup, User::$me->password_salt));
}
@@ -171,27 +167,21 @@ public function updateSalt(): void
public function checkCookie(): void
{
// Strike! You're outta there!
- if ($_GET['member'] != User::$me->id)
+ if ($_GET['member'] != User::$me->id) {
ErrorHandler::fatalLang('login_cookie_error', false);
+ }
User::$me->can_mod = User::$me->allowedTo('access_mod_center') || (!User::$me->is_guest && (User::$me->mod_cache['gq'] != '0=1' || User::$me->mod_cache['bq'] != '0=1' || (Config::$modSettings['postmod_active'] && !empty(User::$me->mod_cache['ap']))));
// Some whitelisting for login_url...
- if (empty($_SESSION['login_url']))
- {
+ if (empty($_SESSION['login_url'])) {
Utils::redirectexit(empty(User::$me->tfa_secret) ? '' : 'action=logintfa');
- }
- elseif (!empty($_SESSION['login_url']) && (strpos($_SESSION['login_url'], 'http://') === false && strpos($_SESSION['login_url'], 'https://') === false))
- {
+ } elseif (!empty($_SESSION['login_url']) && (strpos($_SESSION['login_url'], 'http://') === false && strpos($_SESSION['login_url'], 'https://') === false)) {
unset($_SESSION['login_url']);
Utils::redirectexit(empty(User::$me->tfa_secret) ? '' : 'action=logintfa');
- }
- elseif (!empty(User::$me->tfa_secret))
- {
+ } elseif (!empty(User::$me->tfa_secret)) {
Utils::redirectexit('action=logintfa');
- }
- else
- {
+ } else {
// Best not to clutter the session data too much...
$temp = $_SESSION['login_url'];
unset($_SESSION['login_url']);
@@ -206,8 +196,9 @@ public function checkCookie(): void
public function main(): void
{
// Beyond this point you are assumed to be a guest trying to login.
- if (!User::$me->is_guest)
+ if (!User::$me->is_guest) {
Utils::redirectexit();
+ }
// Are you guessing with a script?
User::$me->checkSession();
@@ -223,12 +214,11 @@ public function main(): void
&& preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0
)
|| (
- isset($_GET['quicklogin'])
- && isset($_SESSION['old_url'])
+ isset($_GET['quicklogin'], $_SESSION['old_url'])
+
&& strpos($_SESSION['old_url'], 'login') === false
)
- )
- {
+ ) {
$_SESSION['login_url'] = $_SESSION['old_url'];
}
@@ -236,8 +226,7 @@ public function main(): void
if (
isset($_SESSION['failed_login'])
&& $_SESSION['failed_login'] >= Config::$modSettings['failed_login_threshold'] * 3
- )
- {
+ ) {
ErrorHandler::fatalLang('login_threshold_fail', 'login');
}
@@ -248,18 +237,15 @@ public function main(): void
!empty($_POST['cookielength'])
&& $_POST['cookielength'] == -1
)
- )
- {
+ ) {
Config::$modSettings['cookieTime'] = 3153600;
- }
- elseif (
+ } elseif (
!empty($_POST['cookielength'])
&& (
$_POST['cookielength'] >= 1
&& $_POST['cookielength'] <= 3153600
)
- )
- {
+ ) {
Config::$modSettings['cookieTime'] = (int) $_POST['cookielength'];
}
@@ -273,26 +259,27 @@ public function main(): void
SecurityToken::create('login');
// Set up the default/fallback stuff.
- Utils::$context['default_username'] = isset($_POST['user']) ? preg_replace('~&#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '\\1;', Utils::htmlspecialchars($_POST['user'])) : '';
+ Utils::$context['default_username'] = isset($_POST['user']) ? preg_replace('~&#(\d{1,7}|x[0-9a-fA-F]{1,6});~', '$1;', Utils::htmlspecialchars($_POST['user'])) : '';
Utils::$context['default_password'] = '';
Utils::$context['never_expire'] = Config::$modSettings['cookieTime'] <= 525600;
- Utils::$context['login_errors'] = array(Lang::$txt['error_occured']);
+ Utils::$context['login_errors'] = [Lang::$txt['error_occured']];
Utils::$context['page_title'] = Lang::$txt['login'];
// Add the login chain to the link tree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=login',
'name' => Lang::$txt['login'],
- );
+ ];
// Bail out if the username and/or password are obviously invalid.
- if (!$this->validateInput())
+ if (!$this->validateInput()) {
return;
+ }
// Are we using any sort of integration to validate the login?
- if (in_array('retry', IntegrationHook::call('integrate_validate_login', array($_POST['user'], isset($_POST['passwrd']) ? $_POST['passwrd'] : null, Config::$modSettings['cookieTime'])), true))
- {
- Utils::$context['login_errors'] = array(Lang::$txt['incorrect_password']);
+ if (in_array('retry', IntegrationHook::call('integrate_validate_login', [$_POST['user'], $_POST['passwrd'] ?? null, Config::$modSettings['cookieTime']]), true)) {
+ Utils::$context['login_errors'] = [Lang::$txt['incorrect_password']];
+
return;
}
@@ -300,47 +287,47 @@ public function main(): void
$loaded = User::load($_POST['user'], User::LOAD_BY_NAME, 'minimal');
// Probably mistyped or their email, try it as an email address. (member_name first, though!)
- if (empty($loaded))
+ if (empty($loaded)) {
$loaded = User::load($_POST['user'], User::LOAD_BY_EMAIL, 'minimal');
+ }
// Let them try again, it didn't match anything...
- if (empty($loaded))
- {
- Utils::$context['login_errors'] = array(Lang::$txt['username_no_exist']);
+ if (empty($loaded)) {
+ Utils::$context['login_errors'] = [Lang::$txt['username_no_exist']];
+
return;
}
User::$my_id = (reset($loaded))->id;
// Bad password! Thought you could fool the database?!
- if (!Security::hashVerifyPassword(User::$profiles[User::$my_id]['member_name'], Utils::htmlspecialcharsDecode($_POST['passwrd']), User::$profiles[User::$my_id]['passwd']))
- {
+ if (!Security::hashVerifyPassword(User::$profiles[User::$my_id]['member_name'], Utils::htmlspecialcharsDecode($_POST['passwrd']), User::$profiles[User::$my_id]['passwd'])) {
// If the forum was recently upgraded, password might be encrypted
// using a different algorithm. If so, fix it. Otherwise, bail out.
- if (!$this->checkPasswordFallbacks())
+ if (!$this->checkPasswordFallbacks()) {
return;
+ }
}
// Correct password, but it took multiple tries...
- elseif (!empty(User::$profiles[User::$my_id]['passwd_flood']))
- {
+ elseif (!empty(User::$profiles[User::$my_id]['passwd_flood'])) {
// Let's be sure they weren't a little hacker.
self::validatePasswordFlood(User::$profiles[User::$my_id]['id_member'], User::$profiles[User::$my_id]['member_name'], User::$profiles[User::$my_id]['passwd_flood'], true);
// If we got here then we can reset the flood counter.
- User::updateMemberData(User::$profiles[User::$my_id]['id_member'], array('passwd_flood' => ''));
+ User::updateMemberData(User::$profiles[User::$my_id]['id_member'], ['passwd_flood' => '']);
}
// Correct password, but they've got no salt. Fix it!
- if (strlen(User::$profiles[User::$my_id]['password_salt']) < 32)
- {
+ if (strlen(User::$profiles[User::$my_id]['password_salt']) < 32) {
User::$profiles[User::$my_id]['password_salt'] = bin2hex(Utils::randomBytes(16));
- User::updateMemberData(User::$profiles[User::$my_id]['id_member'], array('password_salt' => User::$profiles[User::$my_id]['password_salt']));
+ User::updateMemberData(User::$profiles[User::$my_id]['id_member'], ['password_salt' => User::$profiles[User::$my_id]['password_salt']]);
}
// Check their activation status.
- if (!$this->checkActivation())
+ if (!$this->checkActivation()) {
return;
+ }
$this->DoLogin();
}
@@ -356,8 +343,9 @@ public function main(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -400,16 +388,14 @@ public static function checkAjax(): void
!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'
)
- ||
- (
+ || (
!empty(Utils::$context['valid_cors_found'])
&& !empty($_SERVER['HTTP_X_SMF_AJAX'])
&& isset($_REQUEST['ajax'])
)
- )
- {
+ ) {
Utils::$context['from_ajax'] = true;
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
}
}
@@ -429,17 +415,16 @@ public static function validatePasswordFlood($id_member, $member_name, $password
// Destroy any session or cookie data about this member, as they validated wrong.
// Only if they're not validating for 2FA
- if (!$tfa)
- {
+ if (!$tfa) {
Cookie::setLoginCookie(-3600, 0);
- if (isset($_SESSION['login_' . Config::$cookiename]))
+ if (isset($_SESSION['login_' . Config::$cookiename])) {
unset($_SESSION['login_' . Config::$cookiename]);
+ }
}
// We need a member!
- if (!$id_member)
- {
+ if (!$id_member) {
// Redirect back!
Utils::redirectexit();
@@ -448,36 +433,36 @@ public static function validatePasswordFlood($id_member, $member_name, $password
}
// Right, have we got a flood value?
- if ($password_flood_value !== false)
+ if ($password_flood_value !== false) {
@list($time_stamp, $number_tries) = explode('|', $password_flood_value);
+ }
// Timestamp or number of tries invalid?
- if (empty($number_tries) || empty($time_stamp))
- {
+ if (empty($number_tries) || empty($time_stamp)) {
$number_tries = 0;
$time_stamp = time();
}
// They've failed logging in already
- if (!empty($number_tries))
- {
+ if (!empty($number_tries)) {
// Give them less chances if they failed before
$number_tries = $time_stamp < time() - 20 ? 2 : $number_tries;
// They are trying too fast, make them wait longer
- if ($time_stamp < time() - 10)
+ if ($time_stamp < time() - 10) {
$time_stamp = time();
+ }
}
$number_tries++;
// Broken the law?
- if ($number_tries > 5)
+ if ($number_tries > 5) {
ErrorHandler::fatalLang('login_threshold_brute_fail', 'login', [$member_name]);
+ }
// Otherwise set the members data. If they correct on their first attempt then we actually clear it, otherwise we set it!
- User::updateMemberData($id_member, array('passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries));
-
+ User::updateMemberData($id_member, ['passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries]);
}
/******************
@@ -489,8 +474,9 @@ public static function validatePasswordFlood($id_member, $member_name, $password
*/
protected function __construct()
{
- if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
+ if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
+ }
}
/**
@@ -501,31 +487,30 @@ protected function __construct()
protected function validateInput(): bool
{
// You forgot to type your username, dummy!
- if (!isset($_POST['user']) || $_POST['user'] == '')
- {
- Utils::$context['login_errors'] = array(Lang::$txt['need_username']);
+ if (!isset($_POST['user']) || $_POST['user'] == '') {
+ Utils::$context['login_errors'] = [Lang::$txt['need_username']];
+
return false;
}
// Hmm... maybe 'admin' will login with no password. Uhh... NO!
- if (!isset($_POST['passwrd']) || $_POST['passwrd'] == '')
- {
- Utils::$context['login_errors'] = array(Lang::$txt['no_password']);
+ if (!isset($_POST['passwrd']) || $_POST['passwrd'] == '') {
+ Utils::$context['login_errors'] = [Lang::$txt['no_password']];
+
return false;
}
// No funky symbols either.
- if (preg_match('~[<>&"\'=\\\]~', preg_replace('~((\\d{1,7}|x[0-9a-fA-F]{1,6});)~', '', $_POST['user'])) != 0)
- {
- Utils::$context['login_errors'] = array(Lang::$txt['error_invalid_characters_username']);
+ if (preg_match('~[<>&"\'=\\\]~', preg_replace('~((\d{1,7}|x[0-9a-fA-F]{1,6});)~', '', $_POST['user'])) != 0) {
+ Utils::$context['login_errors'] = [Lang::$txt['error_invalid_characters_username']];
+
return false;
}
// And if it's too long, trim it back.
- if (Utils::entityStrlen($_POST['user']) > 80)
- {
+ if (Utils::entityStrlen($_POST['user']) > 80) {
$_POST['user'] = Utils::entitySubstr($_POST['user'], 0, 79);
- Utils::$context['default_username'] = preg_replace('~&#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '\\1;', Utils::htmlspecialchars($_POST['user']));
+ Utils::$context['default_username'] = preg_replace('~&#(\d{1,7}|x[0-9a-fA-F]{1,6});~', '$1;', Utils::htmlspecialchars($_POST['user']));
}
return true;
@@ -548,11 +533,10 @@ protected function checkPasswordFallbacks(): bool
self::validatePasswordFlood(User::$profiles[User::$my_id]['id_member'], User::$profiles[User::$my_id]['member_name'], User::$profiles[User::$my_id]['passwd_flood']);
// Maybe we were too hasty... let's try some other authentication methods.
- $other_passwords = array();
+ $other_passwords = [];
// None of the below cases will be used most of the time (because the salt is normally set.)
- if (!empty(Config::$modSettings['enable_password_conversion']) && User::$profiles[User::$my_id]['password_salt'] == '')
- {
+ if (!empty(Config::$modSettings['enable_password_conversion']) && User::$profiles[User::$my_id]['password_salt'] == '') {
// YaBB SE, Discus, MD5 (used a lot), SHA-1 (used some), SMF 1.0.x, IkonBoard, and none at all.
$other_passwords[] = crypt($_POST['passwrd'], substr($_POST['passwrd'], 0, 2));
$other_passwords[] = crypt($_POST['passwrd'], substr(User::$profiles[User::$my_id]['passwd'], 0, 2));
@@ -568,8 +552,9 @@ protected function checkPasswordFallbacks(): bool
$other_passwords[] = crypt(md5($_POST['passwrd']), md5($_POST['passwrd']));
// Snitz style - SHA-256.
- if (strlen(User::$profiles[User::$my_id]['passwd']) == 64 && function_exists('mhash') && defined('MHASH_SHA256'))
+ if (strlen(User::$profiles[User::$my_id]['passwd']) == 64 && function_exists('mhash') && defined('MHASH_SHA256')) {
$other_passwords[] = bin2hex(mhash(MHASH_SHA256, $_POST['passwrd']));
+ }
// phpBB3.
$other_passwords[] = $this->phpBB3_password_check($_POST['passwrd'], User::$profiles[User::$my_id]['passwd']);
@@ -578,12 +563,10 @@ protected function checkPasswordFallbacks(): bool
$other_passwords[] = md5(crypt($_POST['passwrd'], 'CRYPT_MD5'));
}
// If the salt is set let's try some other options
- elseif (!empty(Config::$modSettings['enable_password_conversion']) && User::$profiles[User::$my_id]['password_salt'] != '')
- {
+ elseif (!empty(Config::$modSettings['enable_password_conversion']) && User::$profiles[User::$my_id]['password_salt'] != '') {
// PHPBB 3 check this function exists in PHP 5.5 or higher
- if (function_exists('password_verify'))
- {
- $other_passwords[] = password_verify($_POST['passwrd'],User::$profiles[User::$my_id]['password_salt']);
+ if (function_exists('password_verify')) {
+ $other_passwords[] = password_verify($_POST['passwrd'], User::$profiles[User::$my_id]['password_salt']);
}
// PHP-Fusion
@@ -593,8 +576,7 @@ protected function checkPasswordFallbacks(): bool
$other_passwords[] = md5(md5(User::$profiles[User::$my_id]['password_salt']) . md5($_POST['passwrd']));
}
// The hash should be 40 if it's SHA-1, so we're safe with more here too.
- elseif (!empty(Config::$modSettings['enable_password_conversion']) && strlen(User::$profiles[User::$my_id]['passwd']) == 32)
- {
+ elseif (!empty(Config::$modSettings['enable_password_conversion']) && strlen(User::$profiles[User::$my_id]['passwd']) == 32) {
// vBulletin 3 style hashing? Let's welcome them with open arms \o/.
$other_passwords[] = md5(md5($_POST['passwrd']) . stripslashes(User::$profiles[User::$my_id]['password_salt']));
@@ -604,16 +586,13 @@ protected function checkPasswordFallbacks(): bool
// Some common md5 ones.
$other_passwords[] = md5(User::$profiles[User::$my_id]['password_salt'] . $_POST['passwrd']);
$other_passwords[] = md5($_POST['passwrd'] . User::$profiles[User::$my_id]['password_salt']);
- }
- elseif (strlen(User::$profiles[User::$my_id]['passwd']) == 40)
- {
+ } elseif (strlen(User::$profiles[User::$my_id]['passwd']) == 40) {
// Maybe they are using a hash from before the password fix.
// This is also valid for SMF 1.1 to 2.0 style of hashing, changed to bcrypt in SMF 2.1
$other_passwords[] = sha1(strtolower(User::$profiles[User::$my_id]['member_name']) . Utils::htmlspecialcharsDecode($_POST['passwrd']));
// BurningBoard3 style of hashing.
- if (!empty(Config::$modSettings['enable_password_conversion']))
- {
+ if (!empty(Config::$modSettings['enable_password_conversion'])) {
$other_passwords[] = sha1(User::$profiles[User::$my_id]['password_salt'] . sha1(User::$profiles[User::$my_id]['password_salt'] . sha1($_POST['passwrd'])));
}
@@ -621,52 +600,45 @@ protected function checkPasswordFallbacks(): bool
$other_passwords[] = sha1(User::$profiles[User::$my_id]['password_salt'] . sha1($_POST['passwrd']));
// Perhaps we converted to UTF-8 and have a valid password being hashed differently.
- if (Utils::$context['character_set'] == 'UTF-8' && !empty(Config::$modSettings['previousCharacterSet']) && Config::$modSettings['previousCharacterSet'] != 'utf8')
- {
+ if (Utils::$context['character_set'] == 'UTF-8' && !empty(Config::$modSettings['previousCharacterSet']) && Config::$modSettings['previousCharacterSet'] != 'utf8') {
// Try iconv first, for no particular reason.
- if (function_exists('iconv'))
- {
+ if (function_exists('iconv')) {
$other_passwords['iconv'] = sha1(strtolower(iconv('UTF-8', Config::$modSettings['previousCharacterSet'], User::$profiles[User::$my_id]['member_name'])) . Utils::htmlspecialcharsDecode(iconv('UTF-8', Config::$modSettings['previousCharacterSet'], $_POST['passwrd'])));
}
// Say it aint so, iconv failed!
- if (empty($other_passwords['iconv']) && function_exists('mb_convert_encoding'))
- {
+ if (empty($other_passwords['iconv']) && function_exists('mb_convert_encoding')) {
$other_passwords[] = sha1(strtolower(mb_convert_encoding(User::$profiles[User::$my_id]['member_name'], 'UTF-8', Config::$modSettings['previousCharacterSet'])) . Utils::htmlspecialcharsDecode(mb_convert_encoding($_POST['passwrd'], 'UTF-8', Config::$modSettings['previousCharacterSet'])));
}
}
}
// Allows mods to easily extend the $other_passwords array
- IntegrationHook::call('integrate_other_passwords', array(&$other_passwords));
+ IntegrationHook::call('integrate_other_passwords', [&$other_passwords]);
// Whichever encryption it was using, let's make it use SMF's now ;).
- if (in_array(User::$profiles[User::$my_id]['passwd'], $other_passwords))
- {
+ if (in_array(User::$profiles[User::$my_id]['passwd'], $other_passwords)) {
User::$profiles[User::$my_id]['passwd'] = Security::hashPassword(User::$profiles[User::$my_id]['member_name'], Utils::htmlspecialcharsDecode($_POST['passwrd']));
User::$profiles[User::$my_id]['password_salt'] = bin2hex(Utils::randomBytes(16));
// Update the password and set up the hash.
- User::updateMemberData(User::$profiles[User::$my_id]['id_member'], array('passwd' => User::$profiles[User::$my_id]['passwd'], 'password_salt' => User::$profiles[User::$my_id]['password_salt'], 'passwd_flood' => ''));
+ User::updateMemberData(User::$profiles[User::$my_id]['id_member'], ['passwd' => User::$profiles[User::$my_id]['passwd'], 'password_salt' => User::$profiles[User::$my_id]['password_salt'], 'passwd_flood' => '']);
}
// Okay, they for sure didn't enter the password!
- else
- {
+ else {
// They've messed up again - keep a count to see if they need a hand.
$_SESSION['failed_login'] = isset($_SESSION['failed_login']) ? ($_SESSION['failed_login'] + 1) : 1;
// Hmm... don't remember it, do you? Here, try the password reminder ;).
- if ($_SESSION['failed_login'] >= Config::$modSettings['failed_login_threshold'])
- {
+ if ($_SESSION['failed_login'] >= Config::$modSettings['failed_login_threshold']) {
Utils::redirectexit('action=reminder');
}
// We'll give you another chance...
- else
- {
+ else {
// Log an error so we know that it didn't go well in the error log.
ErrorHandler::log(Lang::$txt['incorrect_password'] . ' - ' . User::$profiles[User::$my_id]['member_name'] . '', 'user');
- Utils::$context['login_errors'] = array(Lang::$txt['incorrect_password']);
+ Utils::$context['login_errors'] = [Lang::$txt['incorrect_password']];
return false;
}
@@ -686,8 +658,9 @@ protected function phpBB3_password_check()
$passwd_hash = User::$profiles[User::$my_id]['passwd'];
// Too long or too short?
- if (strlen($passwd_hash) != 34)
+ if (strlen($passwd_hash) != 34) {
return;
+ }
// Range of characters allowed.
$range = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
@@ -698,31 +671,37 @@ protected function phpBB3_password_check()
$salt = substr($passwd_hash, 4, 8);
$hash = md5($salt . $passwd, true);
- for (; $count != 0; --$count)
+
+ for (; $count != 0; --$count) {
$hash = md5($hash . $passwd, true);
+ }
$output = substr($passwd_hash, 0, 12);
$i = 0;
- while ($i < 16)
- {
+
+ while ($i < 16) {
$value = ord($hash[$i++]);
$output .= $range[$value & 0x3f];
- if ($i < 16)
+ if ($i < 16) {
$value |= ord($hash[$i]) << 8;
+ }
$output .= $range[($value >> 6) & 0x3f];
- if ($i++ >= 16)
+ if ($i++ >= 16) {
break;
+ }
- if ($i < 16)
+ if ($i < 16) {
$value |= ord($hash[$i]) << 16;
+ }
$output .= $range[($value >> 12) & 0x3f];
- if ($i++ >= 16)
+ if ($i++ >= 16) {
break;
+ }
$output .= $range[($value >> 18) & 0x3f];
}
@@ -736,35 +715,31 @@ protected function phpBB3_password_check()
*/
protected function checkActivation()
{
- if (!isset(Utils::$context['login_errors']))
- Utils::$context['login_errors'] = array();
+ if (!isset(Utils::$context['login_errors'])) {
+ Utils::$context['login_errors'] = [];
+ }
// What is the true activation status of this account?
$activation_status = User::$profiles[User::$my_id]['is_activated'] > 10 ? User::$profiles[User::$my_id]['is_activated'] - 10 : User::$profiles[User::$my_id]['is_activated'];
// Check if the account is activated - COPPA first...
- if ($activation_status == 5)
- {
+ if ($activation_status == 5) {
Utils::$context['login_errors'][] = Lang::$txt['coppa_no_consent'] . ' ' . Lang::$txt['coppa_need_more_details'] . '';
return false;
}
+
// Awaiting approval still?
- elseif ($activation_status == 3)
- {
+ if ($activation_status == 3) {
ErrorHandler::fatalLang('still_awaiting_approval', 'user');
}
// Awaiting deletion, changed their mind?
- elseif ($activation_status == 4)
- {
- if (isset($_REQUEST['undelete']))
- {
- User::updateMemberData(User::$profiles[User::$my_id]['id_member'], array('is_activated' => 1));
+ elseif ($activation_status == 4) {
+ if (isset($_REQUEST['undelete'])) {
+ User::updateMemberData(User::$profiles[User::$my_id]['id_member'], ['is_activated' => 1]);
- Config::updateModSettings(array('unapprovedMembers' => (Config::$modSettings['unapprovedMembers'] > 0 ? Config::$modSettings['unapprovedMembers'] - 1 : 0)));
- }
- else
- {
+ Config::updateModSettings(['unapprovedMembers' => (Config::$modSettings['unapprovedMembers'] > 0 ? Config::$modSettings['unapprovedMembers'] - 1 : 0)]);
+ } else {
Utils::$context['disable_login_hashing'] = true;
Utils::$context['login_errors'][] = Lang::$txt['awaiting_delete_account'];
Utils::$context['login_show_undelete'] = true;
@@ -773,8 +748,7 @@ protected function checkActivation()
}
}
// Standard activation?
- elseif ($activation_status != 1)
- {
+ elseif ($activation_status != 1) {
ErrorHandler::log(Lang::$txt['activate_not_completed1'] . ' - ' . User::$profiles[User::$my_id]['member_name'] . '', 'user');
Utils::$context['login_errors'][] = Lang::$txt['activate_not_completed1'] . ' ' . Lang::$txt['activate_not_completed2'] . '';
@@ -791,7 +765,7 @@ protected function checkActivation()
protected function DoLogin()
{
// Call login integration functions.
- IntegrationHook::call('integrate_login', array(User::$profiles[User::$my_id]['member_name'], null, Config::$modSettings['cookieTime']));
+ IntegrationHook::call('integrate_login', [User::$profiles[User::$my_id]['member_name'], null, Config::$modSettings['cookieTime']]);
// Get ready to set the cookie...
User::setMe(User::$my_id);
@@ -800,8 +774,9 @@ protected function DoLogin()
Cookie::setLoginCookie(60 * Config::$modSettings['cookieTime'], User::$me->id, Cookie::encrypt(User::$me->passwd, User::$me->password_salt));
// Reset the login threshold.
- if (isset($_SESSION['failed_login']))
+ if (isset($_SESSION['failed_login'])) {
unset($_SESSION['failed_login']);
+ }
// Are you banned?
User::$me->kickIfBanned(true);
@@ -810,65 +785,61 @@ protected function DoLogin()
unset($_SESSION['language'], $_SESSION['id_theme']);
// First login?
- if (User::$me->last_login === 0)
- {
+ if (User::$me->last_login === 0) {
$_SESSION['first_login'] = true;
- }
- else
- {
+ } else {
unset($_SESSION['first_login']);
}
// You've logged in, haven't you?
- $update = array('member_ip' => User::$me->ip, 'member_ip2' => $_SERVER['BAN_CHECK_IP']);
+ $update = ['member_ip' => User::$me->ip, 'member_ip2' => $_SERVER['BAN_CHECK_IP']];
- if (empty(User::$me->tfa_secret))
+ if (empty(User::$me->tfa_secret)) {
$update['last_login'] = time();
+ }
User::updateMemberData(User::$me->id, $update);
// Get rid of the online entry for that old guest....
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_online
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_online
WHERE session = {string:session}',
- array(
+ [
'session' => 'ip' . User::$me->ip,
- )
+ ],
);
$_SESSION['log_time'] = 0;
// Log this entry, only if we have it enabled.
- if (!empty(Config::$modSettings['loginHistoryDays']))
- {
- Db::$db->insert('insert',
+ if (!empty(Config::$modSettings['loginHistoryDays'])) {
+ Db::$db->insert(
+ 'insert',
'{db_prefix}member_logins',
- array(
+ [
'id_member' => 'int', 'time' => 'int', 'ip' => 'inet', 'ip2' => 'inet',
- ),
- array(
- User::$me->id, time(), User::$me->ip, User::$me->ip2
- ),
- array(
- 'id_member', 'time'
- )
+ ],
+ [
+ User::$me->id, time(), User::$me->ip, User::$me->ip2,
+ ],
+ [
+ 'id_member', 'time',
+ ],
);
}
// Just log you back out if it's in maintenance mode and you AREN'T an admin.
- if (empty(Config::$maintenance) || User::$me->allowedTo('admin_forum'))
- {
+ if (empty(Config::$maintenance) || User::$me->allowedTo('admin_forum')) {
Utils::redirectexit('action=login2;sa=check;member=' . User::$me->id, Utils::$context['server']['needs_login_fix']);
- }
- else
- {
+ } else {
Utils::redirectexit('action=logout;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'], Utils::$context['server']['needs_login_fix']);
}
}
-
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Login2::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Login2::exportStatic')) {
Login2::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/LoginTFA.php b/Sources/Actions/LoginTFA.php
index 06c8af3a89..6eaf99c194 100644
--- a/Sources/Actions/LoginTFA.php
+++ b/Sources/Actions/LoginTFA.php
@@ -14,16 +14,15 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\Cookie;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Security;
use SMF\Theme;
+use SMF\TOTP\Auth as Tfa;
use SMF\User;
use SMF\Utils;
-use SMF\TOTP\Auth as Tfa;
/**
* Handles Two-Factor Authentication credentials.
@@ -37,12 +36,11 @@ class LoginTFA extends Login2
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'LoginTFA',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -65,8 +63,7 @@ class LoginTFA extends Login2
*/
public function execute(): void
{
- if (!User::$me->is_guest || empty(Utils::$context['tfa_member']) || empty(Config::$modSettings['tfa_mode']))
- {
+ if (!User::$me->is_guest || empty(Utils::$context['tfa_member']) || empty(Config::$modSettings['tfa_mode'])) {
ErrorHandler::fatalLang('no_access', false);
}
@@ -75,65 +72,55 @@ public function execute(): void
$member = Utils::$context['tfa_member'];
// Prevent replay attacks by limiting at least 2 minutes before they can log in again via 2FA
- if (time() - $member['last_login'] < 120)
+ if (time() - $member['last_login'] < 120) {
ErrorHandler::fatalLang('tfa_wait', false);
+ }
$totp = new Tfa($member['tfa_secret']);
$totp->setRange(1);
parent::checkAjax();
- if (!empty($_POST['tfa_code']) && empty($_POST['tfa_backup']))
- {
+ if (!empty($_POST['tfa_code']) && empty($_POST['tfa_backup'])) {
// Check to ensure we're forcing SSL for authentication
- if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn())
- {
+ if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn()) {
ErrorHandler::fatalLang('login_ssl_required', false);
}
$code = $_POST['tfa_code'];
- if (strlen($code) == $totp->getCodeLength() && $totp->validateCode($code))
- {
- User::updateMemberData($member['id_member'], array('last_login' => time()));
+ if (strlen($code) == $totp->getCodeLength() && $totp->validateCode($code)) {
+ User::updateMemberData($member['id_member'], ['last_login' => time()]);
Cookie::setTFACookie(3153600, $member['id_member'], Cookie::encrypt($member['tfa_backup'], $member['password_salt']));
Utils::redirectexit();
- }
- else
- {
+ } else {
parent::validatePasswordFlood($member['id_member'], $member['member_name'], $member['passwd_flood'], false, true);
Utils::$context['tfa_error'] = true;
Utils::$context['tfa_value'] = $_POST['tfa_code'];
}
- }
- elseif (!empty($_POST['tfa_backup']))
- {
+ } elseif (!empty($_POST['tfa_backup'])) {
// Check to ensure we're forcing SSL for authentication
- if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn())
- {
+ if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn()) {
ErrorHandler::fatalLang('login_ssl_required', false);
}
$backup = $_POST['tfa_backup'];
- if (Security::hashVerifyPassword($member['member_name'], $backup, $member['tfa_backup']))
- {
+ if (Security::hashVerifyPassword($member['member_name'], $backup, $member['tfa_backup'])) {
// Get rid of their current TFA settings
- User::updateMemberData($member['id_member'], array(
+ User::updateMemberData($member['id_member'], [
'tfa_secret' => '',
'tfa_backup' => '',
'last_login' => time(),
- ));
+ ]);
Cookie::setTFACookie(3153600, $member['id_member'], Cookie::encrypt($member['tfa_backup'], $member['password_salt']));
Utils::redirectexit('action=profile;area=tfasetup;backup');
- }
- else
- {
+ } else {
parent::validatePasswordFlood($member['id_member'], $member['member_name'], $member['passwd_flood'], false, true);
Utils::$context['tfa_backup_error'] = true;
@@ -159,8 +146,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;
}
@@ -186,7 +174,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\LoginTFA::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\LoginTFA::exportStatic')) {
LoginTFA::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Logout.php b/Sources/Actions/Logout.php
index a504c23727..e92d9ca312 100644
--- a/Sources/Actions/Logout.php
+++ b/Sources/Actions/Logout.php
@@ -14,15 +14,14 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\Cookie;
+use SMF\Db\DatabaseApi as Db;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Logs the user out.
@@ -36,12 +35,11 @@ class Logout extends Login2
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'Logout',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -75,26 +73,22 @@ class Logout extends Login2
public function execute(bool $internal = false, bool $redirect = true): void
{
// They decided to cancel a logout?
- if (!$internal && isset($_POST['cancel']) && isset($_GET[Utils::$context['session_var']]))
- {
+ if (!$internal && isset($_POST['cancel'], $_GET[Utils::$context['session_var']])) {
Utils::redirectexit(!empty($_SESSION['logout_return']) ? $_SESSION['logout_return'] : '');
}
// Prompt to logout?
- elseif (!$internal && !isset($_GET[Utils::$context['session_var']]))
- {
+ elseif (!$internal && !isset($_GET[Utils::$context['session_var']])) {
Lang::load('Login');
Theme::loadTemplate('Login');
Utils::$context['sub_template'] = 'logout';
// This came from a valid hashed return url. Or something that knows our secrets...
- if (!empty($_REQUEST['return_hash']) && !empty($_REQUEST['return_to']) && hash_hmac('sha1', Utils::htmlspecialcharsDecode($_REQUEST['return_to']), Config::getAuthSecret()) == $_REQUEST['return_hash'])
- {
+ if (!empty($_REQUEST['return_hash']) && !empty($_REQUEST['return_to']) && hash_hmac('sha1', Utils::htmlspecialcharsDecode($_REQUEST['return_to']), Config::getAuthSecret()) == $_REQUEST['return_hash']) {
$_SESSION['logout_url'] = Utils::htmlspecialcharsDecode($_REQUEST['return_to']);
$_SESSION['logout_return'] = $_SESSION['logout_url'];
}
// Setup the return address.
- elseif (isset($_SESSION['old_url']))
- {
+ elseif (isset($_SESSION['old_url'])) {
$_SESSION['logout_return'] = $_SESSION['old_url'];
}
@@ -102,30 +96,30 @@ public function execute(bool $internal = false, bool $redirect = true): void
return;
}
// Make sure they aren't being auto-logged out.
- elseif (!$internal && isset($_GET[Utils::$context['session_var']]))
- {
+ elseif (!$internal && isset($_GET[Utils::$context['session_var']])) {
User::$me->checkSession('get');
}
- if (isset($_SESSION['pack_ftp']))
+ if (isset($_SESSION['pack_ftp'])) {
$_SESSION['pack_ftp'] = null;
+ }
// It won't be first login anymore.
unset($_SESSION['first_login']);
// Just ensure they aren't a guest!
- if (!User::$me->is_guest)
- {
+ if (!User::$me->is_guest) {
// Pass the logout information to integrations.
- IntegrationHook::call('integrate_logout', array(User::$me->username));
+ IntegrationHook::call('integrate_logout', [User::$me->username]);
// If you log out, you aren't online anymore :P.
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_online
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_online
WHERE id_member = {int:current_member}',
- array(
+ [
'current_member' => User::$me->id,
- )
+ ],
);
}
@@ -137,12 +131,12 @@ public function execute(bool $internal = false, bool $redirect = true): void
// And some other housekeeping while we're at it.
$salt = bin2hex(Utils::randomBytes(16));
- if (!empty(User::$me->id))
- User::updateMemberData(User::$me->id, array('password_salt' => $salt));
+ if (!empty(User::$me->id)) {
+ User::updateMemberData(User::$me->id, ['password_salt' => $salt]);
+ }
- if (!empty(Config::$modSettings['tfa_mode']) && !empty(User::$me->id) && !empty($_COOKIE[Config::$cookiename . '_tfa']))
- {
- list(,, $exp) = Utils::jsonDecode($_COOKIE[Config::$cookiename . '_tfa'], true);
+ if (!empty(Config::$modSettings['tfa_mode']) && !empty(User::$me->id) && !empty($_COOKIE[Config::$cookiename . '_tfa'])) {
+ list(, , $exp) = Utils::jsonDecode($_COOKIE[Config::$cookiename . '_tfa'], true);
Cookie::setTFACookie((int) $exp - time(), $salt, Cookie::encrypt(User::$me->tfa_backup, $salt));
}
@@ -150,19 +144,13 @@ public function execute(bool $internal = false, bool $redirect = true): void
session_destroy();
// Off to the merry board index we go!
- if ($redirect)
- {
- if (empty($_SESSION['logout_url']))
- {
+ if ($redirect) {
+ if (empty($_SESSION['logout_url'])) {
Utils::redirectexit('', Utils::$context['server']['needs_login_fix']);
- }
- elseif (!empty($_SESSION['logout_url']) && (strpos($_SESSION['logout_url'], 'http://') === false && strpos($_SESSION['logout_url'], 'https://') === false))
- {
+ } elseif (!empty($_SESSION['logout_url']) && (strpos($_SESSION['logout_url'], 'http://') === false && strpos($_SESSION['logout_url'], 'https://') === false)) {
unset($_SESSION['logout_url']);
Utils::redirectexit();
- }
- else
- {
+ } else {
$temp = $_SESSION['logout_url'];
unset($_SESSION['logout_url']);
@@ -182,8 +170,9 @@ public function execute(bool $internal = false, bool $redirect = true): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -212,7 +201,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Logout::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Logout::exportStatic')) {
Logout::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Memberlist.php b/Sources/Actions/Memberlist.php
index 80fccd03dc..4df6e61490 100644
--- a/Sources/Actions/Memberlist.php
+++ b/Sources/Actions/Memberlist.php
@@ -14,9 +14,9 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\BBCodeParser;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -25,7 +25,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This class contains the methods for displaying and searching in the
@@ -40,14 +39,15 @@ class Memberlist implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'Memberlist',
+ 'MLAll' => 'MLAll',
+ 'MLSearch' => 'MLSearch',
'printRows' => 'printMemberListRows',
'getCustFields' => 'getCustFieldsMList',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -68,18 +68,18 @@ class Memberlist implements ActionInterface
* Labels will be replaced with the indicated $txt strings.
* Selected will be changed to match the current sub-action.
*/
- public array $sort_links = array(
- 'all' => array(
+ public array $sort_links = [
+ 'all' => [
'label' => 'view_all_members',
'action' => 'all',
'selected' => true,
- ),
- 'search' => array(
+ ],
+ 'search' => [
'label' => 'mlist_search',
'action' => 'search',
'selected' => false,
- ),
- );
+ ],
+ ];
/**
* @var int
@@ -97,10 +97,10 @@ class Memberlist implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'all' => 'all',
'search' => 'search',
- );
+ ];
/****************************
* Internal static properties
@@ -135,8 +135,7 @@ public function execute(): void
Theme::loadTemplate('Memberlist');
- foreach ($this->sort_links as $sa => &$sort_link)
- {
+ foreach ($this->sort_links as $sa => &$sort_link) {
$sort_link['label'] = Lang::$txt[$sort_link['label']] ?? ($sort_link['label'] ?? ($sort_link['action'] ?? $sa));
$sort_link['selected'] = $this->subaction === ($sort_link['action'] ?? $sa);
@@ -148,96 +147,98 @@ public function execute(): void
Utils::$context['num_members'] = Config::$modSettings['totalMembers'];
// Set up the columns...
- Utils::$context['columns'] = array(
- 'is_online' => array(
+ Utils::$context['columns'] = [
+ 'is_online' => [
'label' => Lang::$txt['status'],
- 'sort' => array(
+ 'sort' => [
'down' => User::$me->allowedTo('moderate_forum') ? 'COALESCE(lo.log_time, 1) ASC, real_name ASC' : 'CASE WHEN mem.show_online THEN COALESCE(lo.log_time, 1) ELSE 1 END ASC, real_name ASC',
- 'up' => User::$me->allowedTo('moderate_forum') ? 'COALESCE(lo.log_time, 1) DESC, real_name DESC' : 'CASE WHEN mem.show_online THEN COALESCE(lo.log_time, 1) ELSE 1 END DESC, real_name DESC'
- ),
- ),
- 'real_name' => array(
+ 'up' => User::$me->allowedTo('moderate_forum') ? 'COALESCE(lo.log_time, 1) DESC, real_name DESC' : 'CASE WHEN mem.show_online THEN COALESCE(lo.log_time, 1) ELSE 1 END DESC, real_name DESC',
+ ],
+ ],
+ 'real_name' => [
'label' => Lang::$txt['name'],
'class' => 'lefttext',
- 'sort' => array(
+ 'sort' => [
'down' => 'mem.real_name DESC',
- 'up' => 'mem.real_name ASC'
- ),
- ),
- 'website_url' => array(
+ 'up' => 'mem.real_name ASC',
+ ],
+ ],
+ 'website_url' => [
'label' => Lang::$txt['website'],
'link_with' => 'website',
- 'sort' => array(
+ 'sort' => [
'down' => User::$me->is_guest ? '1=1' : 'mem.website_url = \'\', mem.website_url is null, mem.website_url DESC',
- 'up' => User::$me->is_guest ? ' 1=1' : 'mem.website_url != \'\', mem.website_url is not null, mem.website_url ASC'
- ),
- ),
- 'id_group' => array(
+ 'up' => User::$me->is_guest ? ' 1=1' : 'mem.website_url != \'\', mem.website_url is not null, mem.website_url ASC',
+ ],
+ ],
+ 'id_group' => [
'label' => Lang::$txt['position'],
- 'sort' => array(
+ 'sort' => [
'down' => 'mg.group_name is null, mg.group_name DESC',
- 'up' => 'mg.group_name is not null, mg.group_name ASC'
- ),
- ),
- 'registered' => array(
+ 'up' => 'mg.group_name is not null, mg.group_name ASC',
+ ],
+ ],
+ 'registered' => [
'label' => Lang::$txt['date_registered'],
- 'sort' => array(
+ 'sort' => [
'down' => 'mem.date_registered DESC',
- 'up' => 'mem.date_registered ASC'
- ),
- ),
- 'post_count' => array(
+ 'up' => 'mem.date_registered ASC',
+ ],
+ ],
+ 'post_count' => [
'label' => Lang::$txt['posts'],
'default_sort_rev' => true,
- 'sort' => array(
+ 'sort' => [
'down' => 'mem.posts DESC',
- 'up' => 'mem.posts ASC'
- ),
- )
- );
+ 'up' => 'mem.posts ASC',
+ ],
+ ],
+ ];
Utils::$context['custom_profile_fields'] = $this->getCustFields();
- if (!empty(Utils::$context['custom_profile_fields']['columns']))
+ if (!empty(Utils::$context['custom_profile_fields']['columns'])) {
Utils::$context['columns'] += Utils::$context['custom_profile_fields']['columns'];
+ }
Utils::$context['colspan'] = 0;
- Utils::$context['disabled_fields'] = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : array();
- foreach (Utils::$context['columns'] as $key => $column)
- {
- if (isset(Utils::$context['disabled_fields'][$key]) || (isset($column['link_with']) && isset(Utils::$context['disabled_fields'][$column['link_with']])))
- {
+ Utils::$context['disabled_fields'] = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : [];
+
+ foreach (Utils::$context['columns'] as $key => $column) {
+ if (isset(Utils::$context['disabled_fields'][$key]) || (isset($column['link_with'], Utils::$context['disabled_fields'][$column['link_with']]))) {
unset(Utils::$context['columns'][$key]);
+
continue;
}
- Utils::$context['colspan'] += isset($column['colspan']) ? $column['colspan'] : 1;
+ Utils::$context['colspan'] += $column['colspan'] ?? 1;
}
// Aesthetic stuff.
end(Utils::$context['columns']);
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=mlist',
- 'name' => Lang::$txt['members_list']
- );
+ 'name' => Lang::$txt['members_list'],
+ ];
Utils::$context['can_send_pm'] = User::$me->allowedTo('pm_send');
Utils::$context['can_send_email'] = User::$me->allowedTo('moderate_forum');
// Build the memberlist button array.
- Utils::$context['memberlist_buttons'] = array(
- 'view_all_members' => array('text' => 'view_all_members', 'image' => 'mlist.png', 'url' => Config::$scripturl . '?action=mlist' . ';sa=all', 'active' => true),
- 'mlist_search' => array('text' => 'mlist_search', 'image' => 'mlist.png', 'url' => Config::$scripturl . '?action=mlist' . ';sa=search'),
- );
+ Utils::$context['memberlist_buttons'] = [
+ 'view_all_members' => ['text' => 'view_all_members', 'image' => 'mlist.png', 'url' => Config::$scripturl . '?action=mlist' . ';sa=all', 'active' => true],
+ 'mlist_search' => ['text' => 'mlist_search', 'image' => 'mlist.png', 'url' => Config::$scripturl . '?action=mlist' . ';sa=search'],
+ ];
// Allow mods to add additional buttons here
IntegrationHook::call('integrate_memberlist_buttons');
- $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);
+ }
}
/**
@@ -254,107 +255,107 @@ public function all()
// 3. the page shown is high enough to make a DB filesort unprofitable.
$use_cache = Config::$modSettings['totalMembers'] > 2000 && (!isset($_REQUEST['sort']) || $_REQUEST['sort'] === 'real_name') && isset($_REQUEST['start']) && $_REQUEST['start'] > $this->cache_step_size;
- if ($use_cache)
- {
+ if ($use_cache) {
// Maybe there's something cached already.
- if (!empty(Config::$modSettings['memberlist_cache']))
+ if (!empty(Config::$modSettings['memberlist_cache'])) {
$memberlist_cache = Utils::jsonDecode(Config::$modSettings['memberlist_cache'], true);
+ }
// Only update the cache if something changed or no cache existed yet.
- if (empty($memberlist_cache) || empty(Config::$modSettings['memberlist_updated']) || $memberlist_cache['last_update'] < Config::$modSettings['memberlist_updated'])
- {
- $request = Db::$db->query('', '
- SELECT real_name
+ if (empty($memberlist_cache) || empty(Config::$modSettings['memberlist_updated']) || $memberlist_cache['last_update'] < Config::$modSettings['memberlist_updated']) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT real_name
FROM {db_prefix}members
WHERE is_activated = {int:is_activated}
ORDER BY real_name',
- array(
+ [
'is_activated' => 1,
- )
+ ],
);
- $memberlist_cache = array(
+ $memberlist_cache = [
'last_update' => time(),
'num_members' => Db::$db->num_rows($request),
- 'index' => array(),
- );
+ 'index' => [],
+ ];
- for ($i = 0, $n = Db::$db->num_rows($request); $i < $n; $i += $this->cache_step_size)
- {
+ for ($i = 0, $n = Db::$db->num_rows($request); $i < $n; $i += $this->cache_step_size) {
Db::$db->data_seek($request, $i);
list($memberlist_cache['index'][$i]) = Db::$db->fetch_row($request);
}
Db::$db->data_seek($request, $memberlist_cache['num_members'] - 1);
- list ($memberlist_cache['index'][$memberlist_cache['num_members'] - 1]) = Db::$db->fetch_row($request);
+ list($memberlist_cache['index'][$memberlist_cache['num_members'] - 1]) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Now we've got the cache...store it.
- Config::updateModSettings(array('memberlist_cache' => Utils::jsonEncode($memberlist_cache)));
+ Config::updateModSettings(['memberlist_cache' => Utils::jsonEncode($memberlist_cache)]);
}
Utils::$context['num_members'] = $memberlist_cache['num_members'];
}
// Without cache we need an extra query to get the amount of members.
- else
- {
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}members
WHERE is_activated = {int:is_activated}',
- array(
+ [
'is_activated' => 1,
- )
+ ],
);
- list (Utils::$context['num_members']) = Db::$db->fetch_row($request);
+ list(Utils::$context['num_members']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
}
// Set defaults for sort (real_name) and start. (0)
- if (!isset($_REQUEST['sort']) || !isset(Utils::$context['columns'][$_REQUEST['sort']]))
+ if (!isset($_REQUEST['sort']) || !isset(Utils::$context['columns'][$_REQUEST['sort']])) {
$_REQUEST['sort'] = 'real_name';
+ }
- if (!is_numeric($_REQUEST['start']))
- {
- if (preg_match('~^[^\'\\\\/]~' . (Utils::$context['utf8'] ? 'u' : ''), Utils::strtolower($_REQUEST['start']), $match) === 0)
+ if (!is_numeric($_REQUEST['start'])) {
+ if (preg_match('~^[^\'\\\\/]~' . (Utils::$context['utf8'] ? 'u' : ''), Utils::strtolower($_REQUEST['start']), $match) === 0) {
ErrorHandler::fatal('Are you a wannabe hacker?', false);
+ }
$_REQUEST['start'] = $match[0];
- $request = Db::$db->query('substring', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ 'substring',
+ 'SELECT COUNT(*)
FROM {db_prefix}members
WHERE LOWER(SUBSTRING(real_name, 1, 1)) < {string:first_letter}
AND is_activated = {int:is_activated}',
- array(
+ [
'is_activated' => 1,
'first_letter' => $_REQUEST['start'],
- )
+ ],
);
- list ($_REQUEST['start']) = Db::$db->fetch_row($request);
+ list($_REQUEST['start']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
}
Utils::$context['letter_links'] = '';
- for ($i = 97; $i < 123; $i++)
- {
+
+ for ($i = 97; $i < 123; $i++) {
Utils::$context['letter_links'] .= '' . strtoupper(chr($i)) . ' ';
}
// Sort out the column information.
- foreach (Utils::$context['columns'] as $col => $column_details)
- {
+ foreach (Utils::$context['columns'] as $col => $column_details) {
Utils::$context['columns'][$col]['href'] = Config::$scripturl . '?action=mlist;sort=' . $col . ';start=' . $_REQUEST['start'];
- if ((!isset($_REQUEST['desc']) && $col == $_REQUEST['sort']) || ($col != $_REQUEST['sort'] && !empty($column_details['default_sort_rev'])))
+ if ((!isset($_REQUEST['desc']) && $col == $_REQUEST['sort']) || ($col != $_REQUEST['sort'] && !empty($column_details['default_sort_rev']))) {
Utils::$context['columns'][$col]['href'] .= ';desc';
+ }
Utils::$context['columns'][$col]['link'] = '' . Utils::$context['columns'][$col]['label'] . '';
Utils::$context['columns'][$col]['selected'] = $_REQUEST['sort'] == $col;
}
// Don't offer website sort to guests
- if (User::$me->is_guest)
- {
+ if (User::$me->is_guest) {
Utils::$context['columns']['website_url']['href'] = '';
Utils::$context['columns']['website_url']['link'] = Utils::$context['columns']['website_url']['label'];
}
@@ -372,23 +373,22 @@ public function all()
Utils::$context['can_moderate_forum'] = User::$me->allowedTo('moderate_forum');
Utils::$context['page_title'] = sprintf(Lang::$txt['viewing_members'], Utils::$context['start'], Utils::$context['end']);
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=mlist;sort=' . $_REQUEST['sort'] . ';start=' . $_REQUEST['start'],
'name' => &Utils::$context['page_title'],
- 'extra_after' => '(' . sprintf(Lang::$txt['of_total_members'], Utils::$context['num_members']) . ')'
- );
+ 'extra_after' => '(' . sprintf(Lang::$txt['of_total_members'], Utils::$context['num_members']) . ')',
+ ];
$limit = $_REQUEST['start'];
- $query_parameters = array(
+ $query_parameters = [
'regular_id_group' => 0,
'is_activated' => 1,
'sort' => Utils::$context['columns'][$_REQUEST['sort']]['sort'][Utils::$context['sort_direction']],
'blank_string' => '',
- );
+ ];
// Using cache allows to narrow down the list to be retrieved.
- if ($use_cache && $_REQUEST['sort'] === 'real_name' && !isset($_REQUEST['desc']))
- {
+ if ($use_cache && $_REQUEST['sort'] === 'real_name' && !isset($_REQUEST['desc'])) {
$first_offset = max(0, $_REQUEST['start'] - ($_REQUEST['start'] % $this->cache_step_size));
$second_offset = min($memberlist_cache['num_members'] - 1, ceil(($_REQUEST['start'] + Config::$modSettings['defaultMaxMembers']) / $this->cache_step_size) * $this->cache_step_size);
@@ -400,8 +400,7 @@ public function all()
}
// Reverse sorting is a bit more complicated...
- elseif ($use_cache && $_REQUEST['sort'] === 'real_name')
- {
+ elseif ($use_cache && $_REQUEST['sort'] === 'real_name') {
$first_offset = max(0, floor(($memberlist_cache['num_members'] - Config::$modSettings['defaultMaxMembers'] - $_REQUEST['start']) / $this->cache_step_size) * $this->cache_step_size);
$second_offset = min($memberlist_cache['num_members'] - 1, ceil(($memberlist_cache['num_members'] - $_REQUEST['start']) / $this->cache_step_size) * $this->cache_step_size);
@@ -413,12 +412,15 @@ public function all()
}
$custom_fields_qry = '';
- if (!empty(Utils::$context['custom_profile_fields']['join'][$_REQUEST['sort']]))
+
+ if (!empty(Utils::$context['custom_profile_fields']['join'][$_REQUEST['sort']])) {
$custom_fields_qry = Utils::$context['custom_profile_fields']['join'][$_REQUEST['sort']];
+ }
// Select the members from the database.
- $request = Db::$db->query('', '
- SELECT mem.id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT mem.id_member
FROM {db_prefix}members AS mem' . ($_REQUEST['sort'] === 'is_online' ? '
LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)' : '') . ($_REQUEST['sort'] === 'id_group' ? '
LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:regular_id_group} THEN mem.id_post_group ELSE mem.id_group END)' : '') . '
@@ -427,25 +429,23 @@ public function all()
AND ' . $where) . '
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array_merge($query_parameters, array(
+ array_merge($query_parameters, [
'sort' => $query_parameters['sort'],
'start' => $limit,
'max' => Config::$modSettings['defaultMaxMembers'],
- ))
+ ]),
);
$this->printRows($request);
Db::$db->free_result($request);
// Add anchors at the start of each letter.
- if ($_REQUEST['sort'] == 'real_name')
- {
+ if ($_REQUEST['sort'] == 'real_name') {
$last_letter = '';
- foreach (Utils::$context['members'] as $i => $dummy)
- {
+
+ foreach (Utils::$context['members'] as $i => $dummy) {
$this_letter = Utils::strtolower(Utils::entitySubstr(Utils::$context['members'][$i]['name'], 0, 1));
- if ($this_letter != $last_letter && preg_match('~[a-z]~', $this_letter) === 1)
- {
+ if ($this_letter != $last_letter && preg_match('~[a-z]~', $this_letter) === 1) {
Utils::$context['members'][$i]['sort_letter'] = Utils::htmlspecialchars($this_letter);
$last_letter = $this_letter;
}
@@ -465,34 +465,36 @@ public function search()
Utils::$context['can_moderate_forum'] = User::$me->allowedTo('moderate_forum');
// Can they search custom fields?
- $request = Db::$db->query('', '
- SELECT col_name, field_name, field_desc
+ $request = Db::$db->query(
+ '',
+ 'SELECT col_name, field_name, field_desc
FROM {db_prefix}custom_fields
WHERE active = {int:active}
' . (User::$me->allowedTo('admin_forum') ? '' : ' AND private < {int:private_level}') . '
AND can_search = {int:can_search}
AND (field_type = {string:field_type_text} OR field_type = {string:field_type_textarea} OR field_type = {string:field_type_select})',
- array(
+ [
'active' => 1,
'can_search' => 1,
'private_level' => 2,
'field_type_text' => 'text',
'field_type_textarea' => 'textarea',
'field_type_select' => 'select',
- )
+ ],
);
- Utils::$context['custom_search_fields'] = array();
- while ($row = Db::$db->fetch_assoc($request))
- Utils::$context['custom_search_fields'][$row['col_name']] = array(
+ Utils::$context['custom_search_fields'] = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ Utils::$context['custom_search_fields'][$row['col_name']] = [
'colname' => $row['col_name'],
'name' => $row['field_name'],
'desc' => $row['field_desc'],
- );
+ ];
+ }
Db::$db->free_result($request);
// They're searching..
- if (isset($_REQUEST['search']) && isset($_REQUEST['fields']))
- {
+ if (isset($_REQUEST['search'], $_REQUEST['fields'])) {
$_POST['search'] = trim(isset($_GET['search']) ? html_entity_decode(htmlspecialchars_decode($_GET['search'], ENT_QUOTES), ENT_QUOTES) : $_POST['search']);
$_POST['fields'] = isset($_GET['fields']) ? explode(',', $_GET['fields']) : $_POST['fields'];
@@ -502,25 +504,28 @@ public function search()
Utils::$context['old_search_value'] = urlencode($_POST['search']);
// No fields? Use default...
- if (empty($_POST['fields']))
- $_POST['fields'] = array('name');
+ if (empty($_POST['fields'])) {
+ $_POST['fields'] = ['name'];
+ }
- $_POST['fields'] = array_intersect($_POST['fields'], array_merge(array('name', 'website', 'group', 'email'), array_keys($context['custom_search_fields'])));
+ $_POST['fields'] = array_intersect($_POST['fields'], array_merge(['name', 'website', 'group', 'email'], array_keys(Utils::$context['custom_search_fields'])));
// Set defaults for how the results are sorted
- if (!isset($_REQUEST['sort']) || !isset(Utils::$context['columns'][$_REQUEST['sort']]))
+ if (!isset($_REQUEST['sort']) || !isset(Utils::$context['columns'][$_REQUEST['sort']])) {
$_REQUEST['sort'] = 'real_name';
+ }
// Build the column link / sort information.
- foreach (Utils::$context['columns'] as $col => $column_details)
- {
+ foreach (Utils::$context['columns'] as $col => $column_details) {
Utils::$context['columns'][$col]['href'] = Config::$scripturl . '?action=mlist;sa=search;start=' . (int) $_REQUEST['start'] . ';sort=' . $col;
- if ((!isset($_REQUEST['desc']) && $col == $_REQUEST['sort']) || ($col != $_REQUEST['sort'] && !empty($column_details['default_sort_rev'])))
+ if ((!isset($_REQUEST['desc']) && $col == $_REQUEST['sort']) || ($col != $_REQUEST['sort'] && !empty($column_details['default_sort_rev']))) {
Utils::$context['columns'][$col]['href'] .= ';desc';
+ }
- if (isset($_POST['search']) && isset($_POST['fields']))
+ if (isset($_POST['search'], $_POST['fields'])) {
Utils::$context['columns'][$col]['href'] .= ';search=' . urlencode($_POST['search']) . ';fields=' . implode(',', $_POST['fields']);
+ }
Utils::$context['columns'][$col]['link'] = '' . Utils::$context['columns'][$col]['label'] . '';
Utils::$context['columns'][$col]['selected'] = $_REQUEST['sort'] == $col;
@@ -530,92 +535,93 @@ public function search()
Utils::$context['sort_direction'] = !isset($_REQUEST['desc']) ? 'up' : 'down';
Utils::$context['sort_by'] = $_REQUEST['sort'];
- $query_parameters = array(
+ $query_parameters = [
'regular_id_group' => 0,
'is_activated' => 1,
'blank_string' => '',
- 'search' => '%' . strtr($_POST['search'], array('_' => '\\_', '%' => '\\%', '*' => '%')) . '%',
+ 'search' => '%' . strtr($_POST['search'], ['_' => '\\_', '%' => '\\%', '*' => '%']) . '%',
'sort' => Utils::$context['columns'][$_REQUEST['sort']]['sort'][Utils::$context['sort_direction']],
- );
+ ];
// Search for a name
- if (in_array('name', $_POST['fields']))
- {
- $fields = User::$me->allowedTo('moderate_forum') ? array('member_name', 'real_name') : array('real_name');
+ if (in_array('name', $_POST['fields'])) {
+ $fields = User::$me->allowedTo('moderate_forum') ? ['member_name', 'real_name'] : ['real_name'];
$search_fields[] = 'name';
- }
- else
- {
- $fields = array();
- $search_fields = array();
+ } else {
+ $fields = [];
+ $search_fields = [];
}
// Search for websites.
- if (in_array('website', $_POST['fields']))
- {
- $fields += array(7 => 'website_title', 'website_url');
+ if (in_array('website', $_POST['fields'])) {
+ $fields += [7 => 'website_title', 'website_url'];
$search_fields[] = 'website';
}
+
// Search for groups.
- if (in_array('group', $_POST['fields']))
- {
- $fields += array(9 => 'COALESCE(group_name, {string:blank_string})');
+ if (in_array('group', $_POST['fields'])) {
+ $fields += [9 => 'COALESCE(group_name, {string:blank_string})'];
$search_fields[] = 'group';
}
+
// Search for an email address?
- if (in_array('email', $_POST['fields']) && User::$me->allowedTo('moderate_forum'))
- {
- $fields += array(2 => 'email_address');
+ if (in_array('email', $_POST['fields']) && User::$me->allowedTo('moderate_forum')) {
+ $fields += [2 => 'email_address'];
$search_fields[] = 'email';
}
- if (Db::$db->case_sensitive)
- foreach ($fields as $key => $field)
+ if (Db::$db->case_sensitive) {
+ foreach ($fields as $key => $field) {
$fields[$key] = 'LOWER(' . $field . ')';
+ }
+ }
- $customJoin = array();
+ $customJoin = [];
$customCount = 10;
// Any custom fields to search for - these being tricky?
- foreach ($_POST['fields'] as $field)
- {
- if (substr($field, 0, 5) == 'cust_' && isset(Utils::$context['custom_search_fields'][$field]))
- {
+ foreach ($_POST['fields'] as $field) {
+ if (substr($field, 0, 5) == 'cust_' && isset(Utils::$context['custom_search_fields'][$field])) {
$customJoin[] = 'LEFT JOIN {db_prefix}themes AS t' . $field . ' ON (t' . $field . '.variable = {string:t' . $field . '} AND t' . $field . '.id_theme = 1 AND t' . $field . '.id_member = mem.id_member)';
$query_parameters['t' . $field] = $field;
- $fields += array($customCount++ => 'COALESCE(t' . $field . '.value, {string:blank_string})');
+ $fields += [$customCount++ => 'COALESCE(t' . $field . '.value, {string:blank_string})'];
$search_fields[] = $field;
}
}
// No search fields? That means you're trying to hack things
- if (empty($search_fields))
+ if (empty($search_fields)) {
ErrorHandler::fatalLang('invalid_search_string', false);
+ }
$query = $_POST['search'] == '' ? '= {string:blank_string}' : (Db::$db->case_sensitive ? 'LIKE LOWER({string:search})' : 'LIKE {string:search}');
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}members AS mem
LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:regular_id_group} THEN mem.id_post_group ELSE mem.id_group END)
' . (empty($customJoin) ? '' : implode('
', $customJoin)) . '
WHERE (' . implode(' ' . $query . ' OR ', $fields) . ' ' . $query . ')
AND mem.is_activated = {int:is_activated}',
- $query_parameters
+ $query_parameters,
);
- list ($numResults) = Db::$db->fetch_row($request);
+ list($numResults) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
Utils::$context['page_index'] = new PageIndex(Config::$scripturl . '?action=mlist;sa=search;search=' . urlencode($_POST['search']) . ';fields=' . implode(',', $_POST['fields']), $_REQUEST['start'], $numResults, Config::$modSettings['defaultMaxMembers']);
$custom_fields_qry = '';
- if (array_search($_REQUEST['sort'], $_POST['fields']) === false && !empty(Utils::$context['custom_profile_fields']['join'][$_REQUEST['sort']]))
+
+ if (array_search($_REQUEST['sort'], $_POST['fields']) === false && !empty(Utils::$context['custom_profile_fields']['join'][$_REQUEST['sort']])) {
$custom_fields_qry = Utils::$context['custom_profile_fields']['join'][$_REQUEST['sort']];
+ }
// Find the members from the database.
- $request = Db::$db->query('', '
- SELECT mem.id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT mem.id_member
FROM {db_prefix}members AS mem
LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)
LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:regular_id_group} THEN mem.id_post_group ELSE mem.id_group END)' .
@@ -626,49 +632,45 @@ public function search()
AND mem.is_activated = {int:is_activated}
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array_merge($query_parameters, array(
+ array_merge($query_parameters, [
'start' => $_REQUEST['start'],
'max' => Config::$modSettings['defaultMaxMembers'],
- ))
+ ]),
);
$this->printRows($request);
Db::$db->free_result($request);
- }
- else
- {
+ } else {
// These are all the possible fields.
- Utils::$context['search_fields'] = array(
+ Utils::$context['search_fields'] = [
'name' => Lang::$txt['mlist_search_name'],
'email' => Lang::$txt['mlist_search_email'],
'website' => Lang::$txt['mlist_search_website'],
'group' => Lang::$txt['mlist_search_group'],
- );
+ ];
// Sorry, but you can't search by email unless you can view emails
- if (!User::$me->allowedTo('moderate_forum'))
- {
+ if (!User::$me->allowedTo('moderate_forum')) {
unset(Utils::$context['search_fields']['email']);
- Utils::$context['search_defaults'] = array('name');
- }
- else
- {
- Utils::$context['search_defaults'] = array('name', 'email');
+ Utils::$context['search_defaults'] = ['name'];
+ } else {
+ Utils::$context['search_defaults'] = ['name', 'email'];
}
- foreach (Utils::$context['custom_search_fields'] as $field)
+ foreach (Utils::$context['custom_search_fields'] as $field) {
Utils::$context['search_fields'][$field['colname']] = sprintf(Lang::$txt['mlist_search_by'], Lang::tokenTxtReplace($field['name']));
+ }
Utils::$context['sub_template'] = 'search';
- Utils::$context['old_search'] = isset($_GET['search']) ? $_GET['search'] : (isset($_POST['search']) ? Utils::htmlspecialchars($_POST['search']) : '');
+ Utils::$context['old_search'] = $_GET['search'] ?? (isset($_POST['search']) ? Utils::htmlspecialchars($_POST['search']) : '');
// Since we're nice we also want to default focus on to the search field.
Theme::addInlineJavaScript("\n\t" . '$(\'input[name="search"]\').focus();', true);
}
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=mlist;sa=search',
- 'name' => &Utils::$context['page_title']
- );
+ 'name' => &Utils::$context['page_title'],
+ ];
// Highlight the correct button, too!
unset(Utils::$context['memberlist_buttons']['view_all_members']['active']);
@@ -686,8 +688,9 @@ public function search()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -729,74 +732,79 @@ public static function MLSearch(): void
public static function printRows($request)
{
// Get the most posts.
- $result = Db::$db->query('', '
- SELECT MAX(posts)
+ $result = Db::$db->query(
+ '',
+ 'SELECT MAX(posts)
FROM {db_prefix}members',
- array(
- )
+ [
+ ],
);
- list ($most_posts) = Db::$db->fetch_row($result);
+ list($most_posts) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
// Avoid division by zero...
- if ($most_posts == 0)
+ if ($most_posts == 0) {
$most_posts = 1;
+ }
- $members = array();
- while ($row = Db::$db->fetch_assoc($request))
+ $members = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$members[] = $row['id_member'];
+ }
// Load all the members for display.
User::load($members);
- Utils::$context['members'] = array();
- foreach ($members as $member)
- {
- if (!isset(User::$loaded[$member]))
+ Utils::$context['members'] = [];
+
+ foreach ($members as $member) {
+ if (!isset(User::$loaded[$member])) {
continue;
+ }
Utils::$context['members'][$member] = User::$loaded[$member]->format();
Utils::$context['members'][$member]['post_percent'] = round((Utils::$context['members'][$member]['real_posts'] * 100) / $most_posts);
Utils::$context['members'][$member]['registered_date'] = Time::strftime('%Y-%m-%d', Utils::$context['members'][$member]['registered_timestamp']);
- if (!empty(Utils::$context['custom_profile_fields']['columns']))
- {
- foreach (Utils::$context['custom_profile_fields']['columns'] as $key => $column)
- {
+ if (!empty(Utils::$context['custom_profile_fields']['columns'])) {
+ foreach (Utils::$context['custom_profile_fields']['columns'] as $key => $column) {
// Don't show anything if there isn't anything to show.
- if (!isset(Utils::$context['members'][$member]['options'][$key]))
- {
- Utils::$context['members'][$member]['options'][$key] = isset($column['default_value']) ? $column['default_value'] : '';
+ if (!isset(Utils::$context['members'][$member]['options'][$key])) {
+ Utils::$context['members'][$member]['options'][$key] = $column['default_value'] ?? '';
+
continue;
}
Utils::$context['members'][$member]['options'][$key] = Lang::tokenTxtReplace(Utils::$context['members'][$member]['options'][$key]);
$currentKey = 0;
- if (!empty($column['options']))
- {
+
+ if (!empty($column['options'])) {
$fieldOptions = explode(',', $column['options']);
- foreach ($fieldOptions as $k => $v)
- {
- if (empty($currentKey))
+
+ foreach ($fieldOptions as $k => $v) {
+ if (empty($currentKey)) {
$currentKey = $v === Utils::$context['members'][$member]['options'][$key] ? $k : 0;
+ }
}
}
- if ($column['bbc'] && !empty(Utils::$context['members'][$member]['options'][$key]))
+ if ($column['bbc'] && !empty(Utils::$context['members'][$member]['options'][$key])) {
Utils::$context['members'][$member]['options'][$key] = strip_tags(BBCodeParser::load()->parse(Utils::$context['members'][$member]['options'][$key]));
-
- elseif ($column['type'] == 'check')
+ } elseif ($column['type'] == 'check') {
Utils::$context['members'][$member]['options'][$key] = Utils::$context['members'][$member]['options'][$key] == 0 ? Lang::$txt['no'] : Lang::$txt['yes'];
+ }
// Enclosing the user input within some other text?
- if (!empty($column['enclose']))
- Utils::$context['members'][$member]['options'][$key] = strtr($column['enclose'], array(
+ if (!empty($column['enclose'])) {
+ Utils::$context['members'][$member]['options'][$key] = strtr($column['enclose'], [
'{SCRIPTURL}' => Config::$scripturl,
'{IMAGES_URL}' => Theme::$current->settings['images_url'],
'{DEFAULT_IMAGES_URL}' => Theme::$current->settings['default_images_url'],
'{INPUT}' => Lang::tokenTxtReplace(Utils::$context['members'][$member]['options'][$key]),
- '{KEY}' => $currentKey
- ));
+ '{KEY}' => $currentKey,
+ ]);
+ }
}
}
}
@@ -809,45 +817,45 @@ public static function printRows($request)
*/
public static function getCustFields()
{
- $cpf = array();
+ $cpf = [];
- $request = Db::$db->query('', '
- SELECT col_name, field_name, field_desc, field_type, field_options, bbc, enclose, default_value
+ $request = Db::$db->query(
+ '',
+ 'SELECT col_name, field_name, field_desc, field_type, field_options, bbc, enclose, default_value
FROM {db_prefix}custom_fields
WHERE active = {int:active}
AND show_mlist = {int:show}
AND private < {int:private_level}',
- array(
+ [
'active' => 1,
'show' => 1,
'private_level' => 2,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+ while ($row = Db::$db->fetch_assoc($request)) {
// Get all the data we're gonna need.
- $cpf['columns'][$row['col_name']] = array(
+ $cpf['columns'][$row['col_name']] = [
'label' => Lang::tokenTxtReplace($row['field_name']),
'type' => $row['field_type'],
'options' => Lang::tokenTxtReplace($row['field_options']),
'bbc' => !empty($row['bbc']),
'enclose' => $row['enclose'],
'default_value' => Lang::tokenTxtReplace($row['default_value']),
- );
+ ];
// Get the right sort method depending on the cust field type.
- if ($row['field_type'] != 'check')
- $cpf['columns'][$row['col_name']]['sort'] = array(
+ if ($row['field_type'] != 'check') {
+ $cpf['columns'][$row['col_name']]['sort'] = [
'down' => 'LENGTH(t' . $row['col_name'] . '.value) > 0 ASC, COALESCE(t' . $row['col_name'] . '.value, \'\') DESC',
- 'up' => 'LENGTH(t' . $row['col_name'] . '.value) > 0 DESC, COALESCE(t' . $row['col_name'] . '.value, \'\') ASC'
- );
-
- else
- $cpf['columns'][$row['col_name']]['sort'] = array(
+ 'up' => 'LENGTH(t' . $row['col_name'] . '.value) > 0 DESC, COALESCE(t' . $row['col_name'] . '.value, \'\') ASC',
+ ];
+ } else {
+ $cpf['columns'][$row['col_name']]['sort'] = [
'down' => 't' . $row['col_name'] . '.value DESC',
- 'up' => 't' . $row['col_name'] . '.value ASC'
- );
+ 'up' => 't' . $row['col_name'] . '.value ASC',
+ ];
+ }
$cpf['join'][$row['col_name']] = 'LEFT JOIN {db_prefix}themes AS t' . $row['col_name'] . ' ON (t' . $row['col_name'] . '.variable = {literal:' . $row['col_name'] . '} AND t' . $row['col_name'] . '.id_theme = 1 AND t' . $row['col_name'] . '.id_member = mem.id_member)';
}
@@ -866,15 +874,17 @@ public static function getCustFields()
protected function __construct()
{
// Allow mods to add sub-actions and sort_links.
- IntegrationHook::call('integrate_memberlist_subactions', array(&self::$subactions, $this->sort_links));
+ IntegrationHook::call('integrate_memberlist_subactions', [&self::$subactions, $this->sort_links]);
- if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
+ if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Memberlist::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Memberlist::exportStatic')) {
Memberlist::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/MessageIndex.php b/Sources/Actions/MessageIndex.php
index 1dbeb4bffd..943887bf00 100644
--- a/Sources/Actions/MessageIndex.php
+++ b/Sources/Actions/MessageIndex.php
@@ -14,11 +14,11 @@
namespace SMF\Actions;
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\IntegrationHook;
use SMF\Lang;
@@ -27,7 +27,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This class shows the list of topics in a board.
@@ -44,11 +43,13 @@ class MessageIndex implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static array $backcompat = array(
- 'func_names' => array(
+ private static array $backcompat = [
+ 'func_names' => [
'call' => 'MessageIndex',
- ),
- );
+ 'getBoardList' => 'getBoardList',
+ 'buildTopicContext' => 'buildTopicContext',
+ ],
+ ];
/*******************
* Public properties
@@ -59,43 +60,43 @@ class MessageIndex implements ActionInterface
*
* Default sort methods.
*/
- public array $sort_methods = array(
- 'subject' => array(
+ public array $sort_methods = [
+ 'subject' => [
'column' => 'mf.subject',
'joins' => 'JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)',
'asc_default' => true,
- ),
- 'starter' => array(
+ ],
+ 'starter' => [
'column' => 'COALESCE(memf.real_name, mf.poster_name)',
'joins' => 'JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)' . "\n\t\t\t" . 'LEFT JOIN {db_prefix}members AS memf ON (memf.id_member = mf.id_member)',
'asc_default' => true,
- ),
- 'last_poster' => array(
+ ],
+ 'last_poster' => [
'column' => 'COALESCE(meml.real_name, ml.poster_name)',
'joins' => 'JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)' . "\n\t\t\t" . 'LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)',
'asc_default' => true,
- ),
- 'replies' => array(
+ ],
+ 'replies' => [
'column' => 't.num_replies',
'joins' => '',
'asc_default' => true,
- ),
- 'views' => array(
+ ],
+ 'views' => [
'column' => 't.num_views',
'joins' => '',
'asc_default' => true,
- ),
- 'first_post' => array(
+ ],
+ 'first_post' => [
'column' => 't.id_topic',
'joins' => '',
'asc_default' => false,
- ),
- 'last_post' => array(
+ ],
+ 'last_post' => [
'column' => 't.id_last_msg',
'joins' => '',
'asc_default' => false,
- ),
- );
+ ],
+ ];
/**
* @var string
@@ -182,8 +183,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;
}
@@ -202,68 +204,66 @@ public static function call(): void
* @param array $boardListOptions An array of options for the board list.
* @return array An array of board info.
*/
- public static function getBoardList($boardListOptions = array()): array
+ public static function getBoardList($boardListOptions = []): array
{
- if (isset($boardListOptions['excluded_boards']) && isset($boardListOptions['included_boards']))
- {
+ if (isset($boardListOptions['excluded_boards'], $boardListOptions['included_boards'])) {
Lang::load('Errors');
trigger_error(Lang::$txt['get_board_list_cannot_include_and_exclude'], E_USER_ERROR);
}
- $where = array();
- $where_parameters = array();
- if (isset($boardListOptions['excluded_boards']))
- {
+ $where = [];
+ $where_parameters = [];
+
+ if (isset($boardListOptions['excluded_boards'])) {
$where[] = 'b.id_board NOT IN ({array_int:excluded_boards})';
$where_parameters['excluded_boards'] = $boardListOptions['excluded_boards'];
}
- if (isset($boardListOptions['included_boards']))
- {
+ if (isset($boardListOptions['included_boards'])) {
$where[] = 'b.id_board IN ({array_int:included_boards})';
$where_parameters['included_boards'] = $boardListOptions['included_boards'];
}
- if (!empty($boardListOptions['ignore_boards']))
+ if (!empty($boardListOptions['ignore_boards'])) {
$where[] = '{query_wanna_see_board}';
-
- elseif (!empty($boardListOptions['use_permissions']))
+ } elseif (!empty($boardListOptions['use_permissions'])) {
$where[] = '{query_see_board}';
+ }
- if (!empty($boardListOptions['not_redirection']))
- {
+ if (!empty($boardListOptions['not_redirection'])) {
$where[] = 'b.redirect = {string:blank_redirect}';
$where_parameters['blank_redirect'] = '';
}
- $request = Db::$db->query('order_by_board_order', '
- SELECT c.name AS cat_name, c.id_cat, b.id_board, b.name AS board_name, b.child_level, b.redirect
+ $request = Db::$db->query(
+ 'order_by_board_order',
+ 'SELECT c.name AS cat_name, c.id_cat, b.id_board, b.name AS board_name, b.child_level, b.redirect
FROM {db_prefix}boards AS b
LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)' . (empty($where) ? '' : '
WHERE ' . implode('
AND ', $where)),
- $where_parameters
+ $where_parameters,
);
- $return_value = array();
- if (Db::$db->num_rows($request) !== 0)
- {
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (!isset($return_value[$row['id_cat']]))
- $return_value[$row['id_cat']] = array(
+ $return_value = [];
+
+ if (Db::$db->num_rows($request) !== 0) {
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (!isset($return_value[$row['id_cat']])) {
+ $return_value[$row['id_cat']] = [
'id' => $row['id_cat'],
'name' => $row['cat_name'],
- 'boards' => array(),
- );
+ 'boards' => [],
+ ];
+ }
- $return_value[$row['id_cat']]['boards'][$row['id_board']] = array(
+ $return_value[$row['id_cat']]['boards'][$row['id_board']] = [
'id' => $row['id_board'],
'name' => $row['board_name'],
'child_level' => $row['child_level'],
'redirect' => $row['redirect'],
'selected' => isset($boardListOptions['selected_board']) && $boardListOptions['selected_board'] == $row['id_board'],
- );
+ ];
}
}
Db::$db->free_result($request);
@@ -285,106 +285,110 @@ public static function buildTopicContext(array $row)
$colorClass = 'windowbg';
// Does the theme support message previews?
- if (!empty(Config::$modSettings['preview_characters']))
- {
+ if (!empty(Config::$modSettings['preview_characters'])) {
// Limit them to Config::$modSettings['preview_characters'] characters
- $row['first_body'] = strip_tags(strtr(BBCodeParser::load()->parse($row['first_body'], $row['first_smileys'], $row['id_first_msg']), array(' ' => '
')));
- if (Utils::entityStrlen($row['first_body']) > Config::$modSettings['preview_characters'])
+ $row['first_body'] = strip_tags(strtr(BBCodeParser::load()->parse($row['first_body'], $row['first_smileys'], $row['id_first_msg']), [' ' => '
']));
+
+ if (Utils::entityStrlen($row['first_body']) > Config::$modSettings['preview_characters']) {
$row['first_body'] = Utils::entitySubstr($row['first_body'], 0, Config::$modSettings['preview_characters']) . '...';
+ }
// Censor the subject and message preview.
Lang::censorText($row['first_subject']);
Lang::censorText($row['first_body']);
// Don't censor them twice!
- if ($row['id_first_msg'] == $row['id_last_msg'])
- {
+ if ($row['id_first_msg'] == $row['id_last_msg']) {
$row['last_subject'] = $row['first_subject'];
$row['last_body'] = $row['first_body'];
- }
- else
- {
- $row['last_body'] = strip_tags(strtr(BBCodeParser::load()->parse($row['last_body'], $row['last_smileys'], $row['id_last_msg']), array(' ' => '
')));
- if (Utils::entityStrlen($row['last_body']) > Config::$modSettings['preview_characters'])
+ } else {
+ $row['last_body'] = strip_tags(strtr(BBCodeParser::load()->parse($row['last_body'], $row['last_smileys'], $row['id_last_msg']), [' ' => '
']));
+
+ if (Utils::entityStrlen($row['last_body']) > Config::$modSettings['preview_characters']) {
$row['last_body'] = Utils::entitySubstr($row['last_body'], 0, Config::$modSettings['preview_characters']) . '...';
+ }
Lang::censorText($row['last_subject']);
Lang::censorText($row['last_body']);
}
- }
- else
- {
+ } else {
$row['first_body'] = '';
$row['last_body'] = '';
Lang::censorText($row['first_subject']);
- if ($row['id_first_msg'] == $row['id_last_msg'])
+ if ($row['id_first_msg'] == $row['id_last_msg']) {
$row['last_subject'] = $row['first_subject'];
- else
+ } else {
Lang::censorText($row['last_subject']);
+ }
}
// Decide how many pages the topic should have.
- if ($row['num_replies'] + 1 > Utils::$context['messages_per_page'])
- {
+ if ($row['num_replies'] + 1 > Utils::$context['messages_per_page']) {
// We can't pass start by reference.
$start = -1;
$pages = new PageIndex(Config::$scripturl . '?topic=' . $row['id_topic'] . '.%1$d', $start, $row['num_replies'] + 1, Utils::$context['messages_per_page'], true, false);
// If we can use all, show all.
- if (!empty(Config::$modSettings['enableAllMessages']) && $row['num_replies'] + 1 < Config::$modSettings['enableAllMessages'])
- $pages .= sprintf(strtr(Theme::$current->settings['page_index']['page'], array('{URL}' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0;all')), '', Lang::$txt['all']);
- }
- else
+ if (!empty(Config::$modSettings['enableAllMessages']) && $row['num_replies'] + 1 < Config::$modSettings['enableAllMessages']) {
+ $pages .= sprintf(strtr(Theme::$current->settings['page_index']['page'], ['{URL}' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0;all']), '', Lang::$txt['all']);
+ }
+ } else {
$pages = '';
+ }
// We need to check the topic icons exist...
- if (!empty(Config::$modSettings['messageIconChecks_enable']))
- {
- if (!isset(Utils::$context['icon_sources'][$row['first_icon']]))
+ if (!empty(Config::$modSettings['messageIconChecks_enable'])) {
+ if (!isset(Utils::$context['icon_sources'][$row['first_icon']])) {
Utils::$context['icon_sources'][$row['first_icon']] = file_exists(Theme::$current->settings['theme_dir'] . '/images/post/' . $row['first_icon'] . '.png') ? 'images_url' : 'default_images_url';
- if (!isset(Utils::$context['icon_sources'][$row['last_icon']]))
+ }
+
+ if (!isset(Utils::$context['icon_sources'][$row['last_icon']])) {
Utils::$context['icon_sources'][$row['last_icon']] = file_exists(Theme::$current->settings['theme_dir'] . '/images/post/' . $row['last_icon'] . '.png') ? 'images_url' : 'default_images_url';
- }
- else
- {
- if (!isset(Utils::$context['icon_sources'][$row['first_icon']]))
+ }
+ } else {
+ if (!isset(Utils::$context['icon_sources'][$row['first_icon']])) {
Utils::$context['icon_sources'][$row['first_icon']] = 'images_url';
- if (!isset(Utils::$context['icon_sources'][$row['last_icon']]))
+ }
+
+ if (!isset(Utils::$context['icon_sources'][$row['last_icon']])) {
Utils::$context['icon_sources'][$row['last_icon']] = 'images_url';
+ }
}
// Force the recycling icon if appropriate
- if (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] == $row['id_board'])
- {
+ if (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] == $row['id_board']) {
$row['first_icon'] = 'recycled';
$row['last_icon'] = 'recycled';
}
// Is this topic pending approval, or does it have any posts pending approval?
- if (!empty($row['unapproved_posts']) && User::$me->allowedTo('approve_posts'))
+ if (!empty($row['unapproved_posts']) && User::$me->allowedTo('approve_posts')) {
$colorClass .= (!$row['approved'] ? ' approvetopic' : ' approvepost');
+ }
// Sticky topics should get a different color, too.
- if ($row['is_sticky'])
+ if ($row['is_sticky']) {
$colorClass .= ' sticky';
+ }
// Locked topics get special treatment as well.
- if ($row['locked'])
+ if ($row['locked']) {
$colorClass .= ' locked';
+ }
// 'Print' the topic info.
- Utils::$context['topics'][$row['id_topic']] = array_merge($row, array(
+ Utils::$context['topics'][$row['id_topic']] = array_merge($row, [
'id' => $row['id_topic'],
- 'first_post' => array(
+ 'first_post' => [
'id' => $row['id_first_msg'],
- 'member' => array(
+ 'member' => [
'username' => $row['first_member_name'],
'name' => $row['first_display_name'],
'id' => $row['first_id_member'],
'href' => !empty($row['first_id_member']) ? Config::$scripturl . '?action=profile;u=' . $row['first_id_member'] : '',
- 'link' => !empty($row['first_id_member']) ? '' . $row['first_display_name'] . '' : $row['first_display_name']
- ),
+ 'link' => !empty($row['first_id_member']) ? '' . $row['first_display_name'] . '' : $row['first_display_name'],
+ ],
'time' => Time::create('@' . $row['first_poster_time'])->format(),
'timestamp' => $row['first_poster_time'],
'subject' => $row['first_subject'],
@@ -393,16 +397,16 @@ public static function buildTopicContext(array $row)
'icon_url' => Theme::$current->settings[Utils::$context['icon_sources'][$row['first_icon']]] . '/post/' . $row['first_icon'] . '.png',
'href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0',
'link' => '' . $row['first_subject'] . '',
- ),
- 'last_post' => array(
+ ],
+ 'last_post' => [
'id' => $row['id_last_msg'],
- 'member' => array(
+ 'member' => [
'username' => $row['last_member_name'],
'name' => $row['last_display_name'],
'id' => $row['last_id_member'],
'href' => !empty($row['last_id_member']) ? Config::$scripturl . '?action=profile;u=' . $row['last_id_member'] : '',
- 'link' => !empty($row['last_id_member']) ? '' . $row['last_display_name'] . '' : $row['last_display_name']
- ),
+ 'link' => !empty($row['last_id_member']) ? '' . $row['last_display_name'] . '' : $row['last_display_name'],
+ ],
'time' => Time::create('@' . $row['last_poster_time'])->format(),
'timestamp' => $row['last_poster_time'],
'subject' => $row['last_subject'],
@@ -410,8 +414,8 @@ public static function buildTopicContext(array $row)
'icon' => $row['last_icon'],
'icon_url' => Theme::$current->settings[Utils::$context['icon_sources'][$row['last_icon']]] . '/post/' . $row['last_icon'] . '.png',
'href' => Config::$scripturl . '?topic=' . $row['id_topic'] . (User::$me->is_guest ? ('.' . (!empty(Theme::$current->options['view_newest_first']) ? 0 : ((int) (($row['num_replies']) / Utils::$context['messages_per_page'])) * Utils::$context['messages_per_page']) . '#msg' . $row['id_last_msg']) : (($row['num_replies'] == 0 ? '.0' : '.msg' . $row['id_last_msg']) . '#new')),
- 'link' => '' . $row['last_subject'] . ''
- ),
+ 'link' => '' . $row['last_subject'] . '',
+ ],
'is_sticky' => !empty($row['is_sticky']),
'is_locked' => !empty($row['locked']),
'is_redirect' => !empty($row['id_redirect_topic']),
@@ -431,22 +435,22 @@ public static function buildTopicContext(array $row)
'approved' => $row['approved'],
'unapproved_posts' => $row['unapproved_posts'],
'css_class' => $colorClass,
- ));
- if (!empty(Theme::$current->settings['avatars_on_indexes']))
- {
+ ]);
+
+ if (!empty(Theme::$current->settings['avatars_on_indexes'])) {
// Last post member avatar
- Utils::$context['topics'][$row['id_topic']]['last_post']['member']['avatar'] = User::setAvatarData(array(
+ Utils::$context['topics'][$row['id_topic']]['last_post']['member']['avatar'] = User::setAvatarData([
'avatar' => $row['avatar'],
'email' => $row['email_address'],
'filename' => !empty($row['last_member_filename']) ? $row['last_member_filename'] : '',
- ));
+ ]);
// First post member avatar
- Utils::$context['topics'][$row['id_topic']]['first_post']['member']['avatar'] = User::setAvatarData(array(
+ Utils::$context['topics'][$row['id_topic']]['first_post']['member']['avatar'] = User::setAvatarData([
'avatar' => $row['first_member_avatar'],
'email' => $row['first_member_mail'],
'filename' => !empty($row['first_member_filename']) ? $row['first_member_filename'] : '',
- ));
+ ]);
}
}
@@ -461,8 +465,9 @@ public static function buildTopicContext(array $row)
*/
protected function __construct()
{
- if (empty(Board::$info->id))
+ if (empty(Board::$info->id)) {
ErrorHandler::fatalLang('no_board', false);
+ }
$this->checkRedirect();
$this->preventPrefetch();
@@ -482,15 +487,15 @@ protected function __construct()
*/
protected function checkRedirect(): void
{
- if (Board::$info->redirect)
- {
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ if (Board::$info->redirect) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET num_posts = num_posts + 1
WHERE id_board = {int:current_board}',
- array(
+ [
'current_board' => Board::$info->id,
- )
+ ],
);
Utils::redirectexit(Board::$info->redirect);
@@ -502,14 +507,13 @@ protected function checkRedirect(): void
*/
protected function preventPrefetch(): void
{
- if (!User::$me->is_guest)
- {
+ if (!User::$me->is_guest) {
// We can't know they read it if we allow prefetches.
// But we'll actually mark it read later after we've done everything else.
- if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
- {
+ if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
ob_end_clean();
Utils::sendHttpStatus(403, 'Prefetch Forbidden');
+
die;
}
}
@@ -522,15 +526,14 @@ protected function setSortMethod(): void
{
// This is a bit convoluted, but it's necessary to maintain backward
// compatibility for the expected parameters of the integration hook.
- foreach ($this->sort_methods as $method => $sort_info)
- {
+ foreach ($this->sort_methods as $method => $sort_info) {
$sort_columns[$method] = &$this->sort_methods[$method]['column'];
$sort_joins[$method] = &$this->sort_methods[$method]['joins'];
$sort_asc_defaults[$method] = &$this->sort_methods[$method]['asc_default'];
}
// Bring in any changes we want to make before the query.
- IntegrationHook::call('integrate_pre_messageindex', array(&$sort_columns, &$sort_joins, &$sort_asc_defaults, &$this->sort_default));
+ IntegrationHook::call('integrate_pre_messageindex', [&$sort_columns, &$sort_joins, &$sort_asc_defaults, &$this->sort_default]);
// Default to sorting by last post descending.
$this->sort_by = !isset($_REQUEST['sort']) || !isset($this->sort_methods[$_REQUEST['sort']]) ? $this->sort_default : $_REQUEST['sort'];
@@ -544,8 +547,7 @@ protected function setSortMethod(): void
Utils::$context['sort_by'] = $this->sort_by;
Lang::$txt['starter'] = Lang::$txt['started_by'];
- foreach ($this->sort_methods as $key => $val)
- {
+ foreach ($this->sort_methods as $key => $val) {
Utils::$context['topics_headers'][$key] = '' . Lang::$txt[$key] . ($this->sort_by == $key ? ' ' : '') . '';
}
}
@@ -566,12 +568,9 @@ protected function setPaginationAndLinks(): void
Utils::$context['maxindex'] = isset($_REQUEST['all']) && !empty(Config::$modSettings['enableAllMessages']) ? Board::$info->total_topics : Utils::$context['topics_per_page'];
// Make sure the starting place makes sense and construct the page index.
- if ($this->sort_by !== $this->sort_default || !$this->ascending_is_default)
- {
+ if ($this->sort_by !== $this->sort_default || !$this->ascending_is_default) {
Utils::$context['page_index'] = new PageIndex(Config::$scripturl . '?board=' . Board::$info->id . '.%1$d' . ($this->sort_default == $this->sort_by ? '' : ';sort=' . $this->sort_by) . ($this->ascending_is_default ? '' : ($this->ascending ? ';asc' : ';desc')), $_REQUEST['start'], Board::$info->total_topics, Utils::$context['maxindex'], true);
- }
- else
- {
+ } else {
Utils::$context['page_index'] = new PageIndex(Config::$scripturl . '?board=' . Board::$info->id . '.%1$d', $_REQUEST['start'], Board::$info->total_topics, Utils::$context['maxindex'], true);
}
@@ -579,24 +578,22 @@ protected function setPaginationAndLinks(): void
$can_show_all = !empty(Config::$modSettings['enableAllMessages']) && Utils::$context['maxindex'] > Config::$modSettings['enableAllMessages'];
- if (!($can_show_all && isset($_REQUEST['all'])))
- {
- Utils::$context['links'] = array(
+ if (!($can_show_all && isset($_REQUEST['all']))) {
+ Utils::$context['links'] = [
'first' => $_REQUEST['start'] >= Utils::$context['topics_per_page'] ? Config::$scripturl . '?board=' . Board::$info->id . '.0' : '',
'prev' => $_REQUEST['start'] >= Utils::$context['topics_per_page'] ? Config::$scripturl . '?board=' . Board::$info->id . '.' . ($_REQUEST['start'] - Utils::$context['topics_per_page']) : '',
'next' => $_REQUEST['start'] + Utils::$context['topics_per_page'] < Board::$info->total_topics ? Config::$scripturl . '?board=' . Board::$info->id . '.' . ($_REQUEST['start'] + Utils::$context['topics_per_page']) : '',
'last' => $_REQUEST['start'] + Utils::$context['topics_per_page'] < Board::$info->total_topics ? Config::$scripturl . '?board=' . Board::$info->id . '.' . (floor((Board::$info->total_topics - 1) / Utils::$context['topics_per_page']) * Utils::$context['topics_per_page']) : '',
- 'up' => Board::$info->parent == 0 ? Config::$scripturl . '?' : Config::$scripturl . '?board=' . Board::$info->parent . '.0'
- );
+ 'up' => Board::$info->parent == 0 ? Config::$scripturl . '?' : Config::$scripturl . '?board=' . Board::$info->parent . '.0',
+ ];
}
- Utils::$context['page_info'] = array(
+ Utils::$context['page_info'] = [
'current_page' => $_REQUEST['start'] / Utils::$context['topics_per_page'] + 1,
- 'num_pages' => floor((Board::$info->total_topics - 1) / Utils::$context['topics_per_page']) + 1
- );
+ 'num_pages' => floor((Board::$info->total_topics - 1) / Utils::$context['topics_per_page']) + 1,
+ ];
- if (isset($_REQUEST['all']) && $can_show_all)
- {
+ if (isset($_REQUEST['all']) && $can_show_all) {
Utils::$context['maxindex'] = Config::$modSettings['enableAllMessages'];
$_REQUEST['start'] = 0;
}
@@ -608,27 +605,29 @@ protected function setPaginationAndLinks(): void
protected function buildTopicList(): void
{
// Set up the default topic icons. We'll need them below.
- Utils::$context['icon_sources'] = array();
- foreach (Utils::$context['stable_icons'] as $icon)
+ Utils::$context['icon_sources'] = [];
+
+ foreach (Utils::$context['stable_icons'] as $icon) {
Utils::$context['icon_sources'][$icon] = 'images_url';
+ }
// Calculate the fastest way to get the topics.
$start = (int) $_REQUEST['start'];
- if ($start > (Board::$info->total_topics - 1) / 2)
- {
+
+ if ($start > (Board::$info->total_topics - 1) / 2) {
$this->ascending = !$this->ascending;
$fake_ascending = true;
Utils::$context['maxindex'] = Board::$info->total_topics < $start + Utils::$context['maxindex'] + 1 ? Board::$info->total_topics - $start : Utils::$context['maxindex'];
$start = Board::$info->total_topics < $start + Utils::$context['maxindex'] + 1 ? 0 : Board::$info->total_topics - $start - Utils::$context['maxindex'];
- }
- else
+ } else {
$fake_ascending = false;
+ }
- $topic_ids = array();
- Utils::$context['topics'] = array();
+ $topic_ids = [];
+ Utils::$context['topics'] = [];
// Grab the appropriate topic information...
- $params = array(
+ $params = [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'topic_list' => $topic_ids,
@@ -636,19 +635,20 @@ protected function buildTopicList(): void
'find_set_topics' => implode(',', $topic_ids),
'start' => $start,
'maxindex' => Utils::$context['maxindex'],
- );
+ ];
- $selects = array();
- $joins = array();
- $main_where = array();
- $sort_where = array();
+ $selects = [];
+ $joins = [];
+ $main_where = [];
+ $sort_where = [];
- IntegrationHook::call('integrate_message_index', array(&$selects, &$joins, &$params, &$main_where, &$topic_ids, &$sort_where));
+ IntegrationHook::call('integrate_message_index', [&$selects, &$joins, &$params, &$main_where, &$topic_ids, &$sort_where]);
- if (!empty(Config::$modSettings['enableParticipation']) && !User::$me->is_guest)
+ if (!empty(Config::$modSettings['enableParticipation']) && !User::$me->is_guest) {
$enableParticipation = true;
- else
+ } else {
$enableParticipation = false;
+ }
$sort_table = '
SELECT t.id_topic, t.id_first_msg, t.id_last_msg' . (!empty($selects) ? (', ' . implode(', ', $selects)) : '') . '
@@ -658,13 +658,14 @@ protected function buildTopicList(): void
WHERE t.id_board = {int:current_board} '
. (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
AND (t.approved = {int:is_approved}' . (User::$me->is_guest ? '' : ' OR t.id_member_started = {int:current_member}') . ')') . (!empty($sort_where) ? '
- AND ' . implode("\n\t\t\t\tAND ", $sort_where) : ''). '
+ AND ' . implode("\n\t\t\t\tAND ", $sort_where) : '') . '
ORDER BY is_sticky' . ($fake_ascending ? '' : ' DESC') . ', ' . $this->sort_column . ($this->ascending ? '' : ' DESC') . '
LIMIT {int:maxindex}
OFFSET {int:start} ';
- $result = Db::$db->query('substring', '
- SELECT
+ $result = Db::$db->query(
+ 'substring',
+ 'SELECT
t.id_topic, t.num_replies, t.locked, t.num_views, t.is_sticky, t.id_poll, t.id_board, t.id_previous_board,
' . (User::$me->is_guest ? '0' : 'COALESCE(lt.id_msg, COALESCE(lmr.id_msg, -1)) + 1') . ' AS new_from,
' . ($enableParticipation ? ' COALESCE(( SELECT 1 FROM {db_prefix}messages AS parti WHERE t.id_topic = parti.id_topic and parti.id_member = {int:current_member} LIMIT 1) , 0) as is_posted_in,
@@ -692,14 +693,14 @@ protected function buildTopicList(): void
' . (!empty($joins) ? implode("\n\t\t\t\t", $joins) : '') . '
' . (!empty($main_where) ? ' WHERE ' . implode("\n\t\t\t\tAND ", $main_where) : '') . '
ORDER BY is_sticky' . ($fake_ascending ? '' : ' DESC') . ', ' . $this->sort_column . ($this->ascending ? '' : ' DESC'),
- $params
+ $params,
);
// Begin 'printing' the message index for current board.
- while ($row = Db::$db->fetch_assoc($result))
- {
- if ($row['id_poll'] > 0 && Config::$modSettings['pollMode'] == '0')
+ while ($row = Db::$db->fetch_assoc($result)) {
+ if ($row['id_poll'] > 0 && Config::$modSettings['pollMode'] == '0') {
continue;
+ }
$topic_ids[] = $row['id_topic'];
@@ -708,8 +709,9 @@ protected function buildTopicList(): void
Db::$db->free_result($result);
// Fix the sequence of topics if they were retrieved in the wrong order. (for speed reasons...)
- if ($fake_ascending)
+ if ($fake_ascending) {
Utils::$context['topics'] = array_reverse(Utils::$context['topics'], true);
+ }
}
/**
@@ -717,13 +719,13 @@ protected function buildTopicList(): void
*/
protected function buildChildBoardIndex(): void
{
- $boardIndexOptions = array(
+ $boardIndexOptions = [
'include_categories' => false,
'base_level' => Board::$info->child_level + 1,
'parent_id' => Board::$info->id,
'set_latest_post' => false,
'countChildPosts' => !empty(Config::$modSettings['countChildPosts']),
- );
+ ];
Utils::$context['boards'] = BoardIndex::get($boardIndexOptions);
}
@@ -732,84 +734,87 @@ protected function buildChildBoardIndex(): void
*/
protected function markViewed(): void
{
- if (!User::$me->is_guest)
- {
- Db::$db->insert('replace',
+ if (!User::$me->is_guest) {
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_boards',
- array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
- array(Config::$modSettings['maxMsgID'], User::$me->id, Board::$info->id),
- array('id_member', 'id_board')
+ ['id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'],
+ [Config::$modSettings['maxMsgID'], User::$me->id, Board::$info->id],
+ ['id_member', 'id_board'],
);
- if (!empty(Board::$info->parent_boards))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}log_boards
+ if (!empty(Board::$info->parent_boards)) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_boards
SET id_msg = {int:id_msg}
WHERE id_member = {int:current_member}
AND id_board IN ({array_int:board_list})',
- array(
+ [
'current_member' => User::$me->id,
'board_list' => array_keys(Board::$info->parent_boards),
'id_msg' => Config::$modSettings['maxMsgID'],
- )
+ ],
);
// We've seen all these boards now!
- foreach (Board::$info->parent_boards as $k => $dummy)
- if (isset($_SESSION['topicseen_cache'][$k]))
+ foreach (Board::$info->parent_boards as $k => $dummy) {
+ if (isset($_SESSION['topicseen_cache'][$k])) {
unset($_SESSION['topicseen_cache'][$k]);
+ }
+ }
}
- if (isset($_SESSION['topicseen_cache'][Board::$info->id]))
+ if (isset($_SESSION['topicseen_cache'][Board::$info->id])) {
unset($_SESSION['topicseen_cache'][Board::$info->id]);
+ }
- $request = Db::$db->query('', '
- SELECT id_topic, id_board, sent
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic, id_board, sent
FROM {db_prefix}log_notify
WHERE id_member = {int:current_member}
AND (' . (!empty(Utils::$context['topics']) ? 'id_topic IN ({array_int:topics}) OR ' : '') . 'id_board = {int:current_board})',
- array(
+ [
'current_board' => Board::$info->id,
- 'topics' => !empty(Utils::$context['topics']) ? array_keys(Utils::$context['topics']) : array(),
+ 'topics' => !empty(Utils::$context['topics']) ? array_keys(Utils::$context['topics']) : [],
'current_member' => User::$me->id,
- )
+ ],
);
Utils::$context['is_marked_notify'] = false; // this is for the *board* only
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (!empty($row['id_board']))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (!empty($row['id_board'])) {
Utils::$context['is_marked_notify'] = true;
$board_sent = $row['sent'];
}
- if (!empty($row['id_topic']))
+
+ if (!empty($row['id_topic'])) {
Utils::$context['topics'][$row['id_topic']]['is_watched'] = true;
+ }
}
Db::$db->free_result($request);
- if (Utils::$context['is_marked_notify'] && !empty($board_sent))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}log_notify
+ if (Utils::$context['is_marked_notify'] && !empty($board_sent)) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_notify
SET sent = {int:is_sent}
WHERE id_member = {int:current_member}
AND id_board = {int:current_board}',
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'is_sent' => 0,
- )
+ ],
);
}
- $pref = Notify::getNotifyPrefs(User::$me->id, array('board_notify', 'board_notify_' . Board::$info->id), true);
- $pref = !empty($pref[User::$me->id]) ? $pref[User::$me->id] : array();
- $pref = isset($pref['board_notify_' . Board::$info->id]) ? $pref['board_notify_' . Board::$info->id] : (!empty($pref['board_notify']) ? $pref['board_notify'] : 0);
+ $pref = Notify::getNotifyPrefs(User::$me->id, ['board_notify', 'board_notify_' . Board::$info->id], true);
+ $pref = !empty($pref[User::$me->id]) ? $pref[User::$me->id] : [];
+ $pref = $pref['board_notify_' . Board::$info->id] ?? (!empty($pref['board_notify']) ? $pref['board_notify'] : 0);
Utils::$context['board_notification_mode'] = !Utils::$context['is_marked_notify'] ? 1 : ($pref & 0x02 ? 3 : ($pref & 0x01 ? 2 : 1));
- }
- else
- {
+ } else {
Utils::$context['is_marked_notify'] = false;
Utils::$context['board_notification_mode'] = 1;
}
@@ -820,45 +825,50 @@ protected function markViewed(): void
*/
protected function getWhoViewing(): void
{
- if (!empty(Theme::$current->settings['display_who_viewing']))
- {
- Utils::$context['view_members'] = array();
- Utils::$context['view_members_list'] = array();
+ if (!empty(Theme::$current->settings['display_who_viewing'])) {
+ Utils::$context['view_members'] = [];
+ Utils::$context['view_members_list'] = [];
Utils::$context['view_num_hidden'] = 0;
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
lo.id_member, lo.log_time, mem.real_name, mem.member_name, mem.show_online,
mg.online_color, mg.id_group, mg.group_name
FROM {db_prefix}log_online AS lo
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lo.id_member)
LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:reg_member_group} THEN mem.id_post_group ELSE mem.id_group END)
WHERE INSTR(lo.url, {string:in_url_string}) > 0 OR lo.session = {string:session}',
- array(
+ [
'reg_member_group' => 0,
'in_url_string' => '"board":' . Board::$info->id,
'session' => User::$me->is_guest ? 'ip' . User::$me->ip : session_id(),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (empty($row['id_member']))
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (empty($row['id_member'])) {
continue;
+ }
- if (!empty($row['online_color']))
+ if (!empty($row['online_color'])) {
$link = '' . $row['real_name'] . '';
- else
+ } else {
$link = '' . $row['real_name'] . '';
+ }
$is_buddy = in_array($row['id_member'], User::$me->buddies);
- if ($is_buddy)
+
+ if ($is_buddy) {
$link = '' . $link . '';
+ }
- if (!empty($row['show_online']) || User::$me->allowedTo('moderate_forum'))
+ if (!empty($row['show_online']) || User::$me->allowedTo('moderate_forum')) {
Utils::$context['view_members_list'][$row['log_time'] . $row['member_name']] = empty($row['show_online']) ? '' . $link . '' : $link;
+ }
// @todo why are we filling this array of data that are just counted (twice) and discarded? ???
- Utils::$context['view_members'][$row['log_time'] . $row['member_name']] = array(
+ Utils::$context['view_members'][$row['log_time'] . $row['member_name']] = [
'id' => $row['id_member'],
'username' => $row['member_name'],
'name' => $row['real_name'],
@@ -867,10 +877,11 @@ protected function getWhoViewing(): void
'link' => $link,
'is_buddy' => $is_buddy,
'hidden' => empty($row['show_online']),
- );
+ ];
- if (empty($row['show_online']))
+ if (empty($row['show_online'])) {
Utils::$context['view_num_hidden']++;
+ }
}
Utils::$context['view_num_guests'] = Db::$db->num_rows($request) - count(Utils::$context['view_members']);
Db::$db->free_result($request);
@@ -889,24 +900,23 @@ protected function setModerators(): void
// Build a list of the board's moderators.
Utils::$context['moderators'] = &Board::$info->moderators;
Utils::$context['moderator_groups'] = &Board::$info->moderator_groups;
- Utils::$context['link_moderators'] = array();
+ Utils::$context['link_moderators'] = [];
- if (!empty(Board::$info->moderators))
- {
- foreach (Board::$info->moderators as $mod)
+ if (!empty(Board::$info->moderators)) {
+ foreach (Board::$info->moderators as $mod) {
Utils::$context['link_moderators'][] = '' . $mod['name'] . '';
+ }
}
- if (!empty(Board::$info->moderator_groups))
- {
+ if (!empty(Board::$info->moderator_groups)) {
// By default just tack the moderator groups onto the end of the members
- foreach (Board::$info->moderator_groups as $mod_group)
+ foreach (Board::$info->moderator_groups as $mod_group) {
Utils::$context['link_moderators'][] = '' . $mod_group['name'] . '';
+ }
}
// Now we tack the info onto the end of the linktree
- if (!empty(Utils::$context['link_moderators']))
- {
+ if (!empty(Utils::$context['link_moderators'])) {
Utils::$context['linktree'][count(Utils::$context['linktree']) - 1]['extra_after'] = '(' . (count(Utils::$context['link_moderators']) == 1 ? Lang::$txt['moderator'] : Lang::$txt['moderators']) . ': ' . implode(', ', Utils::$context['link_moderators']) . ')';
}
}
@@ -917,8 +927,7 @@ protected function setModerators(): void
protected function setUnapprovedPostsMessage(): void
{
// If we can view unapproved messages and there are some build up a list.
- if (User::$me->allowedTo('approve_posts') && (Board::$info->unapproved_topics || Board::$info->unapproved_posts))
- {
+ if (User::$me->allowedTo('approve_posts') && (Board::$info->unapproved_topics || Board::$info->unapproved_posts)) {
$untopics = Board::$info->unapproved_topics ? '' . Board::$info->unapproved_topics . '' : 0;
$unposts = Board::$info->unapproved_posts ? '' . (Board::$info->unapproved_posts - Board::$info->unapproved_topics) . '' : 0;
@@ -927,7 +936,7 @@ protected function setUnapprovedPostsMessage(): void
Lang::$txt['there_are_unapproved_topics'],
$untopics,
$unposts,
- Config::$scripturl . '?action=moderate;area=postmod;sa=' . (Board::$info->unapproved_topics ? 'topics' : 'posts') . ';brd=' . Board::$info->id
+ Config::$scripturl . '?action=moderate;area=postmod;sa=' . (Board::$info->unapproved_topics ? 'topics' : 'posts') . ';brd=' . Board::$info->id,
);
}
@@ -944,7 +953,7 @@ protected function setupTemplate(): void
Theme::loadTemplate('MessageIndex');
// Javascript for inline editing.
- Theme::loadJavaScriptFile('topic.js', array('defer' => false, 'minimize' => true), 'smf_topic');
+ Theme::loadJavaScriptFile('topic.js', ['defer' => false, 'minimize' => true], 'smf_topic');
// 'Print' the header and board info.
Utils::$context['page_title'] = strip_tags(Board::$info->name);
@@ -954,8 +963,9 @@ protected function setupTemplate(): void
Utils::$context['name'] = Board::$info->name;
Utils::$context['description'] = Board::$info->description;
- if (!empty(Board::$info->description))
+ if (!empty(Board::$info->description)) {
Utils::$context['meta_description'] = strip_tags(Board::$info->description);
+ }
// Set a canonical URL for this page.
Utils::$context['canonical_url'] = Config::$scripturl . '?board=' . Board::$info->id . '.' . Utils::$context['start'];
@@ -966,11 +976,11 @@ protected function setupTemplate(): void
Utils::$context['can_moderate_forum'] = User::$me->allowedTo('moderate_forum');
Utils::$context['can_approve_posts'] = User::$me->allowedTo('approve_posts');
- Utils::$context['jump_to'] = array(
+ Utils::$context['jump_to'] = [
'label' => addslashes(Utils::htmlspecialcharsDecode(Lang::$txt['jump_to'])),
- 'board_name' => strtr(Utils::htmlspecialchars(strip_tags(Board::$info->name)), array('&' => '&')),
+ 'board_name' => strtr(Utils::htmlspecialchars(strip_tags(Board::$info->name)), ['&' => '&']),
'child_level' => Board::$info->child_level,
- );
+ ];
}
/**
@@ -979,18 +989,19 @@ protected function setupTemplate(): void
protected function setRobotNoIndex(): void
{
// Right, let's only index normal stuff!
- if (count($_GET) > 1)
- {
+ if (count($_GET) > 1) {
$session_name = session_name();
- foreach ($_GET as $k => $v)
- {
- if (!in_array($k, array('board', 'start', $session_name)))
+
+ foreach ($_GET as $k => $v) {
+ if (!in_array($k, ['board', 'start', $session_name])) {
Utils::$context['robot_no_index'] = true;
+ }
}
}
- if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % Utils::$context['topics_per_page'] != 0))
+ if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % Utils::$context['topics_per_page'] != 0)) {
Utils::$context['robot_no_index'] = true;
+ }
}
/**
@@ -999,8 +1010,7 @@ protected function setRobotNoIndex(): void
protected function buildQuickMod(): void
{
// Is Quick Moderation active/needed?
- if (!empty(Theme::$current->options['display_quick_mod']) && !empty(Utils::$context['topics']))
- {
+ if (!empty(Theme::$current->options['display_quick_mod']) && !empty(Utils::$context['topics'])) {
Utils::$context['can_markread'] = User::$me->is_logged;
Utils::$context['can_lock'] = User::$me->allowedTo('lock_any');
Utils::$context['can_sticky'] = User::$me->allowedTo('make_sticky');
@@ -1012,10 +1022,9 @@ protected function buildQuickMod(): void
// Can we restore topics?
Utils::$context['can_restore'] = User::$me->allowedTo('move_any') && !empty(Board::$info->recycle);
- if (User::$me->is_admin || Config::$modSettings['topic_move_any'])
+ if (User::$me->is_admin || Config::$modSettings['topic_move_any']) {
Utils::$context['can_move_any'] = true;
- else
- {
+ } else {
// We'll use this in a minute
$boards_allowed = User::$me->boardsAllowedTo('post_new');
@@ -1024,32 +1033,32 @@ protected function buildQuickMod(): void
}
// Set permissions for all the topics.
- foreach (Utils::$context['topics'] as $t => $topic)
- {
+ foreach (Utils::$context['topics'] as $t => $topic) {
$started = $topic['first_post']['member']['id'] == User::$me->id;
- Utils::$context['topics'][$t]['quick_mod'] = array(
+ Utils::$context['topics'][$t]['quick_mod'] = [
'lock' => User::$me->allowedTo('lock_any') || ($started && User::$me->allowedTo('lock_own')),
'sticky' => User::$me->allowedTo('make_sticky'),
'move' => (User::$me->allowedTo('move_any') || ($started && User::$me->allowedTo('move_own')) && Utils::$context['can_move_any']),
'modify' => User::$me->allowedTo('modify_any') || ($started && User::$me->allowedTo('modify_own')),
'remove' => User::$me->allowedTo('remove_any') || ($started && User::$me->allowedTo('remove_own')),
- 'approve' => Utils::$context['can_approve'] && $topic['unapproved_posts']
- );
+ 'approve' => Utils::$context['can_approve'] && $topic['unapproved_posts'],
+ ];
Utils::$context['can_lock'] |= ($started && User::$me->allowedTo('lock_own'));
Utils::$context['can_move'] |= ($started && User::$me->allowedTo('move_own') && Utils::$context['can_move_any']);
Utils::$context['can_remove'] |= ($started && User::$me->allowedTo('remove_own'));
}
// Can we use quick moderation checkboxes?
- if (Theme::$current->options['display_quick_mod'] == 1)
+ if (Theme::$current->options['display_quick_mod'] == 1) {
Utils::$context['can_quick_mod'] = User::$me->is_logged || Utils::$context['can_approve'] || Utils::$context['can_remove'] || Utils::$context['can_lock'] || Utils::$context['can_sticky'] || Utils::$context['can_move'] || Utils::$context['can_merge'] || Utils::$context['can_restore'];
+ }
// Or the icons?
- else
+ else {
Utils::$context['can_quick_mod'] = Utils::$context['can_remove'] || Utils::$context['can_lock'] || Utils::$context['can_sticky'] || Utils::$context['can_move'];
+ }
}
- if (!empty(Utils::$context['can_quick_mod']) && Theme::$current->options['display_quick_mod'] == 1)
- {
+ if (!empty(Utils::$context['can_quick_mod']) && Theme::$current->options['display_quick_mod'] == 1) {
// Sets Utils::$context['qmod_actions']
// This is also where the integrate_quick_mod_actions hook now lives.
QuickModeration::getActions();
@@ -1061,46 +1070,50 @@ protected function buildQuickMod(): void
*/
protected function buildButtons(): void
{
- Utils::$context['normal_buttons'] = array();
+ Utils::$context['normal_buttons'] = [];
- if (Utils::$context['can_post_new'])
- Utils::$context['normal_buttons']['new_topic'] = array('text' => 'new_topic', 'image' => 'new_topic.png', 'lang' => true, 'url' => Config::$scripturl . '?action=post;board=' . Utils::$context['current_board'] . '.0', 'active' => true);
+ if (Utils::$context['can_post_new']) {
+ Utils::$context['normal_buttons']['new_topic'] = ['text' => 'new_topic', 'image' => 'new_topic.png', 'lang' => true, 'url' => Config::$scripturl . '?action=post;board=' . Utils::$context['current_board'] . '.0', 'active' => true];
+ }
- if (Utils::$context['can_post_poll'])
- Utils::$context['normal_buttons']['post_poll'] = array('text' => 'new_poll', 'image' => 'new_poll.png', 'lang' => true, 'url' => Config::$scripturl . '?action=post;board=' . Utils::$context['current_board'] . '.0;poll');
+ if (Utils::$context['can_post_poll']) {
+ Utils::$context['normal_buttons']['post_poll'] = ['text' => 'new_poll', 'image' => 'new_poll.png', 'lang' => true, 'url' => Config::$scripturl . '?action=post;board=' . Utils::$context['current_board'] . '.0;poll'];
+ }
- if (User::$me->is_logged)
- Utils::$context['normal_buttons']['markread'] = array('text' => 'mark_read_short', 'image' => 'markread.png', 'lang' => true, 'custom' => 'data-confirm="' . Lang::$txt['are_sure_mark_read'] . '"', 'class' => 'you_sure', 'url' => Config::$scripturl . '?action=markasread;sa=board;board=' . Utils::$context['current_board'] . '.0;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']);
+ if (User::$me->is_logged) {
+ Utils::$context['normal_buttons']['markread'] = ['text' => 'mark_read_short', 'image' => 'markread.png', 'lang' => true, 'custom' => 'data-confirm="' . Lang::$txt['are_sure_mark_read'] . '"', 'class' => 'you_sure', 'url' => Config::$scripturl . '?action=markasread;sa=board;board=' . Utils::$context['current_board'] . '.0;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']];
+ }
- if (Utils::$context['can_mark_notify'])
- Utils::$context['normal_buttons']['notify'] = array(
+ if (Utils::$context['can_mark_notify']) {
+ Utils::$context['normal_buttons']['notify'] = [
'lang' => true,
'text' => 'notify_board_' . Utils::$context['board_notification_mode'],
- 'sub_buttons' => array(
- array(
+ 'sub_buttons' => [
+ [
'text' => 'notify_board_1',
'url' => Config::$scripturl . '?action=notifyboard;board=' . Board::$info->id . ';mode=1;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
- ),
- array(
+ ],
+ [
'text' => 'notify_board_2',
'url' => Config::$scripturl . '?action=notifyboard;board=' . Board::$info->id . ';mode=2;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
- ),
- array(
+ ],
+ [
'text' => 'notify_board_3',
'url' => Config::$scripturl . '?action=notifyboard;board=' . Board::$info->id . ';mode=3;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
- ),
- ),
- );
+ ],
+ ],
+ ];
+ }
// Allow adding new buttons easily.
// Note: Utils::$context['normal_buttons'] is added for backward compatibility with 2.0, but is deprecated and should not be used
- IntegrationHook::call('integrate_messageindex_buttons', array(&Utils::$context['normal_buttons']));
+ IntegrationHook::call('integrate_messageindex_buttons', [&Utils::$context['normal_buttons']]);
}
-
}
// Export public static functions to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\MessageIndex::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\MessageIndex::exportStatic')) {
MessageIndex::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Moderation/EndSession.php b/Sources/Actions/Moderation/EndSession.php
index 1d4e1f9886..86e62434ef 100644
--- a/Sources/Actions/Moderation/EndSession.php
+++ b/Sources/Actions/Moderation/EndSession.php
@@ -13,9 +13,8 @@
namespace SMF\Actions\Moderation;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Utils;
/**
@@ -31,12 +30,11 @@ class EndSession implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ModEndSession',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -63,10 +61,10 @@ public function execute(): void
unset($_SESSION['moderate_time']);
// Clean any moderator tokens as well.
- foreach ($_SESSION['token'] as $key => $token)
- {
- if (strpos($key, '-mod') !== false)
+ foreach ($_SESSION['token'] as $key => $token) {
+ if (strpos($key, '-mod') !== false) {
unset($_SESSION['token'][$key]);
+ }
}
Utils::redirectexit();
@@ -83,8 +81,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;
}
@@ -110,7 +109,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/Moderation/Groups.php b/Sources/Actions/Moderation/Groups.php
index 333a92a5a4..51d07d29fe 100644
--- a/Sources/Actions/Moderation/Groups.php
+++ b/Sources/Actions/Moderation/Groups.php
@@ -11,8 +11,9 @@
* @version 3.0 Alpha 1
*/
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
// Just an alias to help people looking for the action in the wrong namespace.
class_alias('SMF\\Actions\\Groups', 'SMF\\Actions\\Moderation\\Groups');
diff --git a/Sources/Actions/Moderation/Home.php b/Sources/Actions/Moderation/Home.php
index 411aa54a99..56a0887165 100644
--- a/Sources/Actions/Moderation/Home.php
+++ b/Sources/Actions/Moderation/Home.php
@@ -13,11 +13,12 @@
namespace SMF\Actions\Moderation;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+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;
@@ -27,8 +28,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* This is the home page of the moderation center.
@@ -42,12 +41,11 @@ class Home implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ModerationHome',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -58,33 +56,33 @@ class Home implements ActionInterface
*
* Blocks of data to show on the moderation center home page.
*/
- public array $blocks = array(
- 'g' => array(
+ public array $blocks = [
+ 'g' => [
'func' => 'groupRequests',
'sub_template' => 'group_requests_block',
'context_var' => 'group_requests',
- 'permissions' => array('can_moderate_groups'),
- ),
- 'r' => array(
+ 'permissions' => ['can_moderate_groups'],
+ ],
+ 'r' => [
'func' => 'reportedPosts',
'sub_template' => 'reported_posts_block',
'context_var' => 'reported_posts',
- 'permissions' => array('can_moderate_boards'),
- ),
- 'w' => array(
+ 'permissions' => ['can_moderate_boards'],
+ ],
+ 'w' => [
'func' => 'watchedUsers',
'sub_template' => 'watched_users',
'context_var' => 'watched_users',
// There are two possible reasons to grant someone access to this.
- 'permissions' => array('can_moderate_boards', 'can_moderate_users'),
- ),
- 'rm' => array(
+ 'permissions' => ['can_moderate_boards', 'can_moderate_users'],
+ ],
+ 'rm' => [
'func' => 'reportedMembers',
'sub_template' => 'reported_users_block',
'context_var' => 'reported_users',
- 'permissions' => array('can_moderate_users'),
- ),
- );
+ 'permissions' => ['can_moderate_users'],
+ ],
+ ];
/****************************
* Internal static properties
@@ -110,37 +108,36 @@ public function execute(): void
// Normally this will already have been done, but just in case...
Main::checkAccessPermissions();
- Utils::$context['mod_blocks'] = array();
+ Utils::$context['mod_blocks'] = [];
// Handle moderators' notes.
$this->notes();
- IntegrationHook::call('integrate_moderation_home_blocks', array(&$this->blocks));
+ IntegrationHook::call('integrate_moderation_home_blocks', [&$this->blocks]);
- foreach ($this->blocks as $k => $block)
- {
+ foreach ($this->blocks as $k => $block) {
// Define the context variable even if the block is disabled.
- Utils::$context[$block['context_var']] = array();
+ Utils::$context[$block['context_var']] = [];
// Is this block enabled?
$enabled = false;
- foreach ($block['permissions'] as $permission)
+ foreach ($block['permissions'] as $permission) {
$enabled |= Utils::$context[$permission];
+ }
- if (!$enabled)
+ if (!$enabled) {
continue;
-
- if (method_exists($this, $block['func']))
- {
- call_user_func(array($this, $block['func']));
}
- else
- {
+
+ if (method_exists($this, $block['func'])) {
+ call_user_func([$this, $block['func']]);
+ } else {
$call = Utils::getCallable($block['func']);
- if (!empty($call))
+ if (!empty($call)) {
call_user_func($call);
+ }
}
Utils::$context['mod_blocks'][] = $this->blocks[$k]['sub_template'];
@@ -149,7 +146,7 @@ public function execute(): void
// Backward compatibility for mods using the integrate_mod_centre_blocks hook.
self::integrateModBlocks();
- Utils::$context['admin_prefs'] = !empty(Theme::$current->options['admin_preferences']) ? Utils::jsonDecode(Theme::$current->options['admin_preferences'], true) : array();
+ Utils::$context['admin_prefs'] = !empty(Theme::$current->options['admin_preferences']) ? Utils::jsonDecode(Theme::$current->options['admin_preferences'], true) : [];
}
/***********************
@@ -163,8 +160,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;
}
@@ -187,7 +185,7 @@ public static function call(): void
protected function __construct()
{
Theme::loadTemplate('ModerationCenter');
- Theme::loadJavaScriptFile('admin.js', array('minimize' => true), 'smf_admin');
+ Theme::loadJavaScriptFile('admin.js', ['minimize' => true], 'smf_admin');
Utils::$context['page_title'] = Lang::$txt['moderation_center'];
Utils::$context['sub_template'] = 'moderation_center';
@@ -199,31 +197,31 @@ protected function __construct()
protected function notes(): void
{
// Set a nice and informative message.
- Utils::$context['report_post_action'] = !empty($_SESSION['rc_confirmation']) ? $_SESSION['rc_confirmation'] : array();
+ Utils::$context['report_post_action'] = !empty($_SESSION['rc_confirmation']) ? $_SESSION['rc_confirmation'] : [];
unset($_SESSION['rc_confirmation']);
// Are we saving a note?
- if (isset($_GET['modnote']) && isset($_POST['makenote']) && isset($_POST['new_note']))
- {
+ if (isset($_GET['modnote'], $_POST['makenote'], $_POST['new_note'])) {
User::$me->checkSession();
SecurityToken::validate('mod-modnote-add');
$_POST['new_note'] = Utils::htmlspecialchars(trim($_POST['new_note']));
+
// Make sure they actually entered something.
- if (!empty($_POST['new_note']))
- {
+ if (!empty($_POST['new_note'])) {
// Insert it into the database then!
- Db::$db->insert('',
+ Db::$db->insert(
+ '',
'{db_prefix}log_comments',
- array(
+ [
'id_member' => 'int', 'member_name' => 'string', 'comment_type' => 'string', 'recipient_name' => 'string',
'body' => 'string', 'log_time' => 'int',
- ),
- array(
+ ],
+ [
User::$me->id, User::$me->name, 'modnote', '', $_POST['new_note'], time(),
- ),
- array('id_comment')
+ ],
+ ['id_comment'],
);
// Clear the cache.
@@ -239,42 +237,43 @@ protected function notes(): void
}
// Bye... bye...
- if (isset($_GET['notes']) && isset($_GET['delete']) && is_numeric($_GET['delete']))
- {
+ if (isset($_GET['notes'], $_GET['delete']) && is_numeric($_GET['delete'])) {
User::$me->checkSession('get');
SecurityToken::validate('mod-modnote-del', 'get');
// No sneaky stuff now!
- if (!User::$me->allowedTo('admin_forum'))
- {
+ if (!User::$me->allowedTo('admin_forum')) {
// Is this your note?
- $get_owner = Db::$db->query('', '
- SELECT id_member
+ $get_owner = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}log_comments
WHERE id_comment = {int:note}
AND comment_type = {literal:modnote}
AND id_member = {int:user}',
- array(
+ [
'note' => $_GET['delete'],
'user' => User::$me->id,
- )
+ ],
);
$note_owner = Db::$db->num_rows($get_owner);
Db::$db->free_result($get_owner);
- if (empty($note_owner))
+ if (empty($note_owner)) {
ErrorHandler::fatalLang('mc_notes_delete_own', false);
+ }
}
// Lets delete it.
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_comments
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_comments
WHERE id_comment = {int:note}
AND comment_type = {literal:modnote}',
- array(
+ [
'note' => $_GET['delete'],
- )
+ ],
);
// Clear the cache.
@@ -288,17 +287,17 @@ protected function notes(): void
}
// How many notes in total?
- if (($moderator_notes_total = CacheApi::get('moderator_notes_total', 240)) === null)
- {
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ if (($moderator_notes_total = CacheApi::get('moderator_notes_total', 240)) === null) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_comments AS lc
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
WHERE lc.comment_type = {literal:modnote}',
- array(
- )
+ [
+ ],
);
- list ($moderator_notes_total) = Db::$db->fetch_row($request);
+ list($moderator_notes_total) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
CacheApi::put('moderator_notes_total', $moderator_notes_total, 240);
@@ -306,51 +305,52 @@ protected function notes(): void
// Grab the current notes. We can only use the cache for the first page of notes.
$offset = isset($_GET['notes']) && isset($_GET['start']) ? $_GET['start'] : 0;
+ $start = (int) ($_GET['start'] ?? 0);
- if ($offset != 0 || ($moderator_notes = CacheApi::get('moderator_notes', 240)) === null)
- {
- $moderator_notes = array();
+ if ($offset != 0 || ($moderator_notes = CacheApi::get('moderator_notes', 240)) === null) {
+ $moderator_notes = [];
- $request = Db::$db->query('', '
- SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name,
+ $request = Db::$db->query(
+ '',
+ 'SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name,
lc.log_time, lc.body, lc.id_comment AS id_note
FROM {db_prefix}log_comments AS lc
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
WHERE lc.comment_type = {literal:modnote}
ORDER BY id_comment DESC
LIMIT {int:offset}, 10',
- array(
+ [
'offset' => $offset,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$moderator_notes[] = $row;
}
Db::$db->free_result($request);
- if ($offset == 0)
+ if ($offset == 0) {
CacheApi::put('moderator_notes', $moderator_notes, 240);
+ }
}
// Lets construct a page index.
- Utils::$context['page_index'] = new PageIndex(Config::$scripturl . '?action=moderate;area=index;notes', $_GET['start'], $moderator_notes_total, 10);
- Utils::$context['start'] = $_GET['start'];
+ Utils::$context['page_index'] = new PageIndex(Config::$scripturl . '?action=moderate;area=index;notes', $start, $moderator_notes_total, 10);
+ Utils::$context['start'] = $start;
- Utils::$context['notes'] = array();
+ Utils::$context['notes'] = [];
- foreach ($moderator_notes as $note)
- {
- Utils::$context['notes'][] = array(
- 'author' => array(
+ foreach ($moderator_notes as $note) {
+ Utils::$context['notes'][] = [
+ 'author' => [
'id' => $note['id_member'],
'link' => $note['id_member'] ? ('' . $note['member_name'] . '') : $note['member_name'],
- ),
+ ],
'time' => Time::create('@' . $note['log_time'])->format(),
'text' => BBCodeParser::load()->parse($note['body']),
'delete_href' => Config::$scripturl . '?action=moderate;area=index;notes;delete=' . $note['id_note'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'can_delete' => User::$me->allowedTo('admin_forum') || $note['id_member'] == User::$me->id,
- );
+ ];
}
// Couple tokens for add/delete modnotes
@@ -364,12 +364,14 @@ protected function notes(): void
protected function groupRequests(): void
{
// Make sure they can even moderate someone!
- if (User::$me->mod_cache['gq'] == '0=1')
+ if (User::$me->mod_cache['gq'] == '0=1') {
return;
+ }
// What requests are outstanding?
- $request = Db::$db->query('', '
- SELECT lgr.id_request, lgr.id_member, lgr.id_group, lgr.time_applied, mem.member_name, mg.group_name, mem.real_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT lgr.id_request, lgr.id_member, lgr.id_group, lgr.time_applied, mem.member_name, mg.group_name, mem.real_name
FROM {db_prefix}log_group_requests AS lgr
INNER JOIN {db_prefix}members AS mem ON (mem.id_member = lgr.id_member)
INNER JOIN {db_prefix}membergroups AS mg ON (mg.id_group = lgr.id_group)
@@ -377,27 +379,27 @@ protected function groupRequests(): void
AND lgr.status = {int:status_open}
ORDER BY lgr.id_request DESC
LIMIT 10',
- array(
+ [
'status_open' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- Utils::$context['group_requests'][] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ Utils::$context['group_requests'][] = [
'id' => $row['id_request'],
'request_href' => Config::$scripturl . '?action=groups;sa=requests;gid=' . $row['id_group'],
- 'member' => array(
+ 'member' => [
'id' => $row['id_member'],
'name' => $row['real_name'],
'link' => '' . $row['real_name'] . '',
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- ),
- 'group' => array(
+ ],
+ 'group' => [
'id' => $row['id_group'],
'name' => $row['group_name'],
- ),
+ ],
'time_submitted' => Time::create('@' . $row['time_applied'])->format(),
- );
+ ];
}
Db::$db->free_result($request);
}
@@ -407,24 +409,24 @@ protected function groupRequests(): void
*/
protected function watchedUsers(): void
{
- if (($watched_users = CacheApi::get('recent_user_watches', 240)) === null)
- {
+ if (($watched_users = CacheApi::get('recent_user_watches', 240)) === null) {
Config::$modSettings['warning_watch'] = empty(Config::$modSettings['warning_watch']) ? 1 : Config::$modSettings['warning_watch'];
- $watched_users = array();
+ $watched_users = [];
- $request = Db::$db->query('', '
- SELECT id_member, real_name, last_login
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name, last_login
FROM {db_prefix}members
WHERE warning >= {int:warning_watch}
ORDER BY last_login DESC
LIMIT 10',
- array(
+ [
'warning_watch' => Config::$modSettings['warning_watch'],
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$watched_users[] = $row;
}
Db::$db->free_result($request);
@@ -432,15 +434,14 @@ protected function watchedUsers(): void
CacheApi::put('recent_user_watches', $watched_users, 240);
}
- foreach ($watched_users as $user)
- {
- Utils::$context['watched_users'][] = array(
+ foreach ($watched_users as $user) {
+ Utils::$context['watched_users'][] = [
'id' => $user['id_member'],
'name' => $user['real_name'],
'link' => '' . $user['real_name'] . '',
'href' => Config::$scripturl . '?action=profile;u=' . $user['id_member'],
'last_login' => !empty($user['last_login']) ? Time::create('@' . $user['last_login'])->format() : '',
- );
+ ];
}
}
@@ -449,19 +450,20 @@ protected function watchedUsers(): void
*/
protected function reportedPosts(): void
{
- if (User::$me->mod_cache['bq'] == '0=1')
+ if (User::$me->mod_cache['bq'] == '0=1') {
return;
+ }
// Got the info already?
$cachekey = md5(Utils::jsonEncode(User::$me->mod_cache['bq']));
- if (($reported_posts = CacheApi::get('reported_posts_' . $cachekey, 90)) === null)
- {
+ if (($reported_posts = CacheApi::get('reported_posts_' . $cachekey, 90)) === null) {
// By George, that means we in a position to get the reports, jolly good.
- $reported_posts = array();
+ $reported_posts = [];
- $request = Db::$db->query('', '
- SELECT lr.id_report, lr.id_msg, lr.id_topic, lr.id_board, lr.id_member, lr.subject,
+ $request = Db::$db->query(
+ '',
+ 'SELECT lr.id_report, lr.id_msg, lr.id_topic, lr.id_board, lr.id_member, lr.subject,
lr.num_reports, COALESCE(mem.real_name, lr.membername) AS author_name,
COALESCE(mem.id_member, 0) AS id_author
FROM {db_prefix}log_reported AS lr
@@ -472,14 +474,14 @@ protected function reportedPosts(): void
AND lr.ignore_all = {int:not_ignored}
ORDER BY lr.time_updated DESC
LIMIT 10',
- array(
+ [
'not_a_reported_post' => 0,
'not_closed' => 0,
'not_ignored' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$reported_posts[] = $row;
}
Db::$db->free_result($request);
@@ -487,22 +489,21 @@ protected function reportedPosts(): void
CacheApi::put('reported_posts_' . $cachekey, $reported_posts, 90);
}
- foreach ($reported_posts as $i => $row)
- {
- Utils::$context['reported_posts'][] = array(
+ foreach ($reported_posts as $i => $row) {
+ Utils::$context['reported_posts'][] = [
'id' => $row['id_report'],
'topic_href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
'report_href' => Config::$scripturl . '?action=moderate;area=reportedposts;sa=details;rid=' . $row['id_report'],
'report_link' => '' . $row['subject'] . '',
- 'author' => array(
+ 'author' => [
'id' => $row['id_author'],
'name' => $row['author_name'],
'link' => $row['id_author'] ? '' . $row['author_name'] . '' : $row['author_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_author'],
- ),
+ ],
'subject' => $row['subject'],
'num_reports' => $row['num_reports'],
- );
+ ];
}
}
@@ -511,17 +512,18 @@ protected function reportedPosts(): void
*/
protected function reportedMembers(): void
{
- if (!User::$me->allowedTo('moderate_forum'))
+ if (!User::$me->allowedTo('moderate_forum')) {
return;
+ }
$cachekey = md5(Utils::jsonEncode((int) User::$me->allowedTo('moderate_forum')));
-
- if (($reported_users = CacheApi::get('reported_users_' . $cachekey, 90)) === null)
- {
- $reported_users = array();
- $request = Db::$db->query('', '
- SELECT lr.id_report, lr.id_member,
+ if (($reported_users = CacheApi::get('reported_users_' . $cachekey, 90)) === null) {
+ $reported_users = [];
+
+ $request = Db::$db->query(
+ '',
+ 'SELECT lr.id_report, lr.id_member,
lr.num_reports, COALESCE(mem.real_name, lr.membername) AS user_name,
COALESCE(mem.id_member, 0) AS id_user
FROM {db_prefix}log_reported AS lr
@@ -531,14 +533,14 @@ protected function reportedMembers(): void
AND lr.ignore_all = {int:not_ignored}
ORDER BY lr.time_updated DESC
LIMIT 10',
- array(
+ [
'not_a_reported_post' => 0,
'not_closed' => 0,
'not_ignored' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$reported_users[] = $row;
}
Db::$db->free_result($request);
@@ -546,19 +548,18 @@ protected function reportedMembers(): void
CacheApi::put('reported_users_' . $cachekey, $reported_users, 90);
}
- foreach ($reported_users as $i => $row)
- {
- Utils::$context['reported_users'][] = array(
+ foreach ($reported_users as $i => $row) {
+ Utils::$context['reported_users'][] = [
'id' => $row['id_report'],
'report_href' => Config::$scripturl . '?action=moderate;area=reportedmembers;report=' . $row['id_report'],
- 'user' => array(
+ 'user' => [
'id' => $row['id_user'],
'name' => $row['user_name'],
'link' => $row['id_user'] ? '' . $row['user_name'] . '' : $row['user_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_user'],
- ),
+ ],
'num_reports' => $row['num_reports'],
- );
+ ];
}
}
@@ -568,30 +569,32 @@ protected function reportedMembers(): void
/**
* Provides a home for the deprecated integrate_mod_centre_blocks hook.
- *
+ *
* MOD AUTHORS: Please use the integrate_moderation_home_blocks instead.
*/
protected static function integrateModBlocks()
{
- $valid_blocks = array();
+ $valid_blocks = [];
- IntegrationHook::call('integrate_mod_centre_blocks', array(&$valid_blocks));
+ IntegrationHook::call('integrate_mod_centre_blocks', [&$valid_blocks]);
- if (empty($valid_blocks))
+ if (empty($valid_blocks)) {
return;
-
- foreach ($valid_blocks as $k => $func)
- {
+ }
+
+ foreach ($valid_blocks as $k => $func) {
$func = 'ModBlock' . $func;
- if (is_callable($func))
+ if (is_callable($func)) {
Utils::$context['mod_blocks'][] = $func();
+ }
}
}
}
// 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/Moderation/Logs.php b/Sources/Actions/Moderation/Logs.php
index 946d90dcc3..b3e823d946 100644
--- a/Sources/Actions/Moderation/Logs.php
+++ b/Sources/Actions/Moderation/Logs.php
@@ -13,10 +13,10 @@
namespace SMF\Actions\Moderation;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\IntegrationHook;
use SMF\IP;
use SMF\ItemList;
@@ -27,7 +27,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* The moderation and adminstration logs are this class's only job.
@@ -42,12 +41,13 @@ class Logs implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ViewModlog',
- ),
- );
+ 'list_getModLogEntryCount' => 'list_getModLogEntryCount',
+ 'list_getModLogEntries' => 'list_getModLogEntries',
+ ],
+ ];
/*****************
* Class constants
@@ -91,67 +91,67 @@ class Logs implements ActionInterface
*
* Actions that might call this class.
*/
- public static array $actions = array(
+ public static array $actions = [
'moderate',
'admin',
- );
+ ];
/**
* @var array
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'modlog' => 'modlog',
'adminlog' => 'adminlog',
- );
+ ];
/**
* @var array
*
* Actions whose log entries cannot be deleted.
*/
- public static array $uneditable_actions = array(
+ public static array $uneditable_actions = [
'agreement_updated',
'policy_updated',
- );
+ ];
/**
* @var array
*
* Instructions for how to sort columns.
*/
- public static array $sort_types = array(
+ public static array $sort_types = [
'action' => 'lm.action',
'time' => 'lm.log_time',
'member' => 'mem.real_name',
'group' => 'mg.group_name',
'ip' => 'lm.ip',
- );
+ ];
/**
* @var array
*
* This array houses all the valid search types.
*/
- public static array $search_types = array(
- 'action' => array(
+ public static array $search_types = [
+ 'action' => [
'sql' => 'lm.action',
'label' => 'modlog_action',
- ),
- 'member' => array(
+ ],
+ 'member' => [
'sql' => 'mem.real_name',
'label' => 'modlog_member',
- ),
- 'group' => array(
+ ],
+ 'group' => [
'sql' => 'mg.group_name',
'label' => 'modlog_position',
- ),
- 'ip' => array(
+ ],
+ 'ip' => [
'sql' => 'lm.ip',
'label' => 'modlog_ip',
- ),
- );
+ ],
+ ];
/*********************
* Internal properties
@@ -250,10 +250,11 @@ class Logs 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);
+ }
}
/**
@@ -293,8 +294,9 @@ public function modlog()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -317,12 +319,13 @@ public static function call(): void
* @param bool $ignore_boards Whether to ignore board restrictions
* @return int Total number of visible log entries.
*/
- public static function list_getModLogEntryCount($query_string = '', $query_params = array(), $log_type = 1, $ignore_boards = false): int
+ public static function list_getModLogEntryCount($query_string = '', $query_params = [], $log_type = 1, $ignore_boards = false): int
{
- $modlog_query = User::$me->allowedTo('admin_forum') || User::$me->mod_cache['bq'] == '1=1' ? '1=1' : ((User::$me->mod_cache['bq'] == '0=1' || $ignore_boards) ? 'lm.id_board = 0 AND lm.id_topic = 0' : (strtr(User::$me->mod_cache['bq'], array('id_board' => 'b.id_board')) . ' AND ' . strtr(User::$me->mod_cache['bq'], array('id_board' => 't.id_board'))));
+ $modlog_query = User::$me->allowedTo('admin_forum') || User::$me->mod_cache['bq'] == '1=1' ? '1=1' : ((User::$me->mod_cache['bq'] == '0=1' || $ignore_boards) ? 'lm.id_board = 0 AND lm.id_topic = 0' : (strtr(User::$me->mod_cache['bq'], ['id_board' => 'b.id_board']) . ' AND ' . strtr(User::$me->mod_cache['bq'], ['id_board' => 't.id_board'])));
- $result = Db::$db->query('', '
- SELECT COUNT(*)
+ $result = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_actions AS lm
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lm.id_member)
LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:reg_group_id} THEN mem.id_post_group ELSE mem.id_group END)
@@ -332,11 +335,11 @@ public static function list_getModLogEntryCount($query_string = '', $query_param
AND {raw:modlog_query}'
. (!empty($query_string) ? '
AND ' . $query_string : ''),
- array_merge($query_params, array(
+ array_merge($query_params, [
'reg_group_id' => 0,
'log_type' => $log_type,
'modlog_query' => $modlog_query,
- ))
+ ]),
);
list($entry_count) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
@@ -357,19 +360,21 @@ public static function list_getModLogEntryCount($query_string = '', $query_param
* @param bool $ignore_boards Whether to ignore board restrictions
* @return array An array of info about the mod log entries
*/
- public static function list_getModLogEntries($start, $items_per_page, $sort, $query_string = '', $query_params = array(), $log_type = 1, $ignore_boards = false): array
+ public static function list_getModLogEntries($start, $items_per_page, $sort, $query_string = '', $query_params = [], $log_type = 1, $ignore_boards = false): array
{
- $modlog_query = User::$me->allowedTo('admin_forum') || User::$me->mod_cache['bq'] == '1=1' ? '1=1' : ((User::$me->mod_cache['bq'] == '0=1' || $ignore_boards) ? 'lm.id_board = 0 AND lm.id_topic = 0' : (strtr(User::$me->mod_cache['bq'], array('id_board' => 'b.id_board')) . ' AND ' . strtr(User::$me->mod_cache['bq'], array('id_board' => 't.id_board'))));
+ $modlog_query = User::$me->allowedTo('admin_forum') || User::$me->mod_cache['bq'] == '1=1' ? '1=1' : ((User::$me->mod_cache['bq'] == '0=1' || $ignore_boards) ? 'lm.id_board = 0 AND lm.id_topic = 0' : (strtr(User::$me->mod_cache['bq'], ['id_board' => 'b.id_board']) . ' AND ' . strtr(User::$me->mod_cache['bq'], ['id_board' => 't.id_board'])));
- if (!isset(self::$uneditable_actions))
- self::$uneditable_actions = array();
+ if (!isset(self::$uneditable_actions)) {
+ self::$uneditable_actions = [];
+ }
// Can they see the IP address?
$seeIP = User::$me->allowedTo('moderate_forum');
// Here we have the query getting the log details.
- $result = Db::$db->query('', '
- SELECT
+ $result = Db::$db->query(
+ '',
+ 'SELECT
lm.id_action, lm.id_member, lm.ip, lm.log_time, lm.action, lm.id_board, lm.id_topic, lm.id_msg, lm.extra,
mem.real_name, mg.group_name
FROM {db_prefix}log_actions AS lm
@@ -383,96 +388,111 @@ public static function list_getModLogEntries($start, $items_per_page, $sort, $qu
AND ' . $query_string : '') . '
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array_merge($query_params, array(
+ array_merge($query_params, [
'reg_group_id' => 0,
'log_type' => $log_type,
'modlog_query' => $modlog_query,
'sort' => $sort,
'start' => $start,
'max' => $items_per_page,
- ))
+ ]),
);
// Arrays for decoding objects into.
- $topics = array();
- $boards = array();
- $members = array();
- $messages = array();
- $entries = array();
- while ($row = Db::$db->fetch_assoc($result))
- {
+ $topics = [];
+ $boards = [];
+ $members = [];
+ $messages = [];
+ $entries = [];
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$row['extra'] = Utils::jsonDecode($row['extra'], true);
// Corrupt?
- $row['extra'] = is_array($row['extra']) ? $row['extra'] : array();
+ $row['extra'] = is_array($row['extra']) ? $row['extra'] : [];
// Add on some of the column stuff info
- if (!empty($row['id_board']))
- {
- if ($row['action'] == 'move')
+ if (!empty($row['id_board'])) {
+ if ($row['action'] == 'move') {
$row['extra']['board_to'] = $row['id_board'];
- else
+ } else {
$row['extra']['board'] = $row['id_board'];
+ }
}
- if (!empty($row['id_topic']))
+ if (!empty($row['id_topic'])) {
$row['extra']['topic'] = $row['id_topic'];
- if (!empty($row['id_msg']))
+ }
+
+ if (!empty($row['id_msg'])) {
$row['extra']['message'] = $row['id_msg'];
+ }
// Is this associated with a topic?
- if (isset($row['extra']['topic']))
+ if (isset($row['extra']['topic'])) {
$topics[(int) $row['extra']['topic']][] = $row['id_action'];
- if (isset($row['extra']['new_topic']))
+ }
+
+ if (isset($row['extra']['new_topic'])) {
$topics[(int) $row['extra']['new_topic']][] = $row['id_action'];
+ }
// How about a member?
- if (isset($row['extra']['member']))
- {
+ if (isset($row['extra']['member'])) {
// Guests don't have names!
- if (empty($row['extra']['member']))
+ if (empty($row['extra']['member'])) {
$row['extra']['member'] = Lang::$txt['modlog_parameter_guest'];
- else
- {
+ } else {
// Try to find it...
$members[(int) $row['extra']['member']][] = $row['id_action'];
}
}
// Associated with a board?
- if (isset($row['extra']['board_to']))
+ if (isset($row['extra']['board_to'])) {
$boards[(int) $row['extra']['board_to']][] = $row['id_action'];
- if (isset($row['extra']['board_from']))
+ }
+
+ if (isset($row['extra']['board_from'])) {
$boards[(int) $row['extra']['board_from']][] = $row['id_action'];
- if (isset($row['extra']['board']))
+ }
+
+ if (isset($row['extra']['board'])) {
$boards[(int) $row['extra']['board']][] = $row['id_action'];
+ }
// A message?
- if (isset($row['extra']['message']))
+ if (isset($row['extra']['message'])) {
$messages[(int) $row['extra']['message']][] = $row['id_action'];
+ }
// IP Info?
- if (isset($row['extra']['ip_range']))
- if ($seeIP)
+ if (isset($row['extra']['ip_range'])) {
+ if ($seeIP) {
$row['extra']['ip_range'] = '' . $row['extra']['ip_range'] . '';
- else
+ } else {
$row['extra']['ip_range'] = Lang::$txt['logged'];
+ }
+ }
// Email?
- if (isset($row['extra']['email']))
+ if (isset($row['extra']['email'])) {
$row['extra']['email'] = '' . $row['extra']['email'] . '';
+ }
// Bans are complex.
- if ($row['action'] == 'ban' || $row['action'] == 'banremove')
- {
+ if ($row['action'] == 'ban' || $row['action'] == 'banremove') {
$row['action_text'] = Lang::$txt['modlog_ac_ban' . ($row['action'] == 'banremove' ? '_remove' : '')];
- foreach (array('member', 'email', 'ip_range', 'hostname') as $type)
- if (isset($row['extra'][$type]))
+
+ foreach (['member', 'email', 'ip_range', 'hostname'] as $type) {
+ if (isset($row['extra'][$type])) {
$row['action_text'] .= Lang::$txt['modlog_ac_ban_trigger_' . $type];
+ }
+ }
}
// The array to go to the template. Note here that action is set to a "default" value of the action doesn't match anything in the descriptions. Allows easy adding of logging events with basic details.
- $entries[$row['id_action']] = array(
+ $entries[$row['id_action']] = [
'id' => $row['id_action'],
'ip' => $seeIP ? new IP($row['ip']) : Lang::$txt['logged'],
'position' => empty($row['real_name']) && empty($row['group_name']) ? Lang::$txt['guest'] : $row['group_name'],
@@ -482,133 +502,132 @@ public static function list_getModLogEntries($start, $items_per_page, $sort, $qu
'editable' => substr($row['action'], 0, 8) !== 'clearlog' && !in_array($row['action'], self::$uneditable_actions),
'extra' => $row['extra'],
'action' => $row['action'],
- 'action_text' => isset($row['action_text']) ? $row['action_text'] : '',
- );
+ 'action_text' => $row['action_text'] ?? '',
+ ];
}
Db::$db->free_result($result);
- if (!empty($boards))
- {
- $request = Db::$db->query('', '
- SELECT id_board, name
+ if (!empty($boards)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board, name
FROM {db_prefix}boards
WHERE id_board IN ({array_int:board_list})
LIMIT {int:limit}',
- array(
+ [
'board_list' => array_keys($boards),
'limit' => count(array_keys($boards)),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- foreach ($boards[$row['id_board']] as $action)
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ foreach ($boards[$row['id_board']] as $action) {
// Make the board number into a link - dealing with moving too.
- if (isset($entries[$action]['extra']['board_to']) && $entries[$action]['extra']['board_to'] == $row['id_board'])
+ if (isset($entries[$action]['extra']['board_to']) && $entries[$action]['extra']['board_to'] == $row['id_board']) {
$entries[$action]['extra']['board_to'] = '' . $row['name'] . '';
- elseif (isset($entries[$action]['extra']['board_from']) && $entries[$action]['extra']['board_from'] == $row['id_board'])
+ } elseif (isset($entries[$action]['extra']['board_from']) && $entries[$action]['extra']['board_from'] == $row['id_board']) {
$entries[$action]['extra']['board_from'] = '' . $row['name'] . '';
- elseif (isset($entries[$action]['extra']['board']) && $entries[$action]['extra']['board'] == $row['id_board'])
+ } elseif (isset($entries[$action]['extra']['board']) && $entries[$action]['extra']['board'] == $row['id_board']) {
$entries[$action]['extra']['board'] = '' . $row['name'] . '';
+ }
}
}
Db::$db->free_result($request);
}
- if (!empty($topics))
- {
- $request = Db::$db->query('', '
- SELECT ms.subject, t.id_topic
+ if (!empty($topics)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT ms.subject, t.id_topic
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
WHERE t.id_topic IN ({array_int:topic_list})
LIMIT {int:limit}',
- array(
+ [
'topic_list' => array_keys($topics),
'limit' => count(array_keys($topics)),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- foreach ($topics[$row['id_topic']] as $action)
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ foreach ($topics[$row['id_topic']] as $action) {
$this_action = &$entries[$action];
// This isn't used in the current theme.
- $this_action['topic'] = array(
+ $this_action['topic'] = [
'id' => $row['id_topic'],
'subject' => $row['subject'],
'href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.0',
- 'link' => '' . $row['subject'] . ''
- );
+ 'link' => '' . $row['subject'] . '',
+ ];
// Make the topic number into a link - dealing with splitting too.
- if (isset($this_action['extra']['topic']) && $this_action['extra']['topic'] == $row['id_topic'])
+ if (isset($this_action['extra']['topic']) && $this_action['extra']['topic'] == $row['id_topic']) {
$this_action['extra']['topic'] = '' . $row['subject'] . '';
- elseif (isset($this_action['extra']['new_topic']) && $this_action['extra']['new_topic'] == $row['id_topic'])
+ } elseif (isset($this_action['extra']['new_topic']) && $this_action['extra']['new_topic'] == $row['id_topic']) {
$this_action['extra']['new_topic'] = '' . $row['subject'] . '';
+ }
}
}
Db::$db->free_result($request);
}
- if (!empty($messages))
- {
- $request = Db::$db->query('', '
- SELECT id_msg, subject
+ if (!empty($messages)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_msg, subject
FROM {db_prefix}messages
WHERE id_msg IN ({array_int:message_list})
LIMIT {int:limit}',
- array(
+ [
'message_list' => array_keys($messages),
'limit' => count(array_keys($messages)),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- foreach ($messages[$row['id_msg']] as $action)
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ foreach ($messages[$row['id_msg']] as $action) {
$this_action = &$entries[$action];
// This isn't used in the current theme.
- $this_action['message'] = array(
+ $this_action['message'] = [
'id' => $row['id_msg'],
'subject' => $row['subject'],
'href' => Config::$scripturl . '?msg=' . $row['id_msg'],
'link' => '' . $row['subject'] . '',
- );
+ ];
// Make the message number into a link.
- if (isset($this_action['extra']['message']) && $this_action['extra']['message'] == $row['id_msg'])
+ if (isset($this_action['extra']['message']) && $this_action['extra']['message'] == $row['id_msg']) {
$this_action['extra']['message'] = '' . $row['subject'] . '';
+ }
}
}
Db::$db->free_result($request);
}
- if (!empty($members))
- {
- $request = Db::$db->query('', '
- SELECT real_name, id_member
+ if (!empty($members)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT real_name, id_member
FROM {db_prefix}members
WHERE id_member IN ({array_int:member_list})
LIMIT {int:limit}',
- array(
+ [
'member_list' => array_keys($members),
'limit' => count(array_keys($members)),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- foreach ($members[$row['id_member']] as $action)
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ foreach ($members[$row['id_member']] as $action) {
// Not used currently.
- $entries[$action]['member'] = array(
+ $entries[$action]['member'] = [
'id' => $row['id_member'],
'name' => $row['real_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- 'link' => '' . $row['real_name'] . ''
- );
+ 'link' => '' . $row['real_name'] . '',
+ ];
// Make the member number into a name.
$entries[$action]['extra']['member'] = '' . $row['real_name'] . '';
}
@@ -617,36 +636,38 @@ public static function list_getModLogEntries($start, $items_per_page, $sort, $qu
}
// Do some formatting of the action string.
- foreach ($entries as $k => $entry)
- {
+ foreach ($entries as $k => $entry) {
// Make any message info links so its easier to go find that message.
- if (isset($entry['extra']['message']) && (empty($entry['message']) || empty($entry['message']['id'])))
+ if (isset($entry['extra']['message']) && (empty($entry['message']) || empty($entry['message']['id']))) {
$entries[$k]['extra']['message'] = '' . $entry['extra']['message'] . '';
+ }
// Mark up any deleted members, topics and boards.
- foreach (array('board', 'board_from', 'board_to', 'member', 'topic', 'new_topic') as $type)
- if (!empty($entry['extra'][$type]) && is_numeric($entry['extra'][$type]))
+ foreach (['board', 'board_from', 'board_to', 'member', 'topic', 'new_topic'] as $type) {
+ if (!empty($entry['extra'][$type]) && is_numeric($entry['extra'][$type])) {
$entries[$k]['extra'][$type] = sprintf(Lang::$txt['modlog_id'], $entry['extra'][$type]);
+ }
+ }
- if (isset($entry['extra']['report']))
- {
+ if (isset($entry['extra']['report'])) {
// Member profile reports go in a different area
- if (stristr($entry['action'], 'user_report'))
+ if (stristr($entry['action'], 'user_report')) {
$entries[$k]['extra']['report'] = '' . Lang::$txt['modlog_report'] . '';
- else
+ } else {
$entries[$k]['extra']['report'] = '' . Lang::$txt['modlog_report'] . '';
+ }
}
- if (empty($entries[$k]['action_text']))
- $entries[$k]['action_text'] = isset(Lang::$txt['modlog_ac_' . $entry['action']]) ? Lang::$txt['modlog_ac_' . $entry['action']] : $entry['action'];
+ if (empty($entries[$k]['action_text'])) {
+ $entries[$k]['action_text'] = Lang::$txt['modlog_ac_' . $entry['action']] ?? $entry['action'];
+ }
$entries[$k]['action_text'] = preg_replace_callback(
'~\{([A-Za-z\d_]+)\}~i',
- function($matches) use ($entries, $k)
- {
- return isset($entries[$k]['extra'][$matches[1]]) ? $entries[$k]['extra'][$matches[1]] : '';
+ function ($matches) use ($entries, $k) {
+ return $entries[$k]['extra'][$matches[1]] ?? '';
},
- $entries[$k]['action_text']
+ $entries[$k]['action_text'],
);
}
@@ -663,21 +684,20 @@ function($matches) use ($entries, $k)
*/
protected function __construct()
{
- if (!empty($_REQUEST['action']) && in_array($_REQUEST['action'], self::$actions))
+ if (!empty($_REQUEST['action']) && in_array($_REQUEST['action'], self::$actions)) {
$this->action = $_REQUEST['action'];
+ }
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
+ }
$this->log_type = $this->subaction == 'adminlog' ? 3 : 1;
// These change dependant on whether we are viewing the moderation or admin log.
- if ($this->action == 'admin')
- {
+ if ($this->action == 'admin') {
$this->url_start = '?action=admin;area=logs;sa=' . ($this->log_type == 3 ? 'adminlog' : 'modlog') . ';type=' . $this->log_type;
- }
- else
- {
+ } else {
$this->url_start = '?action=moderate;area=modlog';
}
@@ -686,8 +706,9 @@ protected function __construct()
Lang::load('Admin+Modlog');
// Setup the direction stuff...
- if (!empty($_REQUEST['sort']) && isset(self::$sort_types[$_REQUEST['sort']]))
+ if (!empty($_REQUEST['sort']) && isset(self::$sort_types[$_REQUEST['sort']])) {
$this->sort = $_REQUEST['sort'];
+ }
// If we're coming from a search, set those variables.
$this->setupSearch();
@@ -698,53 +719,43 @@ protected function __construct()
*/
protected function setupSearch(): void
{
- if (!empty($_REQUEST['params']) && empty($_REQUEST['is_search']))
- {
- $this->search_params = base64_decode(strtr($_REQUEST['params'], array(' ' => '+')));
+ if (!empty($_REQUEST['params']) && empty($_REQUEST['is_search'])) {
+ $this->search_params = base64_decode(strtr($_REQUEST['params'], [' ' => '+']));
$this->search_params = Utils::jsonDecode($this->search_params, true);
}
- if (!isset($this->search_params['string']) || (!empty($_REQUEST['search']) && $this->search_params['string'] != $_REQUEST['search']))
- {
+ if (!isset($this->search_params['string']) || (!empty($_REQUEST['search']) && $this->search_params['string'] != $_REQUEST['search'])) {
$this->search_params_string = empty($_REQUEST['search']) ? '' : $_REQUEST['search'];
- }
- else
- {
+ } else {
$this->search_params_string = $this->search_params['string'];
}
- if (isset($_REQUEST['search_type']) || empty($this->search_params['type']) || !isset(self::$search_types[$this->search_params['type']]))
- {
+ if (isset($_REQUEST['search_type']) || empty($this->search_params['type']) || !isset(self::$search_types[$this->search_params['type']])) {
$this->search_params_type = isset($_REQUEST['search_type']) && isset(self::$search_types[$_REQUEST['search_type']]) ? $_REQUEST['search_type'] : (isset(self::$search_types[$this->sort]) ? $this->sort : 'member');
- }
- else
- {
+ } else {
$this->search_params_type = $this->search_params['type'];
}
$this->search_params_column = self::$search_types[$this->search_params_type]['sql'];
- $this->search_params = array(
+ $this->search_params = [
'string' => $this->search_params_string,
'type' => $this->search_params_type,
- );
+ ];
// Setup the search context.
$this->encoded_search_params = empty($this->search_params['string']) ? '' : base64_encode(Utils::jsonEncode($this->search_params));
- $this->search_info = array(
+ $this->search_info = [
'string' => $this->search_params['string'],
'type' => $this->search_params['type'],
'label' => Lang::$txt[self::$search_types[$this->search_params_type]['label']],
- );
+ ];
// If they are searching by action, then we must do some manual intervention to search in their language!
- if ($this->search_params['type'] == 'action' && !empty($this->search_params['string']))
- {
+ if ($this->search_params['type'] == 'action' && !empty($this->search_params['string'])) {
// For the moment they can only search for ONE action!
- foreach (Lang::$txt as $key => $text)
- {
- if (substr($key, 0, 10) == 'modlog_ac_' && strpos($text, $this->search_params['string']) !== false)
- {
+ foreach (Lang::$txt as $key => $text) {
+ if (substr($key, 0, 10) == 'modlog_ac_' && strpos($text, $this->search_params['string']) !== false) {
$this->search_params['string'] = substr($key, 10);
break;
}
@@ -757,12 +768,9 @@ protected function setupSearch(): void
*/
protected function deleteEntries(): void
{
- if (isset($_POST['removeall']) && $this->can_delete)
- {
+ if (isset($_POST['removeall']) && $this->can_delete) {
$this->deleteAll();
- }
- elseif (!empty($_POST['remove']) && isset($_POST['delete']) && $this->can_delete)
- {
+ } elseif (!empty($_POST['remove']) && isset($_POST['delete']) && $this->can_delete) {
$this->deleteEntry();
}
}
@@ -775,19 +783,19 @@ protected function deleteAll(): void
User::$me->checkSession();
SecurityToken::validate('mod-ml');
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_actions
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_actions
WHERE id_log = {int:moderate_log}
AND action NOT IN ({array_string:uneditable})',
-
- array(
+ [
'moderate_log' => $this->log_type,
'uneditable' => self::$uneditable_actions,
- )
+ ],
);
$log_type = isset($this->subaction) && $this->subaction == 'adminlog' ? 'admin' : 'moderate';
- Logging::logAction('clearlog_' . $log_type, array(), $log_type);
+ Logging::logAction('clearlog_' . $log_type, [], $log_type);
}
/**
@@ -799,18 +807,19 @@ protected function deleteEntry(): void
SecurityToken::validate('mod-ml');
// No sneaky removing the 'cleared the log' entries.
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_actions
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_actions
WHERE id_log = {int:moderate_log}
AND id_action IN ({array_string:delete_actions})
AND action NOT LIKE {string:clearlog}
AND action NOT IN ({array_string:uneditable})',
- array(
+ [
'delete_actions' => array_unique($_POST['delete']),
'moderate_log' => $this->log_type,
'uneditable' => self::$uneditable_actions,
'clearlog' => 'clearlog_%',
- )
+ ],
);
}
@@ -820,7 +829,7 @@ protected function deleteEntry(): void
protected function createList(): void
{
// This is all the information required for a watched user listing.
- $listOptions = array(
+ $listOptions = [
'id' => 'moderation_log_list',
'title' => $this->log_type == 3 ? Lang::$txt['admin_log'] : Lang::$txt['moderation_log'],
'width' => '100%',
@@ -828,120 +837,119 @@ protected function createList(): void
'no_items_label' => Lang::$txt['modlog_' . ($this->log_type == 3 ? 'admin_log_' : '') . 'no_entries_found'],
'base_href' => Config::$scripturl . $this->url_start . (!empty($this->encoded_search_params) ? ';params=' . $this->encoded_search_params : ''),
'default_sort_col' => 'time',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getModLogEntries',
- 'params' => array(
+ 'params' => [
(!empty($this->search_params['string']) ? ' INSTR({raw:sql_type}, {string:search_string}) > 0' : ''),
- array('sql_type' => $this->search_params_column, 'search_string' => $this->search_params['string']),
+ ['sql_type' => $this->search_params_column, 'search_string' => $this->search_params['string']],
$this->log_type,
- ),
- ),
- 'get_count' => array(
+ ],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getModLogEntryCount',
- 'params' => array(
+ 'params' => [
(!empty($this->search_params['string']) ? ' INSTR({raw:sql_type}, {string:search_string}) > 0' : ''),
- array('sql_type' => $this->search_params_column, 'search_string' => $this->search_params['string']),
+ ['sql_type' => $this->search_params_column, 'search_string' => $this->search_params['string']],
$this->log_type,
- ),
- ),
+ ],
+ ],
// This assumes we are viewing by user.
- 'columns' => array(
- 'action' => array(
- 'header' => array(
+ 'columns' => [
+ 'action' => [
+ 'header' => [
'value' => Lang::$txt['modlog_action'],
'class' => 'lefttext',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'action_text',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lm.action',
'reverse' => 'lm.action DESC',
- ),
- ),
- 'time' => array(
- 'header' => array(
+ ],
+ ],
+ 'time' => [
+ 'header' => [
'value' => Lang::$txt['modlog_date'],
'class' => 'lefttext',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lm.log_time DESC',
'reverse' => 'lm.log_time',
- ),
- ),
- 'moderator' => array(
- 'header' => array(
+ ],
+ ],
+ 'moderator' => [
+ 'header' => [
'value' => Lang::$txt['modlog_member'],
'class' => 'lefttext',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'moderator_link',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'mem.real_name',
'reverse' => 'mem.real_name DESC',
- ),
- ),
- 'position' => array(
- 'header' => array(
+ ],
+ ],
+ 'position' => [
+ 'header' => [
'value' => Lang::$txt['modlog_position'],
'class' => 'lefttext',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'position',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'mg.group_name',
'reverse' => 'mg.group_name DESC',
- ),
- ),
- 'ip' => array(
- 'header' => array(
+ ],
+ ],
+ 'ip' => [
+ 'header' => [
'value' => Lang::$txt['modlog_ip'],
'class' => 'lefttext',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'ip',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lm.ip',
'reverse' => 'lm.ip DESC',
- ),
- ),
- 'delete' => array(
- 'header' => array(
+ ],
+ ],
+ 'delete' => [
+ 'header' => [
'value' => '',
'class' => 'centercol',
- ),
- 'data' => array(
- 'function' => function($entry)
- {
+ ],
+ 'data' => [
+ 'function' => function ($entry) {
return '';
},
'class' => 'centercol',
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . $this->url_start,
'include_sort' => true,
'include_start' => true,
- 'hidden_fields' => array(
+ 'hidden_fields' => [
Utils::$context['session_var'] => Utils::$context['session_id'],
- 'params' => $this->encoded_search_params
- ),
+ 'params' => $this->encoded_search_params,
+ ],
'token' => 'mod-ml',
- ),
- 'additional_rows' => array(
- array(
+ ],
+ 'additional_rows' => [
+ [
'position' => 'after_title',
'value' => '
' . Lang::$txt['modlog_search'] . ' (' . Lang::$txt['modlog_by'] . ': ' . $this->search_info['label'] . '):
@@ -951,20 +959,20 @@ protected function createList(): void
' : ''),
'class' => '',
- ),
- array(
+ ],
+ [
'position' => 'below_table_data',
'value' => $this->can_delete ? '
' : '',
'class' => 'floatright',
- ),
- ),
- );
+ ],
+ ],
+ ];
// Overriding this with a hook?
- $moderation_menu_name = array();
- IntegrationHook::call('integrate_viewModLog', array(&$listOptions, &$moderation_menu_name));
+ $moderation_menu_name = [];
+ IntegrationHook::call('integrate_viewModLog', [&$listOptions, &$moderation_menu_name]);
SecurityToken::create('mod-ml');
@@ -975,17 +983,14 @@ protected function createList(): void
Utils::$context['default_list'] = 'moderation_log_list';
// If a hook has changed this, respect it.
- if (!empty($moderation_menu_name))
- {
+ if (!empty($moderation_menu_name)) {
Menu::$loaded['moderate']->tab_data = $moderation_menu_name;
- }
- elseif (isset(Utils::$context['moderation_menu_name']))
- {
- Menu::$loaded['moderate']->tab_data = array(
+ } elseif (isset(Utils::$context['moderation_menu_name'])) {
+ Menu::$loaded['moderate']->tab_data = [
'title' => Lang::$txt['modlog_' . ($this->log_type == 3 ? 'admin' : 'moderation') . '_log'],
'help' => $this->log_type == 3 ? 'adminlog' : 'modlog',
- 'description' => Lang::$txt['modlog_' . ($this->log_type == 3 ? 'admin' : 'moderation') . '_log_desc']
- );
+ 'description' => Lang::$txt['modlog_' . ($this->log_type == 3 ? 'admin' : 'moderation') . '_log_desc'],
+ ];
}
}
@@ -994,11 +999,11 @@ protected function createList(): void
*************************/
// code...
-
}
// 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/Moderation/Main.php b/Sources/Actions/Moderation/Main.php
index 37843a86e4..06a8fc4502 100644
--- a/Sources/Actions/Moderation/Main.php
+++ b/Sources/Actions/Moderation/Main.php
@@ -15,9 +15,8 @@
namespace SMF\Actions\Moderation;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
use SMF\ErrorHandler;
use SMF\Lang;
@@ -38,12 +37,12 @@ class Main implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'checkAccessPermissions' => 'checkAccessPermissions',
+ 'ModerationMain' => 'ModerationMain',
+ ],
+ ];
/*******************
* Public properties
@@ -69,148 +68,148 @@ class Main implements ActionInterface
* MOD AUTHORS: You can use the integration_moderation_areas hook to add
* things to this menu. The hook can be found in SMF\Menu::_construct().
*/
- public array $moderation_areas = array(
- 'main' => array(
+ public array $moderation_areas = [
+ 'main' => [
'title' => 'mc_main',
- 'areas' => array(
- 'index' => array(
+ 'areas' => [
+ 'index' => [
'label' => 'moderation_center',
'function' => __NAMESPACE__ . '\\Home::call',
'icon' => 'administration',
- ),
- 'modlogoff' => array(
+ ],
+ 'modlogoff' => [
'label' => 'mc_logoff',
'function' => __NAMESPACE__ . '\\EndSession::call',
'enabled' => true,
'icon' => 'exit',
- ),
- 'notice' => array(
+ ],
+ 'notice' => [
'function' => __NAMESPACE__ . '\\ShowNotice::call',
- 'select' => 'index'
- ),
- ),
- ),
- 'logs' => array(
+ 'select' => 'index',
+ ],
+ ],
+ ],
+ 'logs' => [
'title' => 'mc_logs',
- 'areas' => array(
- 'modlog' => array(
+ 'areas' => [
+ 'modlog' => [
'label' => 'modlog_view',
'enabled' => true,
'function' => __NAMESPACE__ . '\\Logs::call',
'icon' => 'logs',
- ),
- 'warnings' => array(
+ ],
+ 'warnings' => [
'label' => 'mc_warnings',
'enabled' => true,
'function' => __NAMESPACE__ . '\\Warnings::call',
'icon' => 'warning',
- 'subsections' => array(
- 'log' => array(
+ 'subsections' => [
+ 'log' => [
'label' => 'mc_warning_log',
- 'permission' => array('view_warning_any', 'moderate_forum'),
- ),
- 'templates' => array(
+ 'permission' => ['view_warning_any', 'moderate_forum'],
+ ],
+ 'templates' => [
'label' => 'mc_warning_templates',
'permission' => 'issue_warning',
- ),
- ),
- ),
- ),
- ),
- 'posts' => array(
+ ],
+ ],
+ ],
+ ],
+ ],
+ 'posts' => [
'title' => 'mc_posts',
'enabled' => true,
- 'areas' => array(
- 'postmod' => array(
+ 'areas' => [
+ 'postmod' => [
'label' => 'mc_unapproved_posts',
'enabled' => true,
'function' => __NAMESPACE__ . '\\Posts::call',
'icon' => 'posts',
'custom_url' => '{scripturl}?action=moderate;area=postmod',
- 'subsections' => array(
- 'posts' => array(
+ 'subsections' => [
+ 'posts' => [
'label' => 'mc_unapproved_replies',
- ),
- 'topics' => array(
+ ],
+ 'topics' => [
'label' => 'mc_unapproved_topics',
- ),
- ),
- ),
- 'attachmod' => array(
+ ],
+ ],
+ ],
+ 'attachmod' => [
'label' => 'mc_unapproved_attachments',
'enabled' => true,
'function' => __NAMESPACE__ . '\\Posts::call',
'icon' => 'post_moderation_attach',
'custom_url' => '{scripturl}?action=moderate;area=attachmod;sa=attachments',
- ),
- 'reportedposts' => array(
+ ],
+ 'reportedposts' => [
'label' => 'mc_reported_posts',
'enabled' => true,
'function' => __NAMESPACE__ . '\\ReportedContent::call',
'icon' => 'reports',
- 'subsections' => array(
- 'show' => array(
+ 'subsections' => [
+ 'show' => [
'label' => 'mc_reportedp_active',
- ),
- 'closed' => array(
+ ],
+ 'closed' => [
'label' => 'mc_reportedp_closed',
- ),
- ),
- ),
- ),
- ),
- 'groups' => array(
+ ],
+ ],
+ ],
+ ],
+ ],
+ 'groups' => [
'title' => 'mc_groups',
'enabled' => true,
- 'areas' => array(
- 'groups' => array(
+ 'areas' => [
+ 'groups' => [
'label' => 'mc_group_requests',
'function' => '\\SMF\\Actions\\Groups::call',
'icon' => 'members_request',
'custom_url' => '{scripturl}?action=moderate;area=groups;sa=requests',
- ),
- 'viewgroups' => array(
+ ],
+ 'viewgroups' => [
'label' => 'mc_view_groups',
'function' => '\\SMF\\Actions\\Groups::call',
'icon' => 'membergroups',
- ),
- ),
- ),
- 'members' => array(
+ ],
+ ],
+ ],
+ 'members' => [
'title' => 'mc_members',
'enabled' => true,
- 'areas' => array(
- 'userwatch' => array(
+ 'areas' => [
+ 'userwatch' => [
'label' => 'mc_watched_users_title',
'enabled' => true,
'function' => __NAMESPACE__ . '\\WatchedUsers::call',
'icon' => 'members_watched',
- 'subsections' => array(
- 'member' => array(
+ 'subsections' => [
+ 'member' => [
'label' => 'mc_watched_users_member',
- ),
- 'post' => array(
+ ],
+ 'post' => [
'label' => 'mc_watched_users_post',
- ),
- ),
- ),
- 'reportedmembers' => array(
+ ],
+ ],
+ ],
+ 'reportedmembers' => [
'label' => 'mc_reported_members_title',
'enabled' => true,
'function' => __NAMESPACE__ . '\\ReportedContent::call',
'icon' => 'members_watched',
- 'subsections' => array(
- 'open' => array(
+ 'subsections' => [
+ 'open' => [
'label' => 'mc_reportedp_active',
- ),
- 'closed' => array(
+ ],
+ 'closed' => [
'label' => 'mc_reportedp_closed',
- ),
- ),
- ),
- ),
- )
- );
+ ],
+ ],
+ ],
+ ],
+ ],
+ ];
/****************************
* Internal static properties
@@ -242,15 +241,15 @@ public function execute(): void
{
$this->createMenu();
- if (isset(Menu::$loaded['moderate']->include_data['file']))
- {
- require_once(Config::$sourcedir . '/' . Menu::$loaded['moderate']->include_data['file']);
+ if (isset(Menu::$loaded['moderate']->include_data['file'])) {
+ require_once Config::$sourcedir . '/' . Menu::$loaded['moderate']->include_data['file'];
}
- $call = method_exists($this, Menu::$loaded['moderate']->include_data['function']) ? array($this, Menu::$loaded['moderate']->include_data['function']) : Utils::getCallable(Menu::$loaded['moderate']->include_data['function']);
+ $call = method_exists($this, Menu::$loaded['moderate']->include_data['function']) ? [$this, Menu::$loaded['moderate']->include_data['function']] : Utils::getCallable(Menu::$loaded['moderate']->include_data['function']);
- if (!empty($call))
+ if (!empty($call)) {
call_user_func($call);
+ }
}
/**
@@ -265,54 +264,53 @@ public function createMenu(): void
User::$me->validateSession('moderate');
// I don't know where we're going - I don't know where we've been...
- $menuOptions = array(
+ $menuOptions = [
'action' => 'moderate',
'disable_url_session_check' => true,
- );
+ ];
$menu = new Menu($this->moderation_areas, $menuOptions);
// We got something - didn't we? DIDN'T WE!
- if (empty($menu->include_data))
+ if (empty($menu->include_data)) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Retain the ID information in case required by a subaction.
Utils::$context['moderation_menu_id'] = $menu->id;
Utils::$context['moderation_menu_name'] = $menu->name;
// @todo: html in here is not good
- $menu->tab_data = array(
+ $menu->tab_data = [
'title' => Lang::$txt['moderation_center'],
'help' => '',
'description' => '
' . Lang::$txt['hello_guest'] . ' ' . User::$me->name . '!
- ' . Lang::$txt['mc_description']
- );
+ ' . Lang::$txt['mc_description'],
+ ];
// What a pleasant shortcut - even tho we're not *really* on the admin screen who cares...
Utils::$context['admin_area'] = $menu->current_area;
// Build the link tree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=moderate',
'name' => Lang::$txt['moderation_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=moderate;area=' . $menu->current_area,
'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=moderate;area=' . $menu->current_area . ';sa=' . $menu->current_subsection,
'name' => $menu->include_data['subsections'][$menu->current_subsection]['label'],
- );
+ ];
}
}
@@ -327,8 +325,9 @@ public function createMenu(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -354,8 +353,9 @@ public static function call(): void
public static function checkAccessPermissions(): void
{
// No need to repeat these checks.
- if (self::$access_checked)
+ if (self::$access_checked) {
return;
+ }
Utils::$context['can_moderate_boards'] = User::$me->mod_cache['bq'] != '0=1';
Utils::$context['can_moderate_groups'] = User::$me->mod_cache['gq'] != '0=1';
@@ -363,8 +363,7 @@ public static function checkAccessPermissions(): void
Utils::$context['can_moderate_users'] = User::$me->allowedTo('moderate_forum');
// Everyone using this area must be allowed here!
- if (!Utils::$context['can_moderate_boards'] && !Utils::$context['can_moderate_groups'] && !Utils::$context['can_moderate_approvals'] && !Utils::$context['can_moderate_users'])
- {
+ if (!Utils::$context['can_moderate_boards'] && !Utils::$context['can_moderate_groups'] && !Utils::$context['can_moderate_approvals'] && !Utils::$context['can_moderate_users']) {
User::$me->isAllowedTo('access_mod_center');
}
@@ -380,12 +379,9 @@ public static function checkAccessPermissions(): void
*/
public static function ModerationMain(bool $dont_call = false): void
{
- if ($dont_call)
- {
+ if ($dont_call) {
self::load()->createMenu();
- }
- else
- {
+ } else {
self::call();
}
}
@@ -400,8 +396,9 @@ public static function ModerationMain(bool $dont_call = false): void
protected function __construct()
{
// Don't run this twice... and don't conflict with the admin bar.
- if (isset(Utils::$context['admin_area']))
+ if (isset(Utils::$context['admin_area'])) {
return;
+ }
self::checkAccessPermissions();
@@ -409,7 +406,7 @@ protected function __construct()
Lang::load('ModerationCenter');
Theme::loadTemplate(false, 'admin');
- 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) : [];
Utils::$context['robot_no_index'] = true;
$this->setModerationAreas();
@@ -423,16 +420,16 @@ protected function setModerationAreas(): void
// Finalize various string values.
array_walk_recursive(
$this->moderation_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,
- ));
- }
+ ]);
+ },
);
// Is moderation security enabled?
@@ -441,7 +438,7 @@ function(&$value, $key)
// Which logs should be enabled?
$this->moderation_areas['logs']['areas']['modlog']['enabled'] = !empty(Config::$modSettings['modlog_enabled']) && Utils::$context['can_moderate_boards'];
- $this->moderation_areas['logs']['areas']['warnings']['enabled'] = Config::$modSettings['warning_settings'][0] == 1 && User::$me->allowedTo(array('issue_warning', 'view_warning_any'));
+ $this->moderation_areas['logs']['areas']['warnings']['enabled'] = Config::$modSettings['warning_settings'][0] == 1 && User::$me->allowedTo(['issue_warning', 'view_warning_any']);
// Which parts of post moderation should be enabled?
$this->moderation_areas['posts']['enabled'] = Utils::$context['can_moderate_boards'] || Utils::$context['can_moderate_approvals'];
@@ -465,7 +462,8 @@ function(&$value, $key)
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Main::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Main::exportStatic')) {
Main::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Moderation/Posts.php b/Sources/Actions/Moderation/Posts.php
index cc3cf73a57..20150eaa91 100644
--- a/Sources/Actions/Moderation/Posts.php
+++ b/Sources/Actions/Moderation/Posts.php
@@ -13,13 +13,13 @@
namespace SMF\Actions\Moderation;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
use SMF\Attachment;
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\IntegrationHook;
use SMF\ItemList;
use SMF\Lang;
@@ -33,7 +33,6 @@
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Handles things related to post moderation.
@@ -47,12 +46,17 @@ class Posts implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'PostModerationMain',
- ),
- );
+ 'approveAllData' => 'approveAllData',
+ 'list_getUnapprovedAttachments' => 'list_getUnapprovedAttachments',
+ 'list_getNumUnapprovedAttachments' => 'list_getNumUnapprovedAttachments',
+ 'unapprovedPosts' => 'UnapprovedPosts',
+ 'unapprovedAttachments' => 'UnapprovedAttachments',
+ 'approveMessage' => 'ApproveMessage',
+ ],
+ ];
/*******************
* Public properties
@@ -75,12 +79,12 @@ class Posts implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'replies' => 'posts',
'topics' => 'posts',
'attachments' => 'attachments',
'approve' => 'approve',
- );
+ ];
/****************************
* Internal static properties
@@ -103,10 +107,11 @@ class Posts 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,97 +127,84 @@ public function posts(): void
// If we filtered by board remove ones outside of this board.
// @todo Put a message saying we're filtered?
- if (isset($_REQUEST['brd']))
- {
- $filter_board = array((int) $_REQUEST['brd']);
+ if (isset($_REQUEST['brd'])) {
+ $filter_board = [(int) $_REQUEST['brd']];
- $approve_boards = $approve_boards == array(0) ? $filter_board : array_intersect($approve_boards, $filter_board);
+ $approve_boards = $approve_boards == [0] ? $filter_board : array_intersect($approve_boards, $filter_board);
}
- if ($approve_boards == array(0))
- {
+ if ($approve_boards == [0]) {
$approve_query = '';
- }
- elseif (!empty($approve_boards))
- {
+ } elseif (!empty($approve_boards)) {
$approve_query = ' AND m.id_board IN (' . implode(',', $approve_boards) . ')';
}
// Nada, zip, etc...
- else
- {
+ else {
$approve_query = ' AND 1=0';
}
// We also need to know where we can delete topics and/or replies to.
- $boards_can = User::$me->boardsAllowedTo(array('remove_any', 'remove_own', 'delete_own', 'delete_any', 'delete_own_replies'), true, false);
+ $boards_can = User::$me->boardsAllowedTo(['remove_any', 'remove_own', 'delete_own', 'delete_any', 'delete_own_replies'], true, false);
- if (Utils::$context['current_view'] == 'topics')
- {
+ if (Utils::$context['current_view'] == 'topics') {
$delete_own_boards = $boards_can['remove_own'];
$delete_any_boards = $boards_can['remove_any'];
- $delete_own_replies = array();
- }
- else
- {
+ $delete_own_replies = [];
+ } else {
$delete_own_boards = $boards_can['delete_own'];
$delete_any_boards = $boards_can['delete_any'];
$delete_own_replies = $boards_can['delete_own_replies'];
}
- $toAction = array();
+ $toAction = [];
// Check if we have something to do?
- if (isset($_GET['approve']))
- {
+ if (isset($_GET['approve'])) {
$toAction[] = (int) $_GET['approve'];
}
// Just a deletion?
- elseif (isset($_GET['delete']))
- {
+ elseif (isset($_GET['delete'])) {
$toAction[] = (int) $_GET['delete'];
}
// Lots of approvals?
- elseif (isset($_POST['item']))
- {
- foreach ($_POST['item'] as $item)
+ elseif (isset($_POST['item'])) {
+ foreach ($_POST['item'] as $item) {
$toAction[] = (int) $item;
+ }
}
// What are we actually doing.
- if (isset($_GET['approve']) || (isset($_POST['do']) && $_POST['do'] == 'approve'))
- {
+ if (isset($_GET['approve']) || (isset($_POST['do']) && $_POST['do'] == 'approve')) {
$curAction = 'approve';
- }
- elseif (isset($_GET['delete']) || (isset($_POST['do']) && $_POST['do'] == 'delete'))
- {
+ } elseif (isset($_GET['delete']) || (isset($_POST['do']) && $_POST['do'] == 'delete')) {
$curAction = 'delete';
}
// Right, so we have something to do?
- if (!empty($toAction) && isset($curAction))
- {
+ if (!empty($toAction) && isset($curAction)) {
User::$me->checkSession('request');
// Handy shortcut.
$any_array = $curAction == 'approve' ? $approve_boards : $delete_any_boards;
// Now for each message work out whether it's actually a topic, and what board it's on.
- $request = Db::$db->query('', '
- SELECT m.id_msg, m.id_member, m.id_board, m.subject, t.id_topic, t.id_first_msg, t.id_member_started
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg, m.id_member, m.id_board, m.subject, t.id_topic, t.id_first_msg, t.id_member_started
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
WHERE m.id_msg IN ({array_int:message_list})
AND m.approved = {int:not_approved}
AND {query_see_message_board}',
- array(
+ [
'message_list' => $toAction,
'not_approved' => 0,
- )
+ ],
);
- $toAction = array();
- $details = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $toAction = [];
+ $details = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// If it's not within what our view is ignore it...
if (
(
@@ -223,30 +215,26 @@ public function posts(): void
$row['id_msg'] != $row['id_first_msg']
&& Utils::$context['current_view'] != 'replies'
)
- )
- {
+ ) {
continue;
}
$can_add = false;
// If we're approving this is simple.
- if ($curAction == 'approve' && ($any_array == array(0) || in_array($row['id_board'], $any_array)))
- {
+ if ($curAction == 'approve' && ($any_array == [0] || in_array($row['id_board'], $any_array))) {
$can_add = true;
}
// Delete requires more permission checks...
- elseif ($curAction == 'delete')
- {
+ elseif ($curAction == 'delete') {
// Own post is easy!
if (
$row['id_member'] == User::$me->id
&& (
- $delete_own_boards == array(0)
+ $delete_own_boards == [0]
|| in_array($row['id_board'], $delete_own_boards)
)
- )
- {
+ ) {
$can_add = true;
}
// Is it a reply to their own topic?
@@ -254,82 +242,77 @@ public function posts(): void
$row['id_member'] == $row['id_member_started']
&& $row['id_msg'] != $row['id_first_msg']
&& (
- $delete_own_replies == array(0)
+ $delete_own_replies == [0]
|| in_array($row['id_board'], $delete_own_replies)
)
- )
- {
+ ) {
$can_add = true;
}
// Someone elses?
elseif (
$row['id_member'] != User::$me->id
&& (
- $delete_any_boards == array(0)
+ $delete_any_boards == [0]
|| in_array($row['id_board'], $delete_any_boards)
)
- )
- {
+ ) {
$can_add = true;
}
}
- if ($can_add)
- {
+ if ($can_add) {
$anItem = Utils::$context['current_view'] == 'topics' ? $row['id_topic'] : $row['id_msg'];
$toAction[] = $anItem;
// All clear. What have we got now, what, what?
- $details[$anItem] = array();
- $details[$anItem]["subject"] = $row['subject'];
- $details[$anItem]["topic"] = $row['id_topic'];
- $details[$anItem]["member"] = (Utils::$context['current_view'] == 'topics') ? $row['id_member_started'] : $row['id_member'];
- $details[$anItem]["board"] = $row['id_board'];
+ $details[$anItem] = [];
+ $details[$anItem]['subject'] = $row['subject'];
+ $details[$anItem]['topic'] = $row['id_topic'];
+ $details[$anItem]['member'] = (Utils::$context['current_view'] == 'topics') ? $row['id_member_started'] : $row['id_member'];
+ $details[$anItem]['board'] = $row['id_board'];
}
}
Db::$db->free_result($request);
// If we have anything left we can actually do the approving (etc).
- if (!empty($toAction))
- {
- if ($curAction == 'approve')
- {
+ if (!empty($toAction)) {
+ if ($curAction == 'approve') {
approveMessages($toAction, $details, Utils::$context['current_view']);
- }
- else
- {
+ } else {
removeMessages($toAction, $details, Utils::$context['current_view']);
}
}
}
// How many unapproved posts are there?
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic AND t.id_first_msg != m.id_msg)
INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
WHERE m.approved = {int:not_approved}
AND {query_see_board}
' . $approve_query,
- array(
+ [
'not_approved' => 0,
- )
+ ],
);
list(Utils::$context['total_unapproved_posts']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// What about topics? Normally we'd use the table alias t for topics but lets use m so we don't have to redo our approve query.
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}topics AS m
WHERE m.approved = {int:not_approved}
AND {query_see_message_board}
' . $approve_query,
- array(
+ [
'not_approved' => 0,
- )
+ ],
);
list(Utils::$context['total_unapproved_topics']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -344,28 +327,28 @@ public function posts(): void
// We have enough to make some pretty tabs!
$menu = Menu::$loaded['moderate'];
- $menu->tab_data = array(
+ $menu->tab_data = [
'title' => Lang::$txt['mc_unapproved_posts'],
'help' => 'postmod',
'description' => Lang::$txt['mc_unapproved_posts_desc'],
- );
+ ];
// Update the tabs with the correct number of posts.
$menu->sections['posts']['areas']['postmod']['subsections']['posts']['label'] .= ' (' . Utils::$context['total_unapproved_posts'] . ')';
$menu->sections['posts']['areas']['postmod']['subsections']['topics']['label'] .= ' (' . Utils::$context['total_unapproved_topics'] . ')';
// If we are filtering some boards out then make sure to send that along with the links.
- if (isset($_REQUEST['brd']))
- {
+ if (isset($_REQUEST['brd'])) {
$menu->sections['posts']['areas']['postmod']['subsections']['posts']['add_params'] = ';brd=' . (int) $_REQUEST['brd'];
$menu->sections['posts']['areas']['postmod']['subsections']['topics']['add_params'] = ';brd=' . (int) $_REQUEST['brd'];
}
// Get all unapproved posts.
- Utils::$context['unapproved_items'] = array();
+ Utils::$context['unapproved_items'] = [];
- $request = Db::$db->query('', '
- SELECT m.id_msg, m.id_topic, m.id_board, m.subject, m.body, m.id_member,
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg, m.id_topic, m.id_board, m.subject, m.body, m.id_member,
COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.smileys_enabled,
t.id_member_started, t.id_first_msg, b.name AS board_name, c.id_cat, c.name AS cat_name
FROM {db_prefix}messages AS m
@@ -378,23 +361,22 @@ public function posts(): void
AND {query_see_board}
' . $approve_query . '
LIMIT {int:start}, {int:limit}',
- array(
+ [
'not_approved' => 0,
'start' => Utils::$context['start'],
'limit' => $limit,
- )
+ ],
);
- for ($i = 1; $row = Db::$db->fetch_assoc($request); $i++)
- {
+
+ for ($i = 1; $row = Db::$db->fetch_assoc($request); $i++) {
// Can delete is complicated, let's solve it first... is it their own post?
if (
$row['id_member'] == User::$me->id
&& (
- $delete_own_boards == array(0)
+ $delete_own_boards == [0]
|| in_array($row['id_board'], $delete_own_boards)
)
- )
- {
+ ) {
$can_delete = true;
}
// Is it a reply to their own topic?
@@ -402,30 +384,26 @@ public function posts(): void
$row['id_member'] == $row['id_member_started']
&& $row['id_msg'] != $row['id_first_msg']
&& (
- $delete_own_replies == array(0)
+ $delete_own_replies == [0]
|| in_array($row['id_board'], $delete_own_replies)
)
- )
- {
+ ) {
$can_delete = true;
}
// Someone elses?
elseif (
$row['id_member'] != User::$me->id
&& (
- $delete_any_boards == array(0)
+ $delete_any_boards == [0]
|| in_array($row['id_board'], $delete_any_boards)
)
- )
- {
+ ) {
$can_delete = true;
- }
- else
- {
+ } else {
$can_delete = false;
}
- Utils::$context['unapproved_items'][] = array(
+ Utils::$context['unapproved_items'][] = [
'id' => $row['id_msg'],
'counter' => Utils::$context['start'] + $i,
'href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
@@ -433,27 +411,27 @@ public function posts(): void
'subject' => $row['subject'],
'body' => BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], $row['id_msg']),
'time' => Time::create('@' . $row['poster_time'])->format(),
- 'poster' => array(
+ 'poster' => [
'id' => $row['id_member'],
'name' => $row['poster_name'],
'link' => $row['id_member'] ? '' . $row['poster_name'] . '' : $row['poster_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- ),
- 'topic' => array(
+ ],
+ 'topic' => [
'id' => $row['id_topic'],
- ),
- 'board' => array(
+ ],
+ 'board' => [
'id' => $row['id_board'],
'name' => $row['board_name'],
'link' => '' . $row['board_name'] . '',
- ),
- 'category' => array(
+ ],
+ 'category' => [
'id' => $row['id_cat'],
'name' => $row['cat_name'],
'link' => '' . $row['cat_name'] . '',
- ),
+ ],
'can_delete' => $can_delete,
- );
+ ];
}
Db::$db->free_result($request);
@@ -470,54 +448,42 @@ public function attachments(): void
// Once again, permissions are king!
$approve_boards = User::$me->boardsAllowedTo('approve_posts');
- if ($approve_boards == array(0))
- {
+ if ($approve_boards == [0]) {
$approve_query = '';
- }
- elseif (!empty($approve_boards))
- {
+ } elseif (!empty($approve_boards)) {
$approve_query = ' AND m.id_board IN (' . implode(',', $approve_boards) . ')';
- }
- else
- {
+ } else {
$approve_query = ' AND 1=0';
}
// Get together the array of things to act on, if any.
- $attachments = array();
+ $attachments = [];
- if (isset($_GET['approve']))
- {
+ if (isset($_GET['approve'])) {
$attachments[] = (int) $_GET['approve'];
- }
- elseif (isset($_GET['delete']))
- {
+ } elseif (isset($_GET['delete'])) {
$attachments[] = (int) $_GET['delete'];
- }
- elseif (isset($_POST['item']))
- {
- foreach ($_POST['item'] as $item)
+ } elseif (isset($_POST['item'])) {
+ foreach ($_POST['item'] as $item) {
$attachments[] = (int) $item;
+ }
}
// Are we approving or deleting?
- if (isset($_GET['approve']) || (isset($_POST['do']) && $_POST['do'] == 'approve'))
- {
+ if (isset($_GET['approve']) || (isset($_POST['do']) && $_POST['do'] == 'approve')) {
$curAction = 'approve';
- }
- elseif (isset($_GET['delete']) || (isset($_POST['do']) && $_POST['do'] == 'delete'))
- {
+ } elseif (isset($_GET['delete']) || (isset($_POST['do']) && $_POST['do'] == 'delete')) {
$curAction = 'delete';
}
// Something to do, let's do it!
- if (!empty($attachments) && isset($curAction))
- {
+ if (!empty($attachments) && isset($curAction)) {
User::$me->checkSession('request');
// Confirm the attachments are eligible for changing!
- $request = Db::$db->query('', '
- SELECT a.id_attach
+ $request = Db::$db->query(
+ '',
+ 'SELECT a.id_attach
FROM {db_prefix}attachments AS a
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
WHERE a.id_attach IN ({array_int:attachments})
@@ -525,152 +491,146 @@ public function attachments(): void
AND a.attachment_type = {int:attachment_type}
AND {query_see_message_board}
' . $approve_query,
- array(
+ [
'attachments' => $attachments,
'not_approved' => 0,
'attachment_type' => 0,
- )
+ ],
);
- $attachments = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $attachments = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$attachments[] = $row['id_attach'];
}
Db::$db->free_result($request);
// Assuming it wasn't all like, proper illegal, we can do the approving.
- if (!empty($attachments))
- {
- if ($curAction == 'approve')
- {
+ if (!empty($attachments)) {
+ if ($curAction == 'approve') {
Attachment::approve($attachments);
- }
- else
- {
- Attachment::remove(array('id_attach' => $attachments, 'do_logging' => true));
+ } else {
+ Attachment::remove(['id_attach' => $attachments, 'do_logging' => true]);
}
}
}
- $listOptions = array(
+ $listOptions = [
'id' => 'mc_unapproved_attach',
'width' => '100%',
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['mc_unapproved_attachments_none_found'],
'base_href' => Config::$scripturl . '?action=moderate;area=attachmod;sa=attachments',
'default_sort_col' => 'attach_name',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getUnapprovedAttachments',
- 'params' => array(
+ 'params' => [
$approve_query,
- ),
- ),
- 'get_count' => array(
+ ],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getNumUnapprovedAttachments',
- 'params' => array(
+ 'params' => [
$approve_query,
- ),
- ),
- 'columns' => array(
- 'attach_name' => array(
- 'header' => array(
+ ],
+ ],
+ 'columns' => [
+ 'attach_name' => [
+ 'header' => [
'value' => Lang::$txt['mc_unapproved_attach_name'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'filename',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'a.filename',
'reverse' => 'a.filename DESC',
- ),
- ),
- 'attach_size' => array(
- 'header' => array(
+ ],
+ ],
+ 'attach_size' => [
+ 'header' => [
'value' => Lang::$txt['mc_unapproved_attach_size'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'size',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'a.size',
'reverse' => 'a.size DESC',
- ),
- ),
- 'attach_poster' => array(
- 'header' => array(
+ ],
+ ],
+ 'attach_poster' => [
+ 'header' => [
'value' => Lang::$txt['mc_unapproved_attach_poster'],
- ),
- 'data' => array(
- 'function' => function($data)
- {
+ ],
+ 'data' => [
+ 'function' => function ($data) {
return $data['poster']['link'];
},
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'm.id_member',
'reverse' => 'm.id_member DESC',
- ),
- ),
- 'date' => array(
- 'header' => array(
+ ],
+ ],
+ 'date' => [
+ 'header' => [
'value' => Lang::$txt['date'],
'style' => 'width: 18%;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
'class' => 'smalltext',
'style' => 'white-space:nowrap;',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'm.poster_time',
'reverse' => 'm.poster_time DESC',
- ),
- ),
- 'message' => array(
- 'header' => array(
+ ],
+ ],
+ 'message' => [
+ 'header' => [
'value' => Lang::$txt['post'],
- ),
- 'data' => array(
- 'function' => function($data)
- {
+ ],
+ 'data' => [
+ 'function' => function ($data) {
return '' . Utils::shorten($data['message']['subject'], 20) . '';
},
'class' => 'smalltext',
'style' => 'width:15em;',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'm.subject',
'reverse' => 'm.subject DESC',
- ),
- ),
- 'action' => array(
- 'header' => array(
+ ],
+ ],
+ 'action' => [
+ 'header' => [
'value' => '',
'style' => 'width: 4%;',
'class' => 'centercol',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => '',
- 'params' => array(
+ 'params' => [
'id' => false,
- ),
- ),
+ ],
+ ],
'class' => 'centercol',
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . '?action=moderate;area=attachmod;sa=attachments',
'include_sort' => true,
'include_start' => true,
- 'hidden_fields' => array(
+ 'hidden_fields' => [
Utils::$context['session_var'] => Utils::$context['session_id'],
- ),
+ ],
'token' => 'mod-ap',
- ),
- 'additional_rows' => array(
- array(
+ ],
+ 'additional_rows' => [
+ [
'position' => 'bottom_of_list',
'value' => '
',
'class' => 'floatright',
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the request list.
SecurityToken::create('mod-ap');
@@ -692,11 +652,11 @@ public function attachments(): void
Utils::$context['sub_template'] = 'show_list';
Utils::$context['default_list'] = 'mc_unapproved_attach';
- Menu::$loaded['moderate']->tab_data = array(
+ Menu::$loaded['moderate']->tab_data = [
'title' => Lang::$txt['mc_unapproved_attachments'],
'help' => '',
- 'description' => Lang::$txt['mc_unapproved_attachments_desc']
- );
+ 'description' => Lang::$txt['mc_unapproved_attachments_desc'],
+ ];
}
/**
@@ -710,38 +670,34 @@ public function approve(): void
User::$me->isAllowedTo('approve_posts');
- $request = Db::$db->query('', '
- SELECT t.id_member_started, t.id_first_msg, m.id_member, m.subject, m.approved
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_member_started, t.id_first_msg, m.id_member, m.subject, m.approved
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})
WHERE m.id_msg = {int:id_msg}
AND m.id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
'id_msg' => $_REQUEST['msg'],
- )
+ ],
);
list($starter, $first_msg, $poster, $subject, $approved) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// If it's the first in a topic then the whole topic gets approved!
- if ($first_msg == $_REQUEST['msg'])
- {
+ if ($first_msg == $_REQUEST['msg']) {
Topic::approve(Topic::$topic_id, !$approved);
- if ($starter != User::$me->id)
- {
- Logging::logAction(($approved ? 'un' : '') . 'approve_topic', array('topic' => Topic::$topic_id, 'subject' => $subject, 'member' => $starter, 'board' => Board::$info->id));
+ if ($starter != User::$me->id) {
+ Logging::logAction(($approved ? 'un' : '') . 'approve_topic', ['topic' => Topic::$topic_id, 'subject' => $subject, 'member' => $starter, 'board' => Board::$info->id]);
}
- }
- else
- {
+ } else {
Msg::approve($_REQUEST['msg'], !$approved);
- if ($poster != User::$me->id)
- {
- Logging::logAction(($approved ? 'un' : '') . 'approve', array('topic' => Topic::$topic_id, 'subject' => $subject, 'member' => $poster, 'board' => Board::$info->id));
+ if ($poster != User::$me->id) {
+ Logging::logAction(($approved ? 'un' : '') . 'approve', ['topic' => Topic::$topic_id, 'subject' => $subject, 'member' => $poster, 'board' => Board::$info->id]);
}
}
@@ -759,8 +715,9 @@ public function approve(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -779,44 +736,48 @@ public static function call(): void
public static function approveAllData(): void
{
// Start with messages and topics.
- $msgs = array();
+ $msgs = [];
- $request = Db::$db->query('', '
- SELECT id_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_msg
FROM {db_prefix}messages
WHERE approved = {int:not_approved}',
- array(
+ [
'not_approved' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_row($request))
- {
+
+ while ($row = Db::$db->fetch_row($request)) {
$msgs[] = $row[0];
}
Db::$db->free_result($request);
- if (!empty($msgs))
+ if (!empty($msgs)) {
Msg::approve($msgs);
+ }
// Now do attachments
- $attachments = array();
+ $attachments = [];
- $request = Db::$db->query('', '
- SELECT id_attach
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_attach
FROM {db_prefix}attachments
WHERE approved = {int:not_approved}',
- array(
+ [
'not_approved' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_row($request))
- {
+
+ while ($row = Db::$db->fetch_row($request)) {
$attachments[] = $row[0];
}
Db::$db->free_result($request);
- if (!empty($attachments))
+ if (!empty($attachments)) {
Attachment::approve($attachments);
+ }
}
/**
@@ -832,10 +793,11 @@ public static function approveAllData(): void
public static function list_getUnapprovedAttachments($start, $items_per_page, $sort, $approve_query): array
{
// Get all unapproved attachments.
- $unapproved_items = array();
+ $unapproved_items = [];
- $request = Db::$db->query('', '
- SELECT a.id_attach, a.filename, a.size, m.id_msg, m.id_topic, m.id_board, m.subject, m.body, m.id_member,
+ $request = Db::$db->query(
+ '',
+ 'SELECT a.id_attach, a.filename, a.size, m.id_msg, m.id_topic, m.id_board, m.subject, m.body, m.id_member,
COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time,
t.id_member_started, t.id_first_msg, b.name AS board_name, c.id_cat, c.name AS cat_name
FROM {db_prefix}attachments AS a
@@ -850,47 +812,47 @@ public static function list_getUnapprovedAttachments($start, $items_per_page, $s
{raw:approve_query}
ORDER BY {raw:sort}
LIMIT {int:start}, {int:items_per_page}',
- array(
+ [
'not_approved' => 0,
'attachment_type' => 0,
'start' => $start,
'sort' => $sort,
'items_per_page' => $items_per_page,
'approve_query' => $approve_query,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $unapproved_items[] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $unapproved_items[] = [
'id' => $row['id_attach'],
'filename' => $row['filename'],
'size' => round($row['size'] / 1024, 2),
'time' => Time::create('@' . $row['poster_time'])->format(),
- 'poster' => array(
+ 'poster' => [
'id' => $row['id_member'],
'name' => $row['poster_name'],
'link' => $row['id_member'] ? '' . $row['poster_name'] . '' : $row['poster_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- ),
- 'message' => array(
+ ],
+ 'message' => [
'id' => $row['id_msg'],
'subject' => $row['subject'],
'body' => BBCodeParser::load()->parse($row['body']),
'time' => Time::create('@' . $row['poster_time'])->format(),
'href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
- ),
- 'topic' => array(
+ ],
+ 'topic' => [
'id' => $row['id_topic'],
- ),
- 'board' => array(
+ ],
+ 'board' => [
'id' => $row['id_board'],
'name' => $row['board_name'],
- ),
- 'category' => array(
+ ],
+ 'category' => [
'id' => $row['id_cat'],
'name' => $row['cat_name'],
- ),
- );
+ ],
+ ];
}
Db::$db->free_result($request);
@@ -907,18 +869,19 @@ public static function list_getUnapprovedAttachments($start, $items_per_page, $s
public static function list_getNumUnapprovedAttachments($approve_query): int
{
// How many unapproved attachments in total?
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}attachments AS a
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
WHERE a.approved = {int:not_approved}
AND a.attachment_type = {int:attachment_type}
AND {query_see_message_board}
' . $approve_query,
- array(
+ [
'not_approved' => 0,
'attachment_type' => 0,
- )
+ ],
);
list($total_unapproved_attachments) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -968,10 +931,11 @@ protected function __construct()
Lang::load('ModerationCenter');
Theme::loadTemplate('ModerationCenter');
- IntegrationHook::call('integrate_post_moderation', array(&self::$subactions));
+ IntegrationHook::call('integrate_post_moderation', [&self::$subactions]);
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
+ }
}
/**
@@ -983,24 +947,19 @@ protected function __construct()
*/
protected function approveMessages($messages, $messageDetails, $current_view = 'replies'): void
{
- if ($current_view == 'topics')
- {
+ if ($current_view == 'topics') {
Topic::approve($messages);
// and tell the world about it
- foreach ($messages as $topic)
- {
- Logging::logAction('approve_topic', array('topic' => $topic, 'subject' => $messageDetails[$topic]['subject'], 'member' => $messageDetails[$topic]['member'], 'board' => $messageDetails[$topic]['board']));
+ foreach ($messages as $topic) {
+ Logging::logAction('approve_topic', ['topic' => $topic, 'subject' => $messageDetails[$topic]['subject'], 'member' => $messageDetails[$topic]['member'], 'board' => $messageDetails[$topic]['board']]);
}
- }
- else
- {
+ } else {
Msg::approve($messages);
// and tell the world about it again
- foreach ($messages as $post)
- {
- Logging::logAction('approve', array('topic' => $messageDetails[$post]['topic'], 'subject' => $messageDetails[$post]['subject'], 'member' => $messageDetails[$post]['member'], 'board' => $messageDetails[$post]['board']));
+ foreach ($messages as $post) {
+ Logging::logAction('approve', ['topic' => $messageDetails[$post]['topic'], 'subject' => $messageDetails[$post]['subject'], 'member' => $messageDetails[$post]['member'], 'board' => $messageDetails[$post]['board']]);
}
}
}
@@ -1015,45 +974,41 @@ protected function approveMessages($messages, $messageDetails, $current_view = '
protected function removeMessages($messages, $messageDetails, $current_view = 'replies'): void
{
// @todo something's not right, Msg::remove() checks permissions, Topic::remove() doesn't
- if ($current_view == 'topics')
- {
+ if ($current_view == 'topics') {
Topic::remove($messages);
// and tell the world about it
- foreach ($messages as $topic)
- {
+ foreach ($messages as $topic) {
// Note, only log topic ID in native form if it's not gone forever.
$topic_key = empty(Config::$modSettings['recycle_enable']) || Config::$modSettings['recycle_board'] != $messageDetails[$topic]['board'] ? 'topic' : 'old_topic_id';
- Logging::logAction('remove', array(
+ Logging::logAction('remove', [
$topic_key => $topic,
'subject' => $messageDetails[$topic]['subject'],
'member' => $messageDetails[$topic]['member'],
'board' => $messageDetails[$topic]['board'],
- ));
+ ]);
}
- }
- else
- {
- foreach ($messages as $post)
- {
+ } else {
+ foreach ($messages as $post) {
Msg::remove($post);
$topic_key = empty(Config::$modSettings['recycle_enable']) || Config::$modSettings['recycle_board'] != $messageDetails[$post]['board'] ? 'topic' : 'old_topic_id';
- Logging::logAction('delete', array(
+ Logging::logAction('delete', [
$topic_key => $messageDetails[$post]['topic'],
'subject' => $messageDetails[$post]['subject'],
'member' => $messageDetails[$post]['member'],
'board' => $messageDetails[$post]['board'],
- ));
+ ]);
}
}
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Posts::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Posts::exportStatic')) {
Posts::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Moderation/ReportedContent.php b/Sources/Actions/Moderation/ReportedContent.php
index c98534aad0..27239513b7 100644
--- a/Sources/Actions/Moderation/ReportedContent.php
+++ b/Sources/Actions/Moderation/ReportedContent.php
@@ -13,12 +13,12 @@
namespace SMF\Actions\Moderation;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
use SMF\Alert;
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\IP;
@@ -32,7 +32,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Handles reported members and posts, as well as moderation comments.
@@ -46,12 +45,18 @@ class ReportedContent implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ReportedContent',
- ),
- );
+ 'recountOpenReports' => 'recountOpenReports',
+ 'showReports' => 'ShowReports',
+ 'showClosedReports' => 'ShowClosedReports',
+ 'reportDetails' => 'ReportDetails',
+ 'handleReport' => 'HandleReport',
+ 'handleComment' => 'HandleComment',
+ 'editComment' => 'EditComment',
+ ],
+ ];
/*******************
* Public properties
@@ -81,24 +86,24 @@ class ReportedContent implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'show' => 'show',
'closed' => 'showClosed',
'details' => 'details',
'handle' => 'setState',
'handlecomment' => 'comment',
'editcomment' => 'modifyComment',
- );
+ ];
/**
* @var array
*
* Supported report types
*/
- public static array $types = array(
+ public static array $types = [
'posts',
'members',
- );
+ ];
/*********************
* Internal properties
@@ -109,7 +114,7 @@ class ReportedContent implements ActionInterface
*
* Boards where the current user can remove any message.
*/
- protected array $remove_any_boards = array();
+ protected array $remove_any_boards = [];
/**
* @var bool
@@ -139,10 +144,11 @@ class ReportedContent 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);
+ }
}
/**
@@ -168,19 +174,20 @@ public function show(): void
Utils::$context['reports'] = $this->getReports(Utils::$context['view_closed']);
// Are we closing multiple reports?
- if (isset($_POST['close']) && isset($_POST['close_selected']))
- {
+ if (isset($_POST['close'], $_POST['close_selected'])) {
User::$me->checkSession('post');
SecurityToken::validate('mod-report-close-all');
// All the ones to update...
- $toClose = array();
+ $toClose = [];
- foreach ($_POST['close'] as $rid)
+ foreach ($_POST['close'] as $rid) {
$toClose[] = (int) $rid;
+ }
- if (!empty($toClose))
+ if (!empty($toClose)) {
$this->updateReport('closed', 1, $toClose);
+ }
// Set the confirmation message.
$_SESSION['rc_confirmation'] = 'close_all';
@@ -232,8 +239,9 @@ public function showClosed(): void
public function details(): void
{
// Have to at least give us something to work with.
- if (empty($_REQUEST['rid']))
+ if (empty($_REQUEST['rid'])) {
ErrorHandler::fatalLang('mc_reportedp_none_found');
+ }
// Integers only please
$report_id = (int) $_REQUEST['rid'];
@@ -241,189 +249,183 @@ public function details(): void
// Get the report details.
$report = $this->getReportDetails($report_id);
- if (empty($report))
+ if (empty($report)) {
ErrorHandler::fatalLang('mc_no_modreport_found', false);
+ }
// Build the report data - basic details first, then extra stuff based on the type
- Utils::$context['report'] = array(
+ Utils::$context['report'] = [
'id' => $report['id_report'],
'report_href' => Config::$scripturl . '?action=moderate;area=reported' . $this->type . ';rid=' . $report['id_report'],
- 'comments' => array(),
- 'mod_comments' => array(),
+ 'comments' => [],
+ 'mod_comments' => [],
'time_started' => Time::create('@' . $report['time_started'])->format(),
'last_updated' => Time::create('@' . $report['time_updated'])->format(),
'num_reports' => $report['num_reports'],
'closed' => $report['closed'],
- 'ignore' => $report['ignore_all']
- );
+ 'ignore' => $report['ignore_all'],
+ ];
// Different reports have different "extra" data attached to them
- if ($this->type == 'members')
- {
- $extraDetails = array(
- 'user' => array(
+ if ($this->type == 'members') {
+ $extraDetails = [
+ 'user' => [
'id' => $report['id_user'],
'name' => $report['user_name'],
'link' => $report['id_user'] ? '' . $report['user_name'] . '' : $report['user_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $report['id_user'],
- ),
- );
- }
- else
- {
- $extraDetails = array(
+ ],
+ ];
+ } else {
+ $extraDetails = [
'topic_id' => $report['id_topic'],
'board_id' => $report['id_board'],
'message_id' => $report['id_msg'],
'message_href' => Config::$scripturl . '?msg=' . $report['id_msg'],
'message_link' => '' . $report['subject'] . '',
- 'author' => array(
+ 'author' => [
'id' => $report['id_author'],
'name' => $report['author_name'],
'link' => $report['id_author'] ? '' . $report['author_name'] . '' : $report['author_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $report['id_author'],
- ),
+ ],
'subject' => $report['subject'],
'body' => BBCodeParser::load()->parse($report['body']),
- );
+ ];
}
Utils::$context['report'] = array_merge(Utils::$context['report'], $extraDetails);
$reportComments = $this->getReportComments($report_id);
- if (!empty($reportComments))
+ if (!empty($reportComments)) {
Utils::$context['report'] = array_merge(Utils::$context['report'], $reportComments);
+ }
// What have the other moderators done to this message?
// Parameters are slightly different depending on what we're doing here...
- if ($this->type == 'members')
- {
+ if ($this->type == 'members') {
// Find their ID in the serialized action string...
$user_id_length = strlen((string) Utils::$context['report']['user']['id']);
$member = 's:6:"member";s:' . $user_id_length . ':"' . Utils::$context['report']['user']['id'] . '";}';
- $params = array(
+ $params = [
'lm.extra LIKE {raw:member}
AND lm.action LIKE {raw:report}',
- array('member' => '\'%' . $member . '\'', 'report' => '\'%_user_report\''),
+ ['member' => '\'%' . $member . '\'', 'report' => '\'%_user_report\''],
1,
true,
- );
- }
- else
- {
- $params = array(
+ ];
+ } else {
+ $params = [
'lm.id_topic = {int:id_topic}
AND lm.id_board != {int:not_a_reported_post}',
- array('id_topic' => Utils::$context['report']['topic_id'], 'not_a_reported_post' => 0),
+ ['id_topic' => Utils::$context['report']['topic_id'], 'not_a_reported_post' => 0],
1,
- );
+ ];
}
Lang::load('Modlog');
// This is all the information from the moderation log.
- $listOptions = array(
+ $listOptions = [
'id' => 'moderation_actions_list',
'title' => Lang::$txt['mc_modreport_modactions'],
'items_per_page' => 15,
'no_items_label' => Lang::$txt['modlog_no_entries_found'],
'base_href' => Config::$scripturl . '?action=moderate;area=reported' . $this->type . ';sa=details;rid=' . Utils::$context['report']['id'],
'default_sort_col' => 'time',
- 'get_items' => array(
+ 'get_items' => [
'function' => __NAMESPACE__ . '\\Logs::list_getModLogEntries',
'params' => $params,
- ),
- 'get_count' => array(
+ ],
+ 'get_count' => [
'function' => __NAMESPACE__ . '\\Logs::list_getModLogEntryCount',
'params' => $params,
- ),
+ ],
// This assumes we are viewing by user.
- 'columns' => array(
- 'action' => array(
- 'header' => array(
+ 'columns' => [
+ 'action' => [
+ 'header' => [
'value' => Lang::$txt['modlog_action'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'action_text',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lm.action',
'reverse' => 'lm.action DESC',
- ),
- ),
- 'time' => array(
- 'header' => array(
+ ],
+ ],
+ 'time' => [
+ 'header' => [
'value' => Lang::$txt['modlog_date'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lm.log_time',
'reverse' => 'lm.log_time DESC',
- ),
- ),
- 'moderator' => array(
- 'header' => array(
+ ],
+ ],
+ 'moderator' => [
+ 'header' => [
'value' => Lang::$txt['modlog_member'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'moderator_link',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'mem.real_name',
'reverse' => 'mem.real_name DESC',
- ),
- ),
- 'position' => array(
- 'header' => array(
+ ],
+ ],
+ 'position' => [
+ 'header' => [
'value' => Lang::$txt['modlog_position'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'position',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'mg.group_name',
'reverse' => 'mg.group_name DESC',
- ),
- ),
- 'ip' => array(
- 'header' => array(
+ ],
+ ],
+ 'ip' => [
+ 'header' => [
'value' => Lang::$txt['modlog_ip'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'ip',
'class' => 'smalltext',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lm.ip',
'reverse' => 'lm.ip DESC',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
// Create the watched user list.
new ItemList($listOptions);
// Make sure to get the correct tab selected.
- if (Utils::$context['report']['closed'])
+ if (Utils::$context['report']['closed']) {
Menu::$loaded['moderate']->current_subsection = 'closed';
+ }
// Finally we are done :P
- if ($this->type == 'members')
- {
+ if ($this->type == 'members') {
Utils::$context['page_title'] = sprintf(Lang::$txt['mc_viewmemberreport'], Utils::$context['report']['user']['name']);
Utils::$context['sub_template'] = 'viewmemberreport';
- }
- else
- {
+ } else {
Utils::$context['page_title'] = sprintf(Lang::$txt['mc_viewmodreport'], Utils::$context['report']['subject'], Utils::$context['report']['author']['name']);
Utils::$context['sub_template'] = 'viewmodreport';
}
@@ -444,8 +446,9 @@ public function setState(): void
User::$me->checkSession('get');
// We need to do something!
- if (empty($_GET['rid']) && (!isset($_GET['ignore']) || !isset($_GET['closed'])))
+ if (empty($_GET['rid']) && (!isset($_GET['ignore']) || !isset($_GET['closed']))) {
ErrorHandler::fatalLang('mc_reportedp_none_found');
+ }
// What are we gonna do?
$action = isset($_GET['ignore']) ? 'ignore' : 'closed';
@@ -477,34 +480,34 @@ public function setState(): void
public function comment(): void
{
// The report ID is a must.
- if (empty($_REQUEST['rid']))
+ if (empty($_REQUEST['rid'])) {
ErrorHandler::fatalLang('mc_reportedp_none_found');
+ }
// Integers only please.
$report_id = (int) $_REQUEST['rid'];
// If they are adding a comment then... add a comment.
- if (isset($_POST['add_comment']) && !empty($_POST['mod_comment']))
- {
+ if (isset($_POST['add_comment']) && !empty($_POST['mod_comment'])) {
User::$me->checkSession();
SecurityToken::validate('mod-reportC-add');
$new_comment = trim(Utils::htmlspecialchars($_POST['mod_comment']));
- $this->saveModComment($report_id, array($report_id, $new_comment, time()));
+ $this->saveModComment($report_id, [$report_id, $new_comment, time()]);
// Everything went better than expected!
$_SESSION['rc_confirmation'] = 'message_saved';
}
// Deleting a comment?
- if (isset($_REQUEST['delete']) && isset($_REQUEST['mid']))
- {
+ if (isset($_REQUEST['delete'], $_REQUEST['mid'])) {
User::$me->checkSession('get');
SecurityToken::validate('mod-reportC-delete', 'get');
- if (empty($_REQUEST['mid']))
+ if (empty($_REQUEST['mid'])) {
ErrorHandler::fatalLang('mc_reportedp_comment_none_found');
+ }
$comment_id = (int) $_REQUEST['mid'];
@@ -512,12 +515,14 @@ public function comment(): void
$comment = $this->getCommentModDetails($comment_id);
// Perhaps somebody else already deleted this fine gem...
- if (empty($comment))
+ if (empty($comment)) {
ErrorHandler::fatalLang('report_action_message_delete_issue');
+ }
// Can you actually do this?
- if (!User::$me->allowedTo('admin_forum') && User::$me->id != $comment['id_member'])
+ if (!User::$me->allowedTo('admin_forum') && User::$me->id != $comment['id_member']) {
ErrorHandler::fatalLang('report_action_message_delete_cannot');
+ }
// All good!
$this->deleteModComment($comment_id);
@@ -540,11 +545,13 @@ public function modifyComment(): void
User::$me->checkSession(isset($_REQUEST['save']) ? 'post' : 'get');
// The report ID is a must.
- if (empty($_REQUEST['rid']))
+ if (empty($_REQUEST['rid'])) {
ErrorHandler::fatalLang('mc_reportedp_none_found');
+ }
- if (empty($_REQUEST['mid']))
+ if (empty($_REQUEST['mid'])) {
ErrorHandler::fatalLang('mc_reportedp_comment_none_found');
+ }
// Integers only please.
Utils::$context['report_id'] = (int) $_REQUEST['rid'];
@@ -552,24 +559,24 @@ public function modifyComment(): void
Utils::$context['comment'] = $this->getCommentModDetails(Utils::$context['comment_id']);
- if (empty(Utils::$context['comment']))
+ if (empty(Utils::$context['comment'])) {
ErrorHandler::fatalLang('mc_reportedp_comment_none_found');
+ }
// Set up the comforting bits...
Utils::$context['page_title'] = Lang::$txt['mc_reported_posts'];
Utils::$context['sub_template'] = 'edit_comment';
- if (isset($_REQUEST['save']) && isset($_POST['edit_comment']) && !empty($_POST['mod_comment']))
- {
+ if (isset($_REQUEST['save'], $_POST['edit_comment']) && !empty($_POST['mod_comment'])) {
SecurityToken::validate('mod-reportC-edit');
// Make sure there is some data to edit in the DB.
- if (empty(Utils::$context['comment']))
+ if (empty(Utils::$context['comment'])) {
ErrorHandler::fatalLang('report_action_message_edit_issue');
+ }
// So, you aren't neither an admin or the comment owner huh? that's too bad.
- if (!User::$me->allowedTo('admin_forum') && User::$me->id != Utils::$context['comment']['id_member'])
- {
+ if (!User::$me->allowedTo('admin_forum') && User::$me->id != Utils::$context['comment']['id_member']) {
ErrorHandler::fatalLang('report_action_message_edit_cannot');
}
@@ -597,8 +604,9 @@ public function modifyComment(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -621,30 +629,31 @@ public static function recountOpenReports(string $type): int
{
$bq = $type == 'members' ? '' : "\n\t\t\t\t" . 'AND ' . User::$me->mod_cache['bq'];
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_reported
WHERE closed = {int:not_closed}
AND ignore_all = {int:not_ignored}
AND id_board' . ($type == 'members' ? '' : '!') . '= {int:not_a_reported_post}'
. $bq,
- array(
+ [
'not_closed' => 0,
'not_ignored' => 0,
'not_a_reported_post' => 0,
- )
+ ],
);
list($open_reports) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
$arr = ($type == 'members' ? 'member_reports' : 'reports');
$_SESSION['rc'] = array_merge(
- !empty($_SESSION['rc']) ? $_SESSION['rc'] : array(),
- array(
+ !empty($_SESSION['rc']) ? $_SESSION['rc'] : [],
+ [
'id' => User::$me->id,
'time' => time(),
$arr => $open_reports,
- )
+ ],
);
return $open_reports;
@@ -723,8 +732,9 @@ protected function __construct()
// area=reported{type}
$this->type = substr($_GET['area'], 8);
- if (!in_array($this->type, self::$types))
+ if (!in_array($this->type, self::$types)) {
ErrorHandler::fatalLang('no_access', false);
+ }
Utils::$context['report_type'] = $this->type;
@@ -732,28 +742,30 @@ protected function __construct()
Theme::loadTemplate('ReportedContent');
// Do we need to show a confirmation message?
- Utils::$context['report_post_action'] = !empty($_SESSION['rc_confirmation']) ? $_SESSION['rc_confirmation'] : array();
+ Utils::$context['report_post_action'] = !empty($_SESSION['rc_confirmation']) ? $_SESSION['rc_confirmation'] : [];
unset($_SESSION['rc_confirmation']);
// Set up the comforting bits...
Utils::$context['page_title'] = Lang::$txt['mc_reported_' . $this->type];
// Put the open and closed options into tabs, because we can...
- Menu::$loaded['moderate']->tab_data = array(
+ Menu::$loaded['moderate']->tab_data = [
'title' => Lang::$txt['mc_reported_' . $this->type],
'help' => '',
'description' => Lang::$txt['mc_reported_' . $this->type . '_desc'],
- );
+ ];
// This comes under the umbrella of moderating posts.
- if ($this->type == 'members' || User::$me->mod_cache['bq'] == '0=1')
+ if ($this->type == 'members' || User::$me->mod_cache['bq'] == '0=1') {
User::$me->isAllowedTo('moderate_forum');
+ }
// Go ahead and add your own sub-actions.
- IntegrationHook::call('integrate_reported_' . $this->type, array(&self::$subactions));
+ IntegrationHook::call('integrate_reported_' . $this->type, [&self::$subactions]);
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
+ }
}
/**
@@ -768,106 +780,108 @@ protected function __construct()
protected function updateReport(string $action, int $value, int|array $report_id): void
{
// Don't bother.
- if (empty($action) || empty($report_id))
+ if (empty($action) || empty($report_id)) {
return;
+ }
// Add the "_all" thingy.
- if ($action == 'ignore')
+ if ($action == 'ignore') {
$action = 'ignore_all';
+ }
// We don't need the board query for reported members
- if ($this->type == 'members')
- {
+ if ($this->type == 'members') {
$board_query = '';
- }
- else
- {
+ } else {
$board_query = ' AND ' . User::$me->mod_cache['bq'];
}
// Update the report...
- Db::$db->query('', '
- UPDATE {db_prefix}log_reported
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_reported
SET {raw:action} = {string:value}
' . (is_array($report_id) ? 'WHERE id_report IN ({array_int:id_report})' : 'WHERE id_report = {int:id_report}') . '
' . $board_query,
- array(
+ [
'action' => $action,
'value' => $value,
'id_report' => $report_id,
- )
+ ],
);
// From now on, lets work with arrays, makes life easier.
$report_id = (array) $report_id;
// Set up the data for the log...
- $extra = array();
+ $extra = [];
- if ($this->type == 'posts')
- {
+ if ($this->type == 'posts') {
// Get the board, topic and message for this report
- $request = Db::$db->query('', '
- SELECT id_board, id_topic, id_msg, id_report
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board, id_topic, id_msg, id_report
FROM {db_prefix}log_reported
WHERE id_report IN ({array_int:id_report})',
- array(
+ [
'id_report' => $report_id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $extra[$row['id_report']] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $extra[$row['id_report']] = [
'report' => $row['id_report'],
'board' => $row['id_board'],
'message' => $row['id_msg'],
'topic' => $row['id_topic'],
- );
+ ];
}
Db::$db->free_result($request);
- }
- else
- {
- $request = Db::$db->query('', '
- SELECT id_report, id_member, membername
+ } else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_report, id_member, membername
FROM {db_prefix}log_reported
WHERE id_report IN ({array_int:id_report})',
- array(
+ [
'id_report' => $report_id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $extra[$row['id_report']] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $extra[$row['id_report']] = [
'report' => $row['id_report'],
'member' => $row['id_member'],
- );
+ ];
}
Db::$db->free_result($request);
}
// Back to "ignore".
- if ($action == 'ignore_all')
+ if ($action == 'ignore_all') {
$action = 'ignore';
+ }
$log_report = $action == 'ignore' ? (!empty($value) ? 'ignore' : 'unignore') : (!empty($value) ? 'close' : 'open');
- if ($this->type == 'members')
+ if ($this->type == 'members') {
$log_report .= '_user';
+ }
// See if any report alerts need to be cleaned up upon close/ignore
- if (in_array($log_report, array('close', 'ignore', 'close_user', 'ignore_user')))
+ if (in_array($log_report, ['close', 'ignore', 'close_user', 'ignore_user'])) {
$this->clearReportAlerts($log_report, $extra);
+ }
// Log this action.
- if (!empty($extra))
- {
- foreach ($extra as $report)
+ if (!empty($extra)) {
+ foreach ($extra as $report) {
Logging::logAction($log_report . '_report', $report);
+ }
}
// Time to update.
- Config::updateModSettings(array('last_mod_report_action' => time()));
+ Config::updateModSettings(['last_mod_report_action' => time()]);
self::recountOpenReports($this->type);
}
@@ -881,13 +895,10 @@ protected function clearReportAlerts(string $log_report, array $extra): void
{
// Setup the query, depending on if it's a member report or a msg report.
// In theory, these should be unique (reports for the same things get combined), but since $extra is an array, treat as an array.
- if (strpos($log_report, '_user') !== false)
- {
+ if (strpos($log_report, '_user') !== false) {
$content_ids = array_unique(array_column($extra, 'member'));
$content_type = 'member';
- }
- else
- {
+ } else {
$content_ids = array_unique(array_column($extra, 'message'));
$content_type = 'msg';
}
@@ -895,17 +906,17 @@ protected function clearReportAlerts(string $log_report, array $extra): void
// Check to see if there are unread alerts to flag as read...
// Might be multiple alerts, for multiple moderators...
Alert::markWhere(
- array(
+ [
'content_id IN ({array_int:content_ids})',
'content_type = {string:content_type}',
'content_action = {string:content_action}',
- ),
- array(
+ ],
+ [
'content_ids' => $content_ids,
'content_type' => $content_type,
'content_action' => 'report',
- ),
- true
+ ],
+ true,
);
}
@@ -918,18 +929,12 @@ protected function clearReportAlerts(string $log_report, array $extra): void
protected function countReports(int $closed = 0): int
{
// Skip entries with id_board = 0 if we're viewing member reports
- if ($this->type == 'members')
- {
+ if ($this->type == 'members') {
$and = 'lr.id_board = 0';
- }
- else
- {
- if (User::$me->mod_cache['bq'] == '1=1' || User::$me->mod_cache['bq'] == '0=1')
- {
+ } else {
+ if (User::$me->mod_cache['bq'] == '1=1' || User::$me->mod_cache['bq'] == '0=1') {
$bq = User::$me->mod_cache['bq'];
- }
- else
- {
+ } else {
$bq = 'lr.' . User::$me->mod_cache['bq'];
}
@@ -937,14 +942,15 @@ protected function countReports(int $closed = 0): int
}
// How many entries are we viewing?
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_reported AS lr
WHERE lr.closed = {int:view_closed}
AND ' . $and,
- array(
+ [
'view_closed' => $closed,
- )
+ ],
);
list($total_reports) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -961,16 +967,16 @@ protected function countReports(int $closed = 0): int
protected function getReports(int $closed = 0): array
{
// Lonely, standalone var.
- $reports = array();
+ $reports = [];
- $report_ids = array();
- $report_boards_ids = array();
+ $report_ids = [];
+ $report_boards_ids = [];
// By George, that means we are in a position to get the reports, jolly good.
- if ($this->type == 'members')
- {
- $request = Db::$db->query('', '
- SELECT lr.id_report, lr.id_member,
+ if ($this->type == 'members') {
+ $request = Db::$db->query(
+ '',
+ 'SELECT lr.id_report, lr.id_member,
lr.time_started, lr.time_updated, lr.num_reports, lr.closed, lr.ignore_all,
COALESCE(mem.real_name, lr.membername) AS user_name, COALESCE(mem.id_member, 0) AS id_user
FROM {db_prefix}log_reported AS lr
@@ -979,17 +985,16 @@ protected function getReports(int $closed = 0): array
AND lr.id_board = 0
ORDER BY lr.time_updated DESC
LIMIT {int:start}, {int:max}',
- array(
+ [
'view_closed' => $closed,
'start' => Utils::$context['start'],
'max' => 10,
- )
+ ],
);
- }
- else
- {
- $request = Db::$db->query('', '
- SELECT lr.id_report, lr.id_msg, lr.id_topic, lr.id_board, lr.id_member, lr.subject, lr.body,
+ } else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT lr.id_report, lr.id_msg, lr.id_topic, lr.id_board, lr.id_member, lr.subject, lr.body,
lr.time_started, lr.time_updated, lr.num_reports, lr.closed, lr.ignore_all,
COALESCE(mem.real_name, lr.membername) AS author_name, COALESCE(mem.id_member, 0) AS id_author
FROM {db_prefix}log_reported AS lr
@@ -999,57 +1004,54 @@ protected function getReports(int $closed = 0): array
AND ' . (User::$me->mod_cache['bq'] == '1=1' || User::$me->mod_cache['bq'] == '0=1' ? User::$me->mod_cache['bq'] : 'lr.' . User::$me->mod_cache['bq']) . '
ORDER BY lr.time_updated DESC
LIMIT {int:start}, {int:max}',
- array(
+ [
'view_closed' => (int) $closed,
'start' => Utils::$context['start'],
'max' => 10,
- )
+ ],
);
}
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$report_ids[] = $row['id_report'];
- $reports[$row['id_report']] = array(
+ $reports[$row['id_report']] = [
'id' => $row['id_report'],
'report_href' => Config::$scripturl . '?action=moderate;area=reported' . $this->type . ';sa=details;rid=' . $row['id_report'],
- 'comments' => array(),
+ 'comments' => [],
'time_started' => Time::create('@' . $row['time_started'])->format(),
'last_updated' => Time::create('@' . $row['time_updated'])->format(),
'num_reports' => $row['num_reports'],
'closed' => $row['closed'],
- 'ignore' => $row['ignore_all']
- );
+ 'ignore' => $row['ignore_all'],
+ ];
- if ($this->type == 'members')
- {
- $extraDetails = array(
- 'user' => array(
+ if ($this->type == 'members') {
+ $extraDetails = [
+ 'user' => [
'id' => $row['id_user'],
'name' => $row['user_name'],
'link' => $row['id_user'] ? '' . $row['user_name'] . '' : $row['user_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_user'],
- ),
- );
- }
- else
- {
+ ],
+ ];
+ } else {
$report_boards_ids[] = $row['id_board'];
- $extraDetails = array(
- 'topic' => array(
+ $extraDetails = [
+ 'topic' => [
'id' => $row['id_topic'],
'id_msg' => $row['id_msg'],
'id_board' => $row['id_board'],
'href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
- ),
- 'author' => array(
+ ],
+ 'author' => [
'id' => $row['id_author'],
'name' => $row['author_name'],
'link' => $row['id_author'] ? '' . $row['author_name'] . '' : $row['author_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_author'],
- ),
+ ],
'subject' => $row['subject'],
'body' => BBCodeParser::load()->parse($row['body']),
- );
+ ];
}
$reports[$row['id_report']] = array_merge($reports[$row['id_report']], $extraDetails);
@@ -1057,59 +1059,57 @@ protected function getReports(int $closed = 0): array
Db::$db->free_result($request);
// Get the names of boards those topics are in. Slightly faster this way.
- if (!empty($report_boards_ids))
- {
+ if (!empty($report_boards_ids)) {
$report_boards_ids = array_unique($report_boards_ids);
- $board_names = array();
- $request = Db::$db->query('', '
- SELECT id_board, name
+ $board_names = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board, name
FROM {db_prefix}boards
WHERE id_board IN ({array_int:boards})',
- array(
+ [
'boards' => $report_boards_ids,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$board_names[$row['id_board']] = $row['name'];
}
Db::$db->free_result($request);
- foreach ($reports as $id_report => $report)
- {
- if (!empty($board_names[$report['topic']['id_board']]))
- {
+ foreach ($reports as $id_report => $report) {
+ if (!empty($board_names[$report['topic']['id_board']])) {
$reports[$id_report]['topic']['board_name'] = $board_names[$report['topic']['id_board']];
}
}
}
// Now get all the people who reported it.
- if (!empty($report_ids))
- {
- $request = Db::$db->query('', '
- SELECT lrc.id_comment, lrc.id_report, lrc.time_sent, lrc.comment,
+ if (!empty($report_ids)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT lrc.id_comment, lrc.id_report, lrc.time_sent, lrc.comment,
COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lrc.membername) AS reporter
FROM {db_prefix}log_reported_comments AS lrc
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lrc.id_member)
WHERE lrc.id_report IN ({array_int:report_list})',
- array(
+ [
'report_list' => $report_ids,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $reports[$row['id_report']]['comments'][] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $reports[$row['id_report']]['comments'][] = [
'id' => $row['id_comment'],
'message' => $row['comment'],
'time' => Time::create('@' . $row['time_sent'])->format(),
- 'member' => array(
+ 'member' => [
'id' => $row['id_member'],
'name' => empty($row['reporter']) ? Lang::$txt['guest'] : $row['reporter'],
'link' => $row['id_member'] ? '' . $row['reporter'] . '' : (empty($row['reporter']) ? Lang::$txt['guest'] : $row['reporter']),
'href' => $row['id_member'] ? Config::$scripturl . '?action=profile;u=' . $row['id_member'] : '',
- ),
- );
+ ],
+ ];
}
Db::$db->free_result($request);
}
@@ -1129,14 +1129,15 @@ protected function getReports(int $closed = 0): array
*/
protected function getReportDetails(int $report_id): array
{
- if (empty($report_id))
- return array();
+ if (empty($report_id)) {
+ return [];
+ }
// We don't need all this info if we're only getting user info
- if ($this->type == 'members')
- {
- $request = Db::$db->query('', '
- SELECT lr.id_report, lr.id_member,
+ if ($this->type == 'members') {
+ $request = Db::$db->query(
+ '',
+ 'SELECT lr.id_report, lr.id_member,
lr.time_started, lr.time_updated, lr.num_reports, lr.closed, lr.ignore_all,
COALESCE(mem.real_name, lr.membername) AS user_name, COALESCE(mem.id_member, 0) AS id_user
FROM {db_prefix}log_reported AS lr
@@ -1144,16 +1145,15 @@ protected function getReportDetails(int $report_id): array
WHERE lr.id_report = {int:id_report}
AND lr.id_board = 0
LIMIT 1',
- array(
+ [
'id_report' => $report_id,
- )
+ ],
);
- }
- else
- {
+ } else {
// Get the report details, need this so we can limit access to a particular board.
- $request = Db::$db->query('', '
- SELECT lr.id_report, lr.id_msg, lr.id_topic, lr.id_board, lr.id_member, lr.subject, lr.body,
+ $request = Db::$db->query(
+ '',
+ 'SELECT lr.id_report, lr.id_msg, lr.id_topic, lr.id_board, lr.id_member, lr.subject, lr.body,
lr.time_started, lr.time_updated, lr.num_reports, lr.closed, lr.ignore_all,
COALESCE(mem.real_name, lr.membername) AS author_name, COALESCE(mem.id_member, 0) AS id_author
FROM {db_prefix}log_reported AS lr
@@ -1161,18 +1161,16 @@ protected function getReportDetails(int $report_id): array
WHERE lr.id_report = {int:id_report}
AND ' . (User::$me->mod_cache['bq'] == '1=1' || User::$me->mod_cache['bq'] == '0=1' ? User::$me->mod_cache['bq'] : 'lr.' . User::$me->mod_cache['bq']) . '
LIMIT 1',
- array(
+ [
'id_report' => $report_id,
- )
+ ],
);
}
+
// So did we find anything?
- if (!Db::$db->num_rows($request))
- {
- $row = array();
- }
- else
- {
+ if (!Db::$db->num_rows($request)) {
+ $row = [];
+ } else {
// Woohoo we found a report and they can see it!
$row = Db::$db->fetch_assoc($request);
}
@@ -1189,70 +1187,73 @@ protected function getReportDetails(int $report_id): array
*/
protected function getReportComments(int $report_id): array
{
- if (empty($report_id))
- return array();
+ if (empty($report_id)) {
+ return [];
+ }
- $report = array(
- 'comments' => array(),
- 'mod_comments' => array()
- );
+ $report = [
+ 'comments' => [],
+ 'mod_comments' => [],
+ ];
// So what bad things do the reporters have to say about it?
- $request = Db::$db->query('', '
- SELECT lrc.id_comment, lrc.id_report, lrc.time_sent, lrc.comment, lrc.member_ip,
+ $request = Db::$db->query(
+ '',
+ 'SELECT lrc.id_comment, lrc.id_report, lrc.time_sent, lrc.comment, lrc.member_ip,
COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lrc.membername) AS reporter
FROM {db_prefix}log_reported_comments AS lrc
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lrc.id_member)
WHERE lrc.id_report = {int:id_report}',
- array(
+ [
'id_report' => $report_id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$row['member_ip'] = new IP($row['member_ip']);
- $report['comments'][] = array(
+ $report['comments'][] = [
'id' => $row['id_comment'],
- 'message' => strtr($row['comment'], array("\n" => ' ')),
+ 'message' => strtr($row['comment'], ["\n" => ' ']),
'time' => Time::create('@' . $row['time_sent'])->format(),
- 'member' => array(
+ 'member' => [
'id' => $row['id_member'],
'name' => empty($row['reporter']) ? Lang::$txt['guest'] : $row['reporter'],
'link' => $row['id_member'] ? '' . $row['reporter'] . '' : (empty($row['reporter']) ? Lang::$txt['guest'] : $row['reporter']),
'href' => $row['id_member'] ? Config::$scripturl . '?action=profile;u=' . $row['id_member'] : '',
'ip' => !empty($row['member_ip']) && User::$me->allowedTo('moderate_forum') ? '' . $row['member_ip'] . '' : '',
- ),
- );
+ ],
+ ];
}
Db::$db->free_result($request);
// Hang about old chap, any comments from moderators on this one?
- $request = Db::$db->query('', '
- SELECT lc.id_comment, lc.id_notice, lc.log_time, lc.body,
+ $request = Db::$db->query(
+ '',
+ 'SELECT lc.id_comment, lc.id_notice, lc.log_time, lc.body,
COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS moderator
FROM {db_prefix}log_comments AS lc
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
WHERE lc.id_notice = {int:id_report}
AND lc.comment_type = {literal:reportc}',
- array(
+ [
'id_report' => $report_id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $report['mod_comments'][] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $report['mod_comments'][] = [
'id' => $row['id_comment'],
'message' => BBCodeParser::load()->parse($row['body']),
'time' => Time::create('@' . $row['log_time'])->format(),
'can_edit' => User::$me->allowedTo('admin_forum') || ((User::$me->id == $row['id_member'])),
- 'member' => array(
+ 'member' => [
'id' => $row['id_member'],
'name' => $row['moderator'],
'link' => $row['id_member'] ? '' . $row['moderator'] . '' : $row['moderator'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- ),
- );
+ ],
+ ];
}
Db::$db->free_result($request);
@@ -1270,24 +1271,25 @@ protected function getReportComments(int $report_id): array
*/
protected function getCommentModDetails(int $comment_id): array
{
- if (empty($comment_id))
- return array();
+ if (empty($comment_id)) {
+ return [];
+ }
- $request = Db::$db->query('', '
- SELECT id_comment, id_notice, log_time, body, id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_comment, id_notice, log_time, body, id_member
FROM {db_prefix}log_comments
WHERE id_comment = {int:id_comment}
AND comment_type = {literal:reportc}',
- array(
+ [
'id_comment' => $comment_id,
- )
+ ],
);
$comment = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
// Add the permission
- if (!empty($comment))
- {
+ if (!empty($comment)) {
$comment['can_edit'] = User::$me->allowedTo('admin_forum') || ((User::$me->id == $comment['id_member']));
}
@@ -1302,28 +1304,29 @@ protected function getCommentModDetails(int $comment_id): array
*/
protected function saveModComment(int $report_id, array $data): void
{
- if (empty($data))
+ if (empty($data)) {
return;
+ }
- $data = array_merge(array(User::$me->id, User::$me->name, 'reportc', ''), $data);
+ $data = array_merge([User::$me->id, User::$me->name, 'reportc', ''], $data);
- $last_comment = Db::$db->insert('',
+ $last_comment = Db::$db->insert(
+ '',
'{db_prefix}log_comments',
- array(
+ [
'id_member' => 'int', 'member_name' => 'string', 'comment_type' => 'string', 'recipient_name' => 'string',
'id_notice' => 'int', 'body' => 'string', 'log_time' => 'int',
- ),
+ ],
$data,
- array('id_comment'),
- 1
+ ['id_comment'],
+ 1,
);
$report = $this->getReportDetails($report_id);
- if ($this->type == 'members')
- {
+ if ($this->type == 'members') {
$prefix = 'Member';
- $data = array(
+ $data = [
'report_id' => $report_id,
'user_id' => $report['id_user'],
'user_name' => $report['user_name'],
@@ -1331,12 +1334,10 @@ protected function saveModComment(int $report_id, array $data): void
'sender_name' => User::$me->name,
'comment_id' => $last_comment,
'time' => time(),
- );
- }
- else
- {
+ ];
+ } else {
$prefix = 'Msg';
- $data = array(
+ $data = [
'report_id' => $report_id,
'comment_id' => $last_comment,
'msg_id' => $report['id_msg'],
@@ -1345,17 +1346,25 @@ protected function saveModComment(int $report_id, array $data): void
'sender_id' => User::$me->id,
'sender_name' => User::$me->name,
'time' => time(),
- );
+ ];
}
// And get ready to notify people.
- if (!empty($report))
- {
- Db::$db->insert('insert',
+ if (!empty($report)) {
+ Db::$db->insert(
+ 'insert',
'{db_prefix}background_tasks',
- array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
- array('$sourcedir/tasks/' . $prefix . 'ReportReply-Notify.php', 'SMF\Tasks\\' . $prefix . 'ReportReply_Notify', Utils::jsonEncode($data), 0),
- array('id_task')
+ [
+ 'task_class' => 'string',
+ 'task_data' => 'string',
+ 'claimed_time' => 'int',
+ ],
+ [
+ 'SMF\\Tasks\\' . $prefix . 'ReportReply_Notify',
+ Utils::jsonEncode($data),
+ 0,
+ ],
+ ['id_task'],
);
}
}
@@ -1368,17 +1377,19 @@ protected function saveModComment(int $report_id, array $data): void
*/
protected function editModComment(int $comment_id, string $edited_comment): void
{
- if (empty($comment_id) || empty($edited_comment))
+ if (empty($comment_id) || empty($edited_comment)) {
return;
+ }
- Db::$db->query('', '
- UPDATE {db_prefix}log_comments
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_comments
SET body = {string:body}
WHERE id_comment = {int:id_comment}',
- array(
+ [
'body' => $edited_comment,
'id_comment' => $comment_id,
- )
+ ],
);
}
@@ -1389,15 +1400,17 @@ protected function editModComment(int $comment_id, string $edited_comment): void
*/
protected function deleteModComment(int $comment_id): void
{
- if (empty($comment_id))
+ if (empty($comment_id)) {
return;
+ }
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_comments
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_comments
WHERE id_comment = {int:comment_id}',
- array(
+ [
'comment_id' => $comment_id,
- )
+ ],
);
}
@@ -1407,70 +1420,66 @@ protected function deleteModComment(int $comment_id): void
protected function buildQuickButtons(): void
{
// Quickbuttons for each report
- foreach (Utils::$context['reports'] as $key => $report)
- {
- Utils::$context['reports'][$key]['quickbuttons'] = array(
- 'details' => array(
+ foreach (Utils::$context['reports'] as $key => $report) {
+ Utils::$context['reports'][$key]['quickbuttons'] = [
+ 'details' => [
'label' => Lang::$txt['mc_reportedp_details'],
'href' => $report['report_href'],
'icon' => 'details',
- ),
- 'ignore' => array(
+ ],
+ 'ignore' => [
'label' => $report['ignore'] ? Lang::$txt['mc_reportedp_unignore'] : Lang::$txt['mc_reportedp_ignore'],
- 'href' => Config::$scripturl.'?action=moderate;area=reported'.$this->type.';sa=handle;ignore='.(int)!$report['ignore'].';rid='.$report['id'].';start='.Utils::$context['start'].';'.Utils::$context['session_var'].'='.Utils::$context['session_id'].';'.Utils::$context['mod-report-ignore_token_var'].'='.Utils::$context['mod-report-ignore_token'],
+ 'href' => Config::$scripturl . '?action=moderate;area=reported' . $this->type . ';sa=handle;ignore=' . (int) !$report['ignore'] . ';rid=' . $report['id'] . ';start=' . Utils::$context['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'] . ';' . Utils::$context['mod-report-ignore_token_var'] . '=' . Utils::$context['mod-report-ignore_token'],
'javascript' => !$report['ignore'] ? ' data-confirm="' . Lang::$txt['mc_reportedp_ignore_confirm'] . '"' : '',
'class' => 'you_sure',
- 'icon' => 'ignore'
- ),
- 'close' => array(
+ 'icon' => 'ignore',
+ ],
+ 'close' => [
'label' => Utils::$context['view_closed'] ? Lang::$txt['mc_reportedp_open'] : Lang::$txt['mc_reportedp_close'],
- 'href' => Config::$scripturl.'?action=moderate;area=reported'.$this->type.';sa=handle;closed='.(int)!$report['closed'].';rid='.$report['id'].';start='.Utils::$context['start'].';'.Utils::$context['session_var'].'='.Utils::$context['session_id'].';'.Utils::$context['mod-report-closed_token_var'].'='.Utils::$context['mod-report-closed_token'],
+ 'href' => Config::$scripturl . '?action=moderate;area=reported' . $this->type . ';sa=handle;closed=' . (int) !$report['closed'] . ';rid=' . $report['id'] . ';start=' . Utils::$context['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'] . ';' . Utils::$context['mod-report-closed_token_var'] . '=' . Utils::$context['mod-report-closed_token'],
'icon' => Utils::$context['view_closed'] ? 'folder' : 'close',
- ),
- );
+ ],
+ ];
// Only reported posts can be deleted
- if ($this->type == 'posts')
- {
- Utils::$context['reports'][$key]['quickbuttons']['delete'] = array(
+ if ($this->type == 'posts') {
+ Utils::$context['reports'][$key]['quickbuttons']['delete'] = [
'label' => Lang::$txt['mc_reportedp_delete'],
- 'href' => Config::$scripturl.'?action=deletemsg;topic='.$report['topic']['id'].'.0;msg='.$report['topic']['id_msg'].';modcenter;'.Utils::$context['session_var'].'='.Utils::$context['session_id'],
- 'javascript' => 'data-confirm="'.Lang::$txt['mc_reportedp_delete_confirm'].'"',
+ 'href' => Config::$scripturl . '?action=deletemsg;topic=' . $report['topic']['id'] . '.0;msg=' . $report['topic']['id_msg'] . ';modcenter;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
+ 'javascript' => 'data-confirm="' . Lang::$txt['mc_reportedp_delete_confirm'] . '"',
'class' => 'you_sure',
'icon' => 'delete',
- 'show' => !$report['closed'] && (is_array($this->remove_any_boards) && in_array($report['topic']['id_board'], $this->remove_any_boards))
- );
+ 'show' => !$report['closed'] && (is_array($this->remove_any_boards) && in_array($report['topic']['id_board'], $this->remove_any_boards)),
+ ];
}
// Ban reported member/post author link
- if ($this->type == 'members')
- {
- $ban_link = Config::$scripturl.'?action=admin;area=ban;sa=add;u='.$report['user']['id'].';'.Utils::$context['session_var'].'='.Utils::$context['session_id'];
- }
- else
- {
- $ban_link = Config::$scripturl.'?action=admin;area=ban;sa=add'.(!empty($report['author']['id']) ? ';u='.$report['author']['id'] : ';msg='.$report['topic']['id_msg']).';'.Utils::$context['session_var'].'='.Utils::$context['session_id'];
+ if ($this->type == 'members') {
+ $ban_link = Config::$scripturl . '?action=admin;area=ban;sa=add;u=' . $report['user']['id'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
+ } else {
+ $ban_link = Config::$scripturl . '?action=admin;area=ban;sa=add' . (!empty($report['author']['id']) ? ';u=' . $report['author']['id'] : ';msg=' . $report['topic']['id_msg']) . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
}
- Utils::$context['reports'][$key]['quickbuttons'] += array(
- 'ban' => array(
+ Utils::$context['reports'][$key]['quickbuttons'] += [
+ 'ban' => [
'label' => Lang::$txt['mc_reportedp_ban'],
'href' => $ban_link,
'icon' => 'error',
- 'show' => !$report['closed'] && !empty($this->manage_bans) && ($this->type == 'posts' || $this->type == 'members' && !empty($report['user']['id']))
- ),
- 'quickmod' => array(
+ 'show' => !$report['closed'] && !empty($this->manage_bans) && ($this->type == 'posts' || $this->type == 'members' && !empty($report['user']['id'])),
+ ],
+ 'quickmod' => [
'class' => 'inline_mod_check',
- 'content' => '',
- 'show' => !Utils::$context['view_closed'] && !empty(Theme::$current->options['display_quick_mod']) && Theme::$current->options['display_quick_mod'] == 1
- )
- );
+ 'content' => '',
+ 'show' => !Utils::$context['view_closed'] && !empty(Theme::$current->options['display_quick_mod']) && Theme::$current->options['display_quick_mod'] == 1,
+ ],
+ ];
}
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ReportedContent::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ReportedContent::exportStatic')) {
ReportedContent::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Moderation/ShowNotice.php b/Sources/Actions/Moderation/ShowNotice.php
index c54f4a7b22..1c9252b8d4 100644
--- a/Sources/Actions/Moderation/ShowNotice.php
+++ b/Sources/Actions/Moderation/ShowNotice.php
@@ -13,16 +13,15 @@
namespace SMF\Actions\Moderation;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Shows a notice sent to a user.
@@ -36,12 +35,11 @@ class ShowNotice implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ShowNotice',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -66,16 +64,17 @@ public function execute(): void
{
$id_notice = (int) $_GET['nid'];
- $request = Db::$db->query('', '
- SELECT body, subject
+ $request = Db::$db->query(
+ '',
+ 'SELECT body, subject
FROM {db_prefix}log_member_notices
WHERE id_notice = {int:id_notice}',
- array(
+ [
'id_notice' => $id_notice,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('no_access', false);
}
list(Utils::$context['notice_body'], Utils::$context['notice_subject']) = Db::$db->fetch_row($request);
@@ -95,8 +94,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;
}
@@ -119,18 +119,19 @@ public static function call(): void
protected function __construct()
{
// Before we get too excited, is the current user allowed to see this?
- User::$me->isAllowedTo(array('issue_warning', 'view_warning_any'));
+ User::$me->isAllowedTo(['issue_warning', 'view_warning_any']);
Utils::$context['page_title'] = Lang::$txt['show_notice'];
Utils::$context['sub_template'] = 'show_notice';
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
Theme::loadTemplate('ModerationCenter');
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ShowNotice::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ShowNotice::exportStatic')) {
ShowNotice::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Moderation/Warnings.php b/Sources/Actions/Moderation/Warnings.php
index 90e57f3ef9..f20667d5ed 100644
--- a/Sources/Actions/Moderation/Warnings.php
+++ b/Sources/Actions/Moderation/Warnings.php
@@ -13,10 +13,10 @@
namespace SMF\Actions\Moderation;
-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;
@@ -28,7 +28,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Allows the moderator to view stuff related to warnings.
@@ -42,12 +41,18 @@ class Warnings implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ViewWarnings',
- ),
- );
+ 'list_getWarningCount' => 'list_getWarningCount',
+ 'list_getWarnings' => 'list_getWarnings',
+ 'list_getWarningTemplateCount' => 'list_getWarningTemplateCount',
+ 'list_getWarningTemplates' => 'list_getWarningTemplates',
+ 'ViewWarningLog' => 'ViewWarningLog',
+ 'ViewWarningTemplates' => 'ViewWarningTemplates',
+ 'ModifyWarningTemplate' => 'ModifyWarningTemplate',
+ ],
+ ];
/*******************
* Public properties
@@ -70,11 +75,11 @@ class Warnings implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
- 'log' => array('log', array('view_warning_any', 'moderate_forum')),
- 'templates' => array('templates', 'issue_warning'),
- 'templateedit' => array('templateEdit', 'issue_warning'),
- );
+ public static array $subactions = [
+ 'log' => ['log', ['view_warning_any', 'moderate_forum']],
+ 'templates' => ['templates', 'issue_warning'],
+ 'templateedit' => ['templateEdit', 'issue_warning'],
+ ];
/****************************
* Internal static properties
@@ -100,15 +105,16 @@ public function execute(): void
Theme::loadTemplate('ModerationCenter');
Lang::load('Profile');
- Menu::$loaded['moderate']->tab_data = array(
+ Menu::$loaded['moderate']->tab_data = [
'title' => Lang::$txt['mc_warnings'],
'description' => Lang::$txt['mc_warnings_description'],
- );
+ ];
- $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);
+ }
}
/**
@@ -122,161 +128,155 @@ public function log(): void
Lang::load('Modlog');
// If we're coming from a search, get the variables.
- if (!empty($_REQUEST['params']) && empty($_REQUEST['is_search']))
- {
- $search_params = base64_decode(strtr($_REQUEST['params'], array(' ' => '+')));
+ if (!empty($_REQUEST['params']) && empty($_REQUEST['is_search'])) {
+ $search_params = base64_decode(strtr($_REQUEST['params'], [' ' => '+']));
$search_params = Utils::jsonDecode($search_params, true);
}
// This array houses all the valid search types.
- $searchTypes = array(
- 'member' => array('sql' => 'member_name_col', 'label' => Lang::$txt['profile_warning_previous_issued']),
- 'recipient' => array('sql' => 'recipient_name', 'label' => Lang::$txt['mc_warnings_recipient']),
- );
+ $searchTypes = [
+ 'member' => ['sql' => 'member_name_col', 'label' => Lang::$txt['profile_warning_previous_issued']],
+ 'recipient' => ['sql' => 'recipient_name', 'label' => Lang::$txt['mc_warnings_recipient']],
+ ];
// Do the column stuff!
- $sort_types = array(
+ $sort_types = [
'member' => 'member_name_col',
'recipient' => 'recipient_name',
- );
+ ];
// Setup the direction stuff...
Utils::$context['order'] = isset($_REQUEST['sort']) && isset($sort_types[$_REQUEST['sort']]) ? $_REQUEST['sort'] : 'member';
- if (!isset($search_params['string']) || (!empty($_REQUEST['search']) && $search_params['string'] != $_REQUEST['search']))
- {
+ if (!isset($search_params['string']) || (!empty($_REQUEST['search']) && $search_params['string'] != $_REQUEST['search'])) {
$search_params_string = empty($_REQUEST['search']) ? '' : $_REQUEST['search'];
- }
- else
- {
+ } else {
$search_params_string = $search_params['string'];
}
- if (isset($_REQUEST['search_type']) || empty($search_params['type']) || !isset($searchTypes[$search_params['type']]))
- {
+ if (isset($_REQUEST['search_type']) || empty($search_params['type']) || !isset($searchTypes[$search_params['type']])) {
$search_params_type = isset($_REQUEST['search_type']) && isset($searchTypes[$_REQUEST['search_type']]) ? $_REQUEST['search_type'] : (isset($searchTypes[Utils::$context['order']]) ? Utils::$context['order'] : 'member');
- }
- else
- {
+ } else {
$search_params_type = $search_params['type'];
}
- $search_params = array(
+ $search_params = [
'string' => $search_params_string,
'type' => $search_params_type,
- );
+ ];
Utils::$context['url_start'] = '?action=moderate;area=warnings;sa=log;sort=' . Utils::$context['order'];
// Setup the search context.
Utils::$context['search_params'] = empty($search_params['string']) ? '' : base64_encode(Utils::jsonEncode($search_params));
-
- Utils::$context['search'] = array(
+
+ Utils::$context['search'] = [
'string' => $search_params['string'],
'type' => $search_params['type'],
'label' => $searchTypes[$search_params_type]['label'],
- );
+ ];
// This is all the information required for a watched user listing.
- $listOptions = array(
+ $listOptions = [
'id' => 'warning_list',
'title' => Lang::$txt['mc_warning_log_title'],
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['mc_warnings_none'],
'base_href' => Config::$scripturl . '?action=moderate;area=warnings;sa=log;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'default_sort_col' => 'time',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getWarnings',
- ),
- 'get_count' => array(
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getWarningCount',
- ),
+ ],
// This assumes we are viewing by user.
- 'columns' => array(
- 'issuer' => array(
- 'header' => array(
+ 'columns' => [
+ 'issuer' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_issued'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'issuer_link',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'member_name_col',
'reverse' => 'member_name_col DESC',
- ),
- ),
- 'recipient' => array(
- 'header' => array(
+ ],
+ ],
+ 'recipient' => [
+ 'header' => [
'value' => Lang::$txt['mc_warnings_recipient'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'recipient_link',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'recipient_name',
'reverse' => 'recipient_name DESC',
- ),
- ),
- 'time' => array(
- 'header' => array(
+ ],
+ ],
+ 'time' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_time'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lc.log_time DESC',
'reverse' => 'lc.log_time',
- ),
- ),
- 'reason' => array(
- 'header' => array(
+ ],
+ ],
+ 'reason' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_reason'],
- ),
- 'data' => array(
- 'function' => function($rowData)
- {
+ ],
+ 'data' => [
+ 'function' => function ($rowData) {
$output = '
' . $rowData['reason'] . '
';
- if (!empty($rowData['id_notice']))
+ if (!empty($rowData['id_notice'])) {
$output .= '
';
+ }
+
return $output;
},
- ),
- ),
- 'points' => array(
- 'header' => array(
+ ],
+ ],
+ 'points' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_level'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'counter',
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . Utils::$context['url_start'],
'include_sort' => true,
'include_start' => true,
- 'hidden_fields' => array(
+ 'hidden_fields' => [
Utils::$context['session_var'] => Utils::$context['session_id'],
- 'params' => false
- ),
- ),
- 'additional_rows' => array(
- array(
+ 'params' => false,
+ ],
+ ],
+ 'additional_rows' => [
+ [
'position' => 'below_table_data',
'value' => '
' . Lang::$txt['modlog_search'] . ':
',
'class' => 'floatright',
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the watched user list.
new ItemList($listOptions);
@@ -291,49 +291,50 @@ public function log(): void
public function templates(): void
{
// Submitting a new one?
- if (isset($_POST['add']))
- {
+ if (isset($_POST['add'])) {
$this->ModifyWarningTemplate();
+
return;
}
- if (isset($_POST['delete']) && !empty($_POST['deltpl']))
- {
+ if (isset($_POST['delete']) && !empty($_POST['deltpl'])) {
User::$me->checkSession();
SecurityToken::validate('mod-wt');
// Log the actions.
- $request = Db::$db->query('', '
- SELECT recipient_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT recipient_name
FROM {db_prefix}log_comments
WHERE id_comment IN ({array_int:delete_ids})
AND comment_type = {string:warntpl}
AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})',
- array(
+ [
'delete_ids' => $_POST['deltpl'],
'warntpl' => 'warntpl',
'generic' => 0,
'current_member' => User::$me->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- Logging::logAction('delete_warn_template', array('template' => $row['recipient_name']));
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ Logging::logAction('delete_warn_template', ['template' => $row['recipient_name']]);
}
Db::$db->free_result($request);
// Do the deletes.
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_comments
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_comments
WHERE id_comment IN ({array_int:delete_ids})
AND comment_type = {string:warntpl}
AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})',
- array(
+ [
'delete_ids' => $_POST['deltpl'],
'warntpl' => 'warntpl',
'generic' => 0,
'current_member' => User::$me->id,
- )
+ ],
);
}
@@ -341,94 +342,93 @@ public function templates(): void
Utils::$context['page_title'] = Lang::$txt['mc_warning_templates_title'];
// This is all the information required for a watched user listing.
- $listOptions = array(
+ $listOptions = [
'id' => 'warning_template_list',
'title' => Lang::$txt['mc_warning_templates_title'],
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['mc_warning_templates_none'],
'base_href' => Config::$scripturl . '?action=moderate;area=warnings;sa=templates;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'default_sort_col' => 'title',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getWarningTemplates',
- ),
- 'get_count' => array(
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getWarningTemplateCount',
- ),
+ ],
// This assumes we are viewing by user.
- 'columns' => array(
- 'title' => array(
- 'header' => array(
+ 'columns' => [
+ 'title' => [
+ 'header' => [
'value' => Lang::$txt['mc_warning_templates_name'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => '%2$s',
- 'params' => array(
+ 'params' => [
'id_comment' => false,
'title' => false,
'body' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'template_title',
'reverse' => 'template_title DESC',
- ),
- ),
- 'creator' => array(
- 'header' => array(
+ ],
+ ],
+ 'creator' => [
+ 'header' => [
'value' => Lang::$txt['mc_warning_templates_creator'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'creator',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'creator_name',
'reverse' => 'creator_name DESC',
- ),
- ),
- 'time' => array(
- 'header' => array(
+ ],
+ ],
+ 'time' => [
+ 'header' => [
'value' => Lang::$txt['mc_warning_templates_time'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lc.log_time DESC',
'reverse' => 'lc.log_time',
- ),
- ),
- 'delete' => array(
- 'header' => array(
+ ],
+ ],
+ 'delete' => [
+ 'header' => [
'value' => '',
'style' => 'width: 4%;',
'class' => 'centercol',
- ),
- 'data' => array(
- 'function' => function($rowData)
- {
+ ],
+ 'data' => [
+ 'function' => function ($rowData) {
return '';
},
'class' => 'centercol',
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . '?action=moderate;area=warnings;sa=templates',
'token' => 'mod-wt',
- ),
- 'additional_rows' => array(
- array(
+ ],
+ 'additional_rows' => [
+ [
'position' => 'bottom_of_list',
'value' => ' ',
- ),
- array(
+ ],
+ [
'position' => 'bottom_of_list',
'value' => '',
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the watched user list.
SecurityToken::create('mod-wt');
@@ -452,44 +452,43 @@ public function templateEdit(): void
Menu::$loaded['moderate']['current_subsection'] = 'templates';
// Defaults.
- Utils::$context['template_data'] = array(
+ Utils::$context['template_data'] = [
'title' => '',
'body' => Lang::$txt['mc_warning_template_body_default'],
'personal' => false,
'can_edit_personal' => true,
- );
+ ];
// If it's an edit load it.
- if (Utils::$context['is_edit'])
- {
- $request = Db::$db->query('', '
- SELECT id_member, id_recipient, recipient_name AS template_title, body
+ if (Utils::$context['is_edit']) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, id_recipient, recipient_name AS template_title, body
FROM {db_prefix}log_comments
WHERE id_comment = {int:id}
AND comment_type = {string:warntpl}
AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})',
- array(
+ [
'id' => Utils::$context['id_template'],
'warntpl' => 'warntpl',
'generic' => 0,
'current_member' => User::$me->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- Utils::$context['template_data'] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ Utils::$context['template_data'] = [
'title' => $row['template_title'],
'body' => Utils::htmlspecialchars($row['body']),
'personal' => $row['id_recipient'],
'can_edit_personal' => $row['id_member'] == User::$me->id,
- );
+ ];
}
Db::$db->free_result($request);
}
// Wait, we are saving?
- if (isset($_POST['save']))
- {
+ if (isset($_POST['save'])) {
User::$me->checkSession();
SecurityToken::validate('mod-wt');
@@ -498,8 +497,7 @@ public function templateEdit(): void
$_POST['template_title'] = trim($_POST['template_title']);
// Need something in both boxes.
- if (!empty($_POST['template_body']) && !empty($_POST['template_title']))
- {
+ if (!empty($_POST['template_body']) && !empty($_POST['template_title'])) {
// Safety first.
$_POST['template_title'] = Utils::htmlspecialchars($_POST['template_title']);
@@ -507,23 +505,23 @@ public function templateEdit(): void
Msg::preparsecode($_POST['template_body']);
// But put line breaks back!
- $_POST['template_body'] = strtr($_POST['template_body'], array(' ' => "\n"));
+ $_POST['template_body'] = strtr($_POST['template_body'], [' ' => "\n"]);
// Is this personal?
$recipient_id = !empty($_POST['make_personal']) ? User::$me->id : 0;
// If we are this far it's save time.
- if (Utils::$context['is_edit'])
- {
+ if (Utils::$context['is_edit']) {
// Simple update...
- Db::$db->query('', '
- UPDATE {db_prefix}log_comments
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_comments
SET id_recipient = {int:personal}, recipient_name = {string:title}, body = {string:body}
WHERE id_comment = {int:id}
AND comment_type = {string:warntpl}
- AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})'.
+ AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})' .
($recipient_id ? ' AND id_member = {int:current_member}' : ''),
- array(
+ [
'personal' => $recipient_id,
'title' => $_POST['template_title'],
'body' => $_POST['template_body'],
@@ -531,60 +529,52 @@ public function templateEdit(): void
'warntpl' => 'warntpl',
'generic' => 0,
'current_member' => User::$me->id,
- )
+ ],
);
// If it wasn't visible and now is they've effectively added it.
- if (Utils::$context['template_data']['personal'] && !$recipient_id)
- {
- Logging::logAction('add_warn_template', array('template' => $_POST['template_title']));
+ if (Utils::$context['template_data']['personal'] && !$recipient_id) {
+ Logging::logAction('add_warn_template', ['template' => $_POST['template_title']]);
}
// Conversely if they made it personal it's a delete.
- elseif (!Utils::$context['template_data']['personal'] && $recipient_id)
- {
- Logging::logAction('delete_warn_template', array('template' => $_POST['template_title']));
+ elseif (!Utils::$context['template_data']['personal'] && $recipient_id) {
+ Logging::logAction('delete_warn_template', ['template' => $_POST['template_title']]);
}
// Otherwise just an edit.
- else
- {
- Logging::logAction('modify_warn_template', array('template' => $_POST['template_title']));
+ else {
+ Logging::logAction('modify_warn_template', ['template' => $_POST['template_title']]);
}
- }
- else
- {
- Db::$db->insert('',
+ } else {
+ Db::$db->insert(
+ '',
'{db_prefix}log_comments',
- array(
+ [
'id_member' => 'int', 'member_name' => 'string', 'comment_type' => 'string', 'id_recipient' => 'int',
'recipient_name' => 'string-255', 'body' => 'string-65535', 'log_time' => 'int',
- ),
- array(
+ ],
+ [
User::$me->id, User::$me->name, 'warntpl', $recipient_id,
$_POST['template_title'], $_POST['template_body'], time(),
- ),
- array('id_comment')
+ ],
+ ['id_comment'],
);
- Logging::logAction('add_warn_template', array('template' => $_POST['template_title']));
+ Logging::logAction('add_warn_template', ['template' => $_POST['template_title']]);
}
// Get out of town...
Utils::redirectexit('action=moderate;area=warnings;sa=templates');
- }
- else
- {
- Utils::$context['warning_errors'] = array();
+ } else {
+ Utils::$context['warning_errors'] = [];
Utils::$context['template_data']['title'] = !empty($_POST['template_title']) ? $_POST['template_title'] : '';
Utils::$context['template_data']['body'] = !empty($_POST['template_body']) ? $_POST['template_body'] : Lang::$txt['mc_warning_template_body_default'];
Utils::$context['template_data']['personal'] = !empty($_POST['make_personal']);
- if (empty($_POST['template_title']))
- {
+ if (empty($_POST['template_title'])) {
Utils::$context['warning_errors'][] = Lang::$txt['mc_warning_template_error_no_title'];
}
- if (empty($_POST['template_body']))
- {
+ if (empty($_POST['template_body'])) {
Utils::$context['warning_errors'][] = Lang::$txt['mc_warning_template_error_no_body'];
}
}
@@ -604,8 +594,9 @@ public function templateEdit(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -625,15 +616,16 @@ public static function call(): void
*/
public static function list_getWarningCount(): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_comments
WHERE comment_type = {string:warning}',
- array(
+ [
'warning' => 'warning',
- )
+ ],
);
- list ($totalWarns) = Db::$db->fetch_row($request);
+ list($totalWarns) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
return $totalWarns;
@@ -649,10 +641,11 @@ public static function list_getWarningCount(): int
*/
public static function list_getWarnings($start, $items_per_page, $sort): array
{
- $warnings = array();
+ $warnings = [];
- $request = Db::$db->query('', '
- SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name_col,
+ $request = Db::$db->query(
+ '',
+ 'SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name_col,
COALESCE(mem2.id_member, 0) AS id_recipient, COALESCE(mem2.real_name, lc.recipient_name) AS recipient_name,
lc.log_time, lc.body, lc.id_notice, lc.counter
FROM {db_prefix}log_comments AS lc
@@ -661,23 +654,23 @@ public static function list_getWarnings($start, $items_per_page, $sort): array
WHERE lc.comment_type = {string:warning}
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array(
+ [
'warning' => 'warning',
'start' => $start,
'max' => $items_per_page,
'sort' => $sort,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $warnings[] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $warnings[] = [
'issuer_link' => $row['id_member'] ? ('' . $row['member_name_col'] . '') : $row['member_name_col'],
'recipient_link' => $row['id_recipient'] ? ('' . $row['recipient_name'] . '') : $row['recipient_name'],
'time' => Time::create('@' . $row['log_time'])->format(),
'reason' => $row['body'],
'counter' => $row['counter'] > 0 ? '+' . $row['counter'] : $row['counter'],
'id_notice' => $row['id_notice'],
- );
+ ];
}
Db::$db->free_result($request);
@@ -691,18 +684,19 @@ public static function list_getWarnings($start, $items_per_page, $sort): array
*/
public static function list_getWarningTemplateCount(): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_comments
WHERE comment_type = {string:warntpl}
AND (id_recipient = {string:generic} OR id_recipient = {int:current_member})',
- array(
+ [
'warntpl' => 'warntpl',
'generic' => 0,
'current_member' => User::$me->id,
- )
+ ],
);
- list ($totalWarns) = Db::$db->fetch_row($request);
+ list($totalWarns) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
return $totalWarns;
@@ -718,10 +712,11 @@ public static function list_getWarningTemplateCount(): int
*/
public static function list_getWarningTemplates($start, $items_per_page, $sort): array
{
- $templates = array();
+ $templates = [];
- $request = Db::$db->query('', '
- SELECT lc.id_comment, COALESCE(mem.id_member, 0) AS id_member,
+ $request = Db::$db->query(
+ '',
+ 'SELECT lc.id_comment, COALESCE(mem.id_member, 0) AS id_member,
COALESCE(mem.real_name, lc.member_name) AS creator_name, recipient_name AS template_title,
lc.log_time, lc.body
FROM {db_prefix}log_comments AS lc
@@ -730,21 +725,21 @@ public static function list_getWarningTemplates($start, $items_per_page, $sort):
AND (id_recipient = {string:generic} OR id_recipient = {int:current_member})
ORDER BY ' . $sort . '
LIMIT ' . $start . ', ' . $items_per_page,
- array(
+ [
'warntpl' => 'warntpl',
'generic' => 0,
'current_member' => User::$me->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $templates[] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $templates[] = [
'id_comment' => $row['id_comment'],
'creator' => $row['id_member'] ? ('' . $row['creator_name'] . '') : $row['creator_name'],
'time' => Time::create('@' . $row['log_time'])->format(),
'title' => $row['template_title'],
'body' => Utils::htmlspecialchars($row['body']),
- );
+ ];
}
Db::$db->free_result($request);
@@ -790,31 +785,31 @@ public static function ModifyWarningTemplate(): void
*/
protected function __construct()
{
- IntegrationHook::call('integrate_warning_log_actions', array(&self::$subactions));
+ IntegrationHook::call('integrate_warning_log_actions', [&self::$subactions]);
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
+ }
// If the user can't do the specified sub-action, choose the first one they can.
- if (!User::$me->allowedTo(self::$subactions[$this->subaction][1]))
- {
+ if (!User::$me->allowedTo(self::$subactions[$this->subaction][1])) {
$this->subaction = '';
- foreach (self::$subactions as $sa => $sa_info)
- {
- if ($sa === $this->subaction)
+ foreach (self::$subactions as $sa => $sa_info) {
+ if ($sa === $this->subaction) {
continue;
+ }
- if (User::$me->allowedTo(self::$subactions[$sa][1]))
- {
+ if (User::$me->allowedTo(self::$subactions[$sa][1])) {
$this->subaction = $sa;
break;
}
}
// This shouldn't happen, but just in case...
- if (empty($this->subaction))
+ if (empty($this->subaction)) {
Utils::redirectexit('action=moderate;area=index');
+ }
}
}
@@ -823,11 +818,11 @@ protected function __construct()
*************************/
// code...
-
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Warnings::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Warnings::exportStatic')) {
Warnings::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Moderation/WatchedUsers.php b/Sources/Actions/Moderation/WatchedUsers.php
index f1e4b30b62..46d97f4abb 100644
--- a/Sources/Actions/Moderation/WatchedUsers.php
+++ b/Sources/Actions/Moderation/WatchedUsers.php
@@ -13,11 +13,11 @@
namespace SMF\Actions\Moderation;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ItemList;
use SMF\Lang;
use SMF\Menu;
@@ -26,12 +26,11 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Rename here and in the exportStatic call at the end of the file.
*/
-class WatchUsers implements ActionInterface
+class WatchedUsers implements ActionInterface
{
use BackwardCompatibility;
@@ -40,12 +39,15 @@ class WatchUsers implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ViewWatchedUsers',
- ),
- );
+ 'list_getWatchedUserCount' => 'list_getWatchedUserCount',
+ 'list_getWatchedUsers' => 'list_getWatchedUsers',
+ 'list_getWatchedUserPostsCount' => 'list_getWatchedUserPostsCount',
+ 'list_getWatchedUserPosts' => 'list_getWatchedUserPosts',
+ ],
+ ];
/****************************
* Internal static properties
@@ -69,180 +71,178 @@ class WatchUsers implements ActionInterface
public function execute(): void
{
// First off - are we deleting?
- if (!empty($_REQUEST['delete']))
- {
+ if (!empty($_REQUEST['delete'])) {
User::$me->checkSession(!is_array($_REQUEST['delete']) ? 'get' : 'post');
- $toDelete = array();
- if (!is_array($_REQUEST['delete']))
+ $toDelete = [];
+
+ if (!is_array($_REQUEST['delete'])) {
$toDelete[] = (int) $_REQUEST['delete'];
- else
- foreach ($_REQUEST['delete'] as $did)
+ } else {
+ foreach ($_REQUEST['delete'] as $did) {
$toDelete[] = (int) $did;
+ }
+ }
- if (!empty($toDelete))
- {
+ if (!empty($toDelete)) {
// If they don't have permission we'll let it error - either way no chance of a security slip here!
- foreach ($toDelete as $did)
+ foreach ($toDelete as $did) {
Msg::remove($did);
+ }
}
}
// Start preparing the list by grabbing relevant permissions.
- if (!Utils::$context['view_posts'])
- {
+ if (!Utils::$context['view_posts']) {
$approve_query = '';
- $delete_boards = array();
- }
- else
- {
+ $delete_boards = [];
+ } else {
// Still obey permissions!
$approve_boards = User::$me->boardsAllowedTo('approve_posts');
$delete_boards = User::$me->boardsAllowedTo('delete_any');
- if ($approve_boards == array(0))
+ if ($approve_boards == [0]) {
$approve_query = '';
- elseif (!empty($approve_boards))
+ } elseif (!empty($approve_boards)) {
$approve_query = ' AND m.id_board IN (' . implode(',', $approve_boards) . ')';
+ }
// Nada, zip, etc...
- else
+ else {
$approve_query = ' AND 1=0';
+ }
}
// This is all the information required for a watched user listing.
- $listOptions = array(
+ $listOptions = [
'id' => 'watch_user_list',
'title' => Lang::$txt['mc_watched_users_title'] . ' - ' . (Utils::$context['view_posts'] ? Lang::$txt['mc_watched_users_post'] : Lang::$txt['mc_watched_users_member']),
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Utils::$context['view_posts'] ? Lang::$txt['mc_watched_users_no_posts'] : Lang::$txt['mc_watched_users_none'],
'base_href' => Config::$scripturl . '?action=moderate;area=userwatch;sa=' . (Utils::$context['view_posts'] ? 'post' : 'member'),
'default_sort_col' => Utils::$context['view_posts'] ? '' : 'member',
- 'get_items' => array(
+ 'get_items' => [
'function' => Utils::$context['view_posts'] ? __CLASS__ . '::list_getWatchedUserPosts' : __CLASS__ . '::list_getWatchedUsers',
- 'params' => array(
+ 'params' => [
$approve_query,
$delete_boards,
- ),
- ),
- 'get_count' => array(
+ ],
+ ],
+ 'get_count' => [
'function' => Utils::$context['view_posts'] ? 'list_getWatchedUserPostsCount' : __CLASS__ . '::list_getWatchedUserCount',
- 'params' => array(
+ 'params' => [
$approve_query,
- ),
- ),
+ ],
+ ],
// This assumes we are viewing by user.
- 'columns' => array(
- 'member' => array(
- 'header' => array(
+ 'columns' => [
+ 'member' => [
+ 'header' => [
'value' => Lang::$txt['mc_watched_users_member'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => '%2$s',
- 'params' => array(
+ 'params' => [
'id' => false,
'name' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'real_name',
'reverse' => 'real_name DESC',
- ),
- ),
- 'warning' => array(
- 'header' => array(
+ ],
+ ],
+ 'warning' => [
+ 'header' => [
'value' => Lang::$txt['mc_watched_users_warning'],
- ),
- 'data' => array(
- 'function' => function($member)
- {
+ ],
+ 'data' => [
+ 'function' => function ($member) {
return User::$me->allowedTo('issue_warning') ? '' . $member['warning'] . '%' : $member['warning'] . '%';
},
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'warning',
'reverse' => 'warning DESC',
- ),
- ),
- 'posts' => array(
- 'header' => array(
+ ],
+ ],
+ 'posts' => [
+ 'header' => [
'value' => Lang::$txt['posts'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => '%2$s',
- 'params' => array(
+ 'params' => [
'id' => false,
'posts' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'posts',
'reverse' => 'posts DESC',
- ),
- ),
- 'last_login' => array(
- 'header' => array(
+ ],
+ ],
+ 'last_login' => [
+ 'header' => [
'value' => Lang::$txt['mc_watched_users_last_login'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'last_login',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'last_login',
'reverse' => 'last_login DESC',
- ),
- ),
- 'last_post' => array(
- 'header' => array(
+ ],
+ ],
+ 'last_post' => [
+ 'header' => [
'value' => Lang::$txt['mc_watched_users_last_post'],
- ),
- 'data' => array(
- 'function' => function($member)
- {
- if ($member['last_post_id'])
+ ],
+ 'data' => [
+ 'function' => function ($member) {
+ if ($member['last_post_id']) {
return '' . $member['last_post'] . '';
- else
- return $member['last_post'];
+ }
+
+ return $member['last_post'];
},
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . '?action=moderate;area=userwatch;sa=post',
'include_sort' => true,
'include_start' => true,
- 'hidden_fields' => array(
+ 'hidden_fields' => [
Utils::$context['session_var'] => Utils::$context['session_id'],
- ),
- ),
- 'additional_rows' => array(
+ ],
+ ],
+ 'additional_rows' => [
Utils::$context['view_posts'] ?
- array(
+ [
'position' => 'bottom_of_list',
'value' => '
',
'class' => 'floatright',
- ) : array(),
- ),
- );
+ ] : [],
+ ],
+ ];
// If this is being viewed by posts we actually change the columns to call a template each time.
- if (Utils::$context['view_posts'])
- {
- $listOptions['columns'] = array(
- 'posts' => array(
- 'data' => array(
- 'function' => function($post)
- {
+ if (Utils::$context['view_posts']) {
+ $listOptions['columns'] = [
+ 'posts' => [
+ 'data' => [
+ 'function' => function ($post) {
return template_user_watch_post_callback($post);
},
- 'class' => 'unique'
- ),
- ),
- );
+ 'class' => 'unique',
+ ],
+ ],
+ ];
}
// Create the watched user list.
@@ -263,8 +263,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;
}
@@ -285,15 +286,16 @@ public static function call(): void
*/
public static function list_getWatchedUserCount($approve_query): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}members
WHERE warning >= {int:warning_watch}',
- array(
+ [
'warning_watch' => Config::$modSettings['warning_watch'],
- )
+ ],
);
- list ($totalMembers) = Db::$db->fetch_row($request);
+ list($totalMembers) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
return $totalMembers;
@@ -311,24 +313,25 @@ public static function list_getWatchedUserCount($approve_query): int
*/
public static function list_getWatchedUsers($start, $items_per_page, $sort, $approve_query, $dummy): array
{
- $request = Db::$db->query('', '
- SELECT id_member, real_name, last_login, posts, warning
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name, last_login, posts, warning
FROM {db_prefix}members
WHERE warning >= {int:warning_watch}
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array(
+ [
'warning_watch' => Config::$modSettings['warning_watch'],
'sort' => $sort,
'start' => $start,
'max' => $items_per_page,
- )
+ ],
);
- $watched_users = array();
- $members = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
- $watched_users[$row['id_member']] = array(
+ $watched_users = [];
+ $members = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $watched_users[$row['id_member']] = [
'id' => $row['id_member'],
'name' => $row['real_name'],
'last_login' => $row['last_login'] ? Time::create('@' . $row['last_login'])->format() : Lang::$txt['never'],
@@ -336,16 +339,16 @@ public static function list_getWatchedUsers($start, $items_per_page, $sort, $app
'last_post_id' => 0,
'warning' => $row['warning'],
'posts' => $row['posts'],
- );
+ ];
$members[] = $row['id_member'];
}
Db::$db->free_result($request);
- if (!empty($members))
- {
+ if (!empty($members)) {
// First get the latest messages from these users.
- $request = Db::$db->query('', '
- SELECT m.id_member, MAX(m.id_msg) AS last_post_id
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_member, MAX(m.id_msg) AS last_post_id
FROM {db_prefix}messages AS m' . (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)') . '
WHERE {query_see_message_board}
@@ -353,28 +356,30 @@ public static function list_getWatchedUsers($start, $items_per_page, $sort, $app
AND m.approved = {int:is_approved}
AND t.approved = {int:is_approved}') . '
GROUP BY m.id_member',
- array(
+ [
'member_list' => $members,
'is_approved' => 1,
- )
+ ],
);
- $latest_posts = array();
- while ($row = Db::$db->fetch_assoc($request))
+ $latest_posts = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$latest_posts[$row['id_member']] = $row['last_post_id'];
+ }
- if (!empty($latest_posts))
- {
+ if (!empty($latest_posts)) {
// Now get the time those messages were posted.
- $request = Db::$db->query('', '
- SELECT id_member, poster_time
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, poster_time
FROM {db_prefix}messages
WHERE id_msg IN ({array_int:message_list})',
- array(
+ [
'message_list' => $latest_posts,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$watched_users[$row['id_member']]['last_post'] = Time::create('@' . $row['poster_time'])->format();
$watched_users[$row['id_member']]['last_post_id'] = $latest_posts[$row['id_member']];
}
@@ -382,20 +387,21 @@ public static function list_getWatchedUsers($start, $items_per_page, $sort, $app
Db::$db->free_result($request);
}
- $request = Db::$db->query('', '
- SELECT MAX(m.poster_time) AS last_post, MAX(m.id_msg) AS last_post_id, m.id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT MAX(m.poster_time) AS last_post, MAX(m.id_msg) AS last_post_id, m.id_member
FROM {db_prefix}messages AS m
WHERE {query_see_message_board}
AND m.id_member IN ({array_int:member_list})' . (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
AND m.approved = {int:is_approved}') . '
GROUP BY m.id_member',
- array(
+ [
'member_list' => $members,
'is_approved' => 1,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$watched_users[$row['id_member']]['last_post'] = Time::create('@' . $row['last_post'])->format();
$watched_users[$row['id_member']]['last_post_id'] = $row['last_post_id'];
}
@@ -413,19 +419,20 @@ public static function list_getWatchedUsers($start, $items_per_page, $sort, $app
*/
public static function list_getWatchedUserPostsCount($approve_query): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
WHERE mem.warning >= {int:warning_watch}
AND {query_see_board}
' . $approve_query,
- array(
+ [
'warning_watch' => Config::$modSettings['warning_watch'],
- )
+ ],
);
- list ($totalMemberPosts) = Db::$db->fetch_row($request);
+ list($totalMemberPosts) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
return $totalMemberPosts;
@@ -443,8 +450,9 @@ public static function list_getWatchedUserPostsCount($approve_query): int
*/
public static function list_getWatchedUserPosts($start, $items_per_page, $sort, $approve_query, $delete_boards): array
{
- $request = Db::$db->query('', '
- SELECT m.id_msg, m.id_topic, m.id_board, m.id_member, m.subject, m.body, m.poster_time,
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg, m.id_topic, m.id_board, m.id_member, m.subject, m.body, m.poster_time,
m.approved, mem.real_name, m.smileys_enabled
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
@@ -454,19 +462,19 @@ public static function list_getWatchedUserPosts($start, $items_per_page, $sort,
' . $approve_query . '
ORDER BY m.id_msg DESC
LIMIT {int:start}, {int:max}',
- array(
+ [
'warning_watch' => Config::$modSettings['warning_watch'],
'start' => $start,
'max' => $items_per_page,
- )
+ ],
);
- $member_posts = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $member_posts = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$row['subject'] = Lang::censorText($row['subject']);
$row['body'] = Lang::censorText($row['body']);
- $member_posts[$row['id_msg']] = array(
+ $member_posts[$row['id_msg']] = [
'id' => $row['id_msg'],
'id_topic' => $row['id_topic'],
'author_link' => '' . $row['real_name'] . '',
@@ -474,8 +482,8 @@ public static function list_getWatchedUserPosts($start, $items_per_page, $sort,
'body' => BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], $row['id_msg']),
'poster_time' => Time::create('@' . $row['poster_time'])->format(),
'approved' => $row['approved'],
- 'can_delete' => $delete_boards == array(0) || in_array($row['id_board'], $delete_boards),
- );
+ 'can_delete' => $delete_boards == [0] || in_array($row['id_board'], $delete_boards),
+ ];
}
Db::$db->free_result($request);
@@ -502,16 +510,17 @@ protected function __construct()
Config::$modSettings['warning_watch'] = empty(Config::$modSettings['warning_watch']) ? 1 : Config::$modSettings['warning_watch'];
// Put some pretty tabs on cause we're gonna be doing hot stuff here...
- Menu::$loaded['moderate']->tab_data = array(
+ Menu::$loaded['moderate']->tab_data = [
'title' => Lang::$txt['mc_watched_users_title'],
'help' => '',
'description' => Lang::$txt['mc_watched_users_desc'],
- );
+ ];
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\WatchUsers::exportStatic'))
- WatchUsers::exportStatic();
+if (is_callable(__NAMESPACE__ . '\\WatchedUsers::exportStatic')) {
+ WatchedUsers::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Moderation/index.php b/Sources/Actions/Moderation/index.php
new file mode 100644
index 0000000000..976d292448
--- /dev/null
+++ b/Sources/Actions/Moderation/index.php
@@ -0,0 +1,9 @@
+
\ No newline at end of file
diff --git a/Sources/Actions/MsgDelete.php b/Sources/Actions/MsgDelete.php
index a728ab3a71..4cb095bc0b 100644
--- a/Sources/Actions/MsgDelete.php
+++ b/Sources/Actions/MsgDelete.php
@@ -14,16 +14,15 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Logging;
use SMF\Msg;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This action handles the deletion of posts.
@@ -37,12 +36,11 @@ class MsgDelete implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'DeleteMessage',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -71,85 +69,65 @@ public function execute(): void
$_REQUEST['msg'] = (int) $_REQUEST['msg'];
// Is Topic::$topic_id set?
- if (empty(Topic::$topic_id) && isset($_REQUEST['topic']))
+ if (empty(Topic::$topic_id) && isset($_REQUEST['topic'])) {
Topic::$topic_id = (int) $_REQUEST['topic'];
+ }
TopicRemove::removeDeleteConcurrence();
- $request = Db::$db->query('', '
- SELECT t.id_member_started, m.id_member, m.subject, m.poster_time, m.approved
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_member_started, m.id_member, m.subject, m.poster_time, m.approved
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = {int:id_msg} AND m.id_topic = {int:current_topic})
WHERE t.id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
'id_msg' => $_REQUEST['msg'],
- )
+ ],
);
list($starter, $poster, $subject, $post_time, $approved) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Verify they can see this!
- if (Config::$modSettings['postmod_active'] && !$approved && !empty($poster) && $poster != User::$me->id)
- {
+ if (Config::$modSettings['postmod_active'] && !$approved && !empty($poster) && $poster != User::$me->id) {
User::$me->isAllowedTo('approve_posts');
}
- if ($poster == User::$me->id)
- {
- if (!User::$me->allowedTo('delete_own'))
- {
- if ($starter == User::$me->id && !User::$me->allowedTo('delete_any'))
- {
+ if ($poster == User::$me->id) {
+ if (!User::$me->allowedTo('delete_own')) {
+ if ($starter == User::$me->id && !User::$me->allowedTo('delete_any')) {
User::$me->isAllowedTo('delete_replies');
- }
- elseif (!User::$me->allowedTo('delete_any'))
- {
+ } elseif (!User::$me->allowedTo('delete_any')) {
User::$me->isAllowedTo('delete_own');
}
- }
- elseif (!User::$me->allowedTo('delete_any') && ($starter != User::$me->id || !User::$me->allowedTo('delete_replies')) && !empty(Config::$modSettings['edit_disable_time']) && $post_time + Config::$modSettings['edit_disable_time'] * 60 < time())
- {
+ } elseif (!User::$me->allowedTo('delete_any') && ($starter != User::$me->id || !User::$me->allowedTo('delete_replies')) && !empty(Config::$modSettings['edit_disable_time']) && $post_time + Config::$modSettings['edit_disable_time'] * 60 < time()) {
ErrorHandler::fatalLang('modify_post_time_passed', false);
}
- }
- elseif ($starter == User::$me->id && !User::$me->allowedTo('delete_any'))
- {
+ } elseif ($starter == User::$me->id && !User::$me->allowedTo('delete_any')) {
User::$me->isAllowedTo('delete_replies');
- }
- else
- {
+ } else {
User::$me->isAllowedTo('delete_any');
}
// If the full topic was removed go back to the board.
$full_topic = Msg::remove($_REQUEST['msg']);
- if (User::$me->allowedTo('delete_any') && (!User::$me->allowedTo('delete_own') || $poster != User::$me->id))
- {
- Logging::logAction('delete', array('topic' => Topic::$topic_id, 'subject' => $subject, 'member' => $poster, 'board' => Board::$info->id));
+ if (User::$me->allowedTo('delete_any') && (!User::$me->allowedTo('delete_own') || $poster != User::$me->id)) {
+ Logging::logAction('delete', ['topic' => Topic::$topic_id, 'subject' => $subject, 'member' => $poster, 'board' => Board::$info->id]);
}
// We want to redirect back to recent action.
- if (isset($_REQUEST['modcenter']))
- {
+ if (isset($_REQUEST['modcenter'])) {
Utils::redirectexit('action=moderate;area=reportedposts;done');
- }
- elseif (isset($_REQUEST['recent']))
- {
+ } elseif (isset($_REQUEST['recent'])) {
Utils::redirectexit('action=recent');
- }
- elseif (isset($_REQUEST['profile'], $_REQUEST['start'], $_REQUEST['u']))
- {
+ } elseif (isset($_REQUEST['profile'], $_REQUEST['start'], $_REQUEST['u'])) {
Utils::redirectexit('action=profile;u=' . $_REQUEST['u'] . ';area=showposts;start=' . $_REQUEST['start']);
- }
- elseif ($full_topic)
- {
+ } elseif ($full_topic) {
Utils::redirectexit('board=' . Board::$info->id . '.0');
- }
- else
- {
+ } else {
Utils::redirectexit('topic=' . Topic::$topic_id . '.' . $_REQUEST['start']);
}
}
@@ -165,8 +143,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;
}
@@ -192,7 +171,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\MsgDelete::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\MsgDelete::exportStatic')) {
MsgDelete::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Notify.php b/Sources/Actions/Notify.php
index fa9438f9e6..4c14c018c7 100644
--- a/Sources/Actions/Notify.php
+++ b/Sources/Actions/Notify.php
@@ -14,14 +14,13 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This abstract class contains the main functionality to toggle email
@@ -40,29 +39,34 @@ abstract class Notify
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'getNotifyPrefs' => 'getNotifyPrefs',
+ 'setNotifyPrefs' => 'setNotifyPrefs',
+ 'deleteNotifyPrefs' => 'deleteNotifyPrefs',
+ 'getMemberWithToken' => 'getMemberWithToken',
+ 'createUnsubscribeToken' => 'createUnsubscribeToken',
+ ],
+ ];
/*****************
* Class constants
*****************/
// Pref refers to the value that will be saved to user_alerts_prefs table.
- const PREF_NONE = 0;
- const PREF_ALERT = 1;
- const PREF_EMAIL = 2;
- const PREF_BOTH = 3;
+ public const PREF_NONE = 0;
+ public const PREF_ALERT = 1;
+ public const PREF_EMAIL = 2;
+ public const PREF_BOTH = 3;
// Mode refers to the input submitted by $_GET or $_POST.
// Unfortunately, mode != pref.
- const MODE_NO_EMAIL = -2;
- const MODE_NO_ALERT = -1;
- const MODE_IGNORE = 0;
- const MODE_NONE = 1;
- const MODE_ALERT = 2;
- const MODE_BOTH = 3;
+ public const MODE_NO_EMAIL = -2;
+ public const MODE_NO_ALERT = -1;
+ public const MODE_IGNORE = 0;
+ public const MODE_NONE = 1;
+ public const MODE_ALERT = 2;
+ public const MODE_BOTH = 3;
/*******************
* Public properties
@@ -128,29 +132,30 @@ public function execute(): void
$this->setId();
$this->setMode();
- if (!isset($this->mode))
+ if (!isset($this->mode)) {
return;
+ }
// We don't tolerate imposters around here.
- if (empty($this->token))
+ if (empty($this->token)) {
User::$me->checkSession('get');
+ }
$this->changePref();
// AJAX call.
- if (isset($_GET['xml']))
- {
+ if (isset($_GET['xml'])) {
$this->prepareAjaxResponse();
}
// Nothing to redirect to or they got here via an unsubscribe link,
// so just show a confirmation message.
- elseif (!isset($this->id) || !empty($this->token))
- {
+ elseif (!isset($this->id) || !empty($this->token)) {
$this->showConfirmation();
}
// Send them back to wherever they came from.
- else
+ else {
Utils::redirectexit($this->type . '=' . $this->id . '.' . ($_REQUEST['start'] ?? 0));
+ }
}
/***********************
@@ -169,39 +174,44 @@ public function execute(): void
public static function getNotifyPrefs($members, $prefs = '', $process_default = false)
{
// We want this as an array whether it is or not.
- $members = is_array($members) ? $members : (array) $members;
+ $members = array_map('intval', (array) $members);
- if (!empty($prefs))
+ if (!empty($prefs)) {
$prefs = is_array($prefs) ? $prefs : (array) $prefs;
+ }
- $result = array();
+ $result = [];
// We want to now load the default, which is stored with a member id of 0.
$members[] = 0;
- $request = Db::$db->query('', '
- SELECT id_member, alert_pref, alert_value
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, alert_pref, alert_value
FROM {db_prefix}user_alerts_prefs
WHERE id_member IN ({array_int:members})' . (!empty($prefs) ? '
AND alert_pref IN ({array_string:prefs})' : ''),
- array(
+ [
'members' => $members,
'prefs' => $prefs,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$result[$row['id_member']][$row['alert_pref']] = $row['alert_value'];
+ }
// We may want to keep the default values separate from a given user's. Or we might not.
- if ($process_default && isset($result[0]))
- {
- foreach ($members as $member)
- if (isset($result[$member]))
+ if ($process_default && isset($result[0])) {
+ foreach ($members as $member) {
+ if (isset($result[$member])) {
$result[$member] += $result[0];
- else
+ } else {
$result[$member] = $result[0];
+ }
+ }
- unset ($result[0]);
+ unset($result[0]);
}
return $result;
@@ -213,20 +223,24 @@ public static function getNotifyPrefs($members, $prefs = '', $process_default =
* @param int $memID The user whose preferences you are setting
* @param array $prefs An array key of pref -> value
*/
- public static function setNotifyPrefs($memID, $prefs = array())
+ public static function setNotifyPrefs($memID, $prefs = [])
{
- if (empty($prefs) || !is_int($memID))
+ if (empty($prefs) || !is_int($memID)) {
return;
+ }
+
+ $update_rows = [];
- $update_rows = array();
- foreach ($prefs as $k => $v)
- $update_rows[] = array($memID, $k, min(max((int) $v, -128), 127));
+ foreach ($prefs as $k => $v) {
+ $update_rows[] = [$memID, $k, min(max((int) $v, -128), 127)];
+ }
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}user_alerts_prefs',
- array('id_member' => 'int', 'alert_pref' => 'string', 'alert_value' => 'int'),
+ ['id_member' => 'int', 'alert_pref' => 'string', 'alert_value' => 'int'],
$update_rows,
- array('id_member', 'alert_pref')
+ ['id_member', 'alert_pref'],
);
}
@@ -238,17 +252,19 @@ public static function setNotifyPrefs($memID, $prefs = array())
*/
public static function deleteNotifyPrefs($memID, array $prefs)
{
- if (empty($prefs) || empty($memID))
+ if (empty($prefs) || empty($memID)) {
return;
+ }
- Db::$db->query('', '
- DELETE FROM {db_prefix}user_alerts_prefs
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}user_alerts_prefs
WHERE id_member = {int:member}
AND alert_pref IN ({array_string:prefs})',
- array(
+ [
'member' => $memID,
'prefs' => $prefs,
- )
+ ],
);
}
@@ -264,31 +280,34 @@ public static function getMemberWithToken($type)
$id_member = !empty($_REQUEST['u']) ? (int) $_REQUEST['u'] : 0;
// We can't do anything without these
- if (empty($id_member) || empty($_REQUEST['token']))
+ if (empty($id_member) || empty($_REQUEST['token'])) {
ErrorHandler::fatalLang('unsubscribe_invalid', false);
+ }
// Get the user info we need
- $request = Db::$db->query('', '
- SELECT id_member AS id, email_address AS email
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member AS id, email_address AS email
FROM {db_prefix}members
WHERE id_member = {int:id_member}',
- array(
+ [
'id_member' => $id_member,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('unsubscribe_invalid', false);
}
$this->member_info = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
// What token are we expecting?
- $expected_token = Notify::createUnsubscribeToken($this->member_info['id'], $this->member_info['email'], $type, in_array($type, array('board', 'topic')) && !empty($$type) ? $$type : 0);
+ $expected_token = Notify::createUnsubscribeToken($this->member_info['id'], $this->member_info['email'], $type, in_array($type, ['board', 'topic']) && !empty($$type) ? $$type : 0);
// Don't do anything if the token they gave is wrong
- if ($_REQUEST['token'] !== $expected_token)
+ if ($_REQUEST['token'] !== $expected_token) {
ErrorHandler::fatalLang('unsubscribe_invalid', false);
+ }
// At this point, we know we have a legitimate unsubscribe request
return $this->member_info;
@@ -305,7 +324,7 @@ public static function getMemberWithToken($type)
*/
public static function createUnsubscribeToken($memID, $email, $type = '', $itemID = 0)
{
- $token_items = implode(' ', array($memID, $email, $type, $itemID));
+ $token_items = implode(' ', [$memID, $email, $type, $itemID]);
// When the message is public and the key is secret, an HMAC is the appropriate tool.
$token = hash_hmac('sha256', $token_items, Config::getAuthSecret(), true);
@@ -314,7 +333,7 @@ public static function createUnsubscribeToken($memID, $email, $type = '', $itemI
$token = substr($token, 0, 10);
// Use base64 (with URL-friendly characters) to make the token shorter.
- return strtr(base64_encode($token), array('+' => '_', '/' => '-', '=' => ''));
+ return strtr(base64_encode($token), ['+' => '_', '/' => '-', '=' => '']);
}
/******************
@@ -326,14 +345,12 @@ public static function createUnsubscribeToken($memID, $email, $type = '', $itemI
*/
protected function setMemberInfo()
{
- if (isset($_REQUEST['u']) && isset($_REQUEST['token']))
- {
+ if (isset($_REQUEST['u'], $_REQUEST['token'])) {
$this->member_info = self::getMemberWithToken($this->type);
$this->token = $_REQUEST['token'];
}
// No token, so try with the current user.
- else
- {
+ else {
// Permissions are an important part of anything ;).
User::$me->kickIfGuest();
$this->member_info = (array) User::$me;
@@ -360,11 +377,13 @@ protected function setMode()
$this->saToMode();
// What do we do? Better ask if they didn't say..
- if (!isset($_GET['mode']) && !isset($_GET['xml']))
+ if (!isset($_GET['mode']) && !isset($_GET['xml'])) {
$this->ask();
+ }
- if (isset($_GET['mode']))
+ if (isset($_GET['mode'])) {
$this->mode = (int) $_GET['mode'];
+ }
}
/**
@@ -375,12 +394,11 @@ protected function ask()
Theme::loadTemplate('Notify');
Utils::$context['page_title'] = Lang::$txt['notification'];
- if ($this->member_info['id'] !== User::$me->id)
- {
- Utils::$context['notify_info'] = array(
+ if ($this->member_info['id'] !== User::$me->id) {
+ Utils::$context['notify_info'] = [
'u' => $this->member_info['id'],
'token' => $_REQUEST['token'],
- );
+ ];
}
$this->askTemplateData();
@@ -403,8 +421,7 @@ abstract protected function changePref();
*/
protected function setAlertPref()
{
- switch ($this->mode)
- {
+ switch ($this->mode) {
case self::MODE_IGNORE:
case self::MODE_NONE:
$this->alert_pref = self::PREF_NONE;
@@ -422,7 +439,7 @@ protected function setAlertPref()
// while leaving the alert preference unchanged.
case self::MODE_NO_EMAIL:
// Use bitwise operator to turn off the email part of the setting.
- $this->alert_pref = self::getNotifyPrefs($this->member_info['id'], array($this->type . '_notify_' . $this->id), true) & self::PREF_ALERT;
+ $this->alert_pref = self::getNotifyPrefs($this->member_info['id'], [$this->type . '_notify_' . $this->id], true) & self::PREF_ALERT;
break;
}
}
@@ -432,32 +449,31 @@ protected function setAlertPref()
*/
protected function changeBoardTopicPref()
{
- self::setNotifyPrefs((int) $this->member_info['id'], array($this->type . '_notify_' . $this->id => $this->alert_pref));
+ self::setNotifyPrefs((int) $this->member_info['id'], [$this->type . '_notify_' . $this->id => $this->alert_pref]);
- if ($this->alert_pref > self::PREF_NONE)
- {
+ if ($this->alert_pref > self::PREF_NONE) {
$id_board = $this->type === 'board' ? $this->id : 0;
$id_topic = $this->type === 'topic' ? $this->id : 0;
// Turn notification on. (note this just blows smoke if it's already on.)
- Db::$db->insert('ignore',
+ Db::$db->insert(
+ 'ignore',
'{db_prefix}log_notify',
- array('id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int'),
- array(User::$me->id, $id_topic, $id_board),
- array('id_member', 'id_topic', 'id_board')
+ ['id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int'],
+ [User::$me->id, $id_topic, $id_board],
+ ['id_member', 'id_topic', 'id_board'],
);
- }
- else
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_notify
+ } else {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_notify
WHERE id_member = {int:member}
AND {raw:column} = {int:id}',
- array(
+ [
'column' => 'id_' . $this->type,
'id' => $this->id,
'member' => $this->member_info['id'],
- )
+ ],
);
}
}
@@ -467,14 +483,14 @@ protected function changeBoardTopicPref()
*/
protected function prepareAjaxResponse()
{
- Utils::$context['xml_data']['errors'] = array(
+ Utils::$context['xml_data']['errors'] = [
'identifier' => 'error',
- 'children' => array(
- array(
+ 'children' => [
+ [
'value' => 0,
- ),
- ),
- );
+ ],
+ ],
+ ];
Utils::$context['sub_template'] = 'generic_xml';
}
@@ -498,7 +514,8 @@ abstract protected function getSuccessMsg();
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Notify::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Notify::exportStatic')) {
Notify::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/NotifyAnnouncements.php b/Sources/Actions/NotifyAnnouncements.php
index fb22325560..5b981a2abf 100644
--- a/Sources/Actions/NotifyAnnouncements.php
+++ b/Sources/Actions/NotifyAnnouncements.php
@@ -14,7 +14,6 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Lang;
use SMF\Utils;
@@ -30,12 +29,11 @@ class NotifyAnnouncements extends Notify implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'AnnouncementsNotify',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -71,8 +69,9 @@ class NotifyAnnouncements extends Notify implements ActionInterface
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -110,8 +109,7 @@ protected function setId()
*/
protected function saToMode()
{
- if (!isset($_GET['mode']) && isset($_GET['sa']))
- {
+ if (!isset($_GET['mode']) && isset($_GET['sa'])) {
$_GET['mode'] = $_GET['sa'] == 'on' ? 3 : 0;
unset($_GET['sa']);
}
@@ -125,10 +123,11 @@ protected function setMode()
$this->saToMode();
// What do we do? Better ask if they didn't say..
- if (!isset($_GET['mode']))
+ if (!isset($_GET['mode'])) {
$this->ask();
- else
+ } else {
$this->mode = $_GET['mode'];
+ }
}
/**
@@ -149,7 +148,7 @@ protected function changePref()
$this->alert_pref = $this->alert_pref & parent::PREF_EMAIL;
// Update their announcement notification preference.
- parent::setNotifyPrefs((int) $this->member_info['id'], array('announcements' => $this->alert_pref));
+ parent::setNotifyPrefs((int) $this->member_info['id'], ['announcements' => $this->alert_pref]);
// Show a confirmation message.
Utils::$context['sub_template'] = 'notify_pref_changed';
@@ -166,7 +165,8 @@ protected function getSuccessMsg()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\NotifyAnnouncements::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\NotifyAnnouncements::exportStatic')) {
NotifyAnnouncements::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/NotifyBoard.php b/Sources/Actions/NotifyBoard.php
index 2a5235f141..cb0a7c573f 100644
--- a/Sources/Actions/NotifyBoard.php
+++ b/Sources/Actions/NotifyBoard.php
@@ -14,8 +14,8 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
+use SMF\Config;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Utils;
@@ -32,12 +32,11 @@ class NotifyBoard extends Notify implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'BoardNotify',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -73,8 +72,9 @@ class NotifyBoard extends Notify implements ActionInterface
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -103,8 +103,9 @@ protected function __construct()
*/
protected function setId()
{
- if (empty(Board::$info->id))
+ if (empty(Board::$info->id)) {
ErrorHandler::fatalLang('no_board', false);
+ }
$this->id = Board::$info->id;
}
@@ -116,8 +117,7 @@ protected function setId()
*/
protected function saToMode()
{
- if (!isset($_GET['mode']) && isset($_GET['sa']))
- {
+ if (!isset($_GET['mode']) && isset($_GET['sa'])) {
$_GET['mode'] = $_GET['sa'] == 'on' ? 3 : -1;
unset($_GET['sa']);
}
@@ -156,11 +156,11 @@ protected function getSuccessMsg()
*************************/
// code...
-
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\NotifyBoard::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\NotifyBoard::exportStatic')) {
NotifyBoard::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/NotifyTopic.php b/Sources/Actions/NotifyTopic.php
index 04ff92a911..9bfb667407 100644
--- a/Sources/Actions/NotifyTopic.php
+++ b/Sources/Actions/NotifyTopic.php
@@ -14,11 +14,12 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
+use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Topic;
-use SMF\Db\DatabaseApi as Db;
+use SMF\Utils;
/**
* Toggles email notification preferences for topics.
@@ -32,12 +33,11 @@ class NotifyTopic extends Notify implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'TopicNotify',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -73,8 +73,9 @@ class NotifyTopic extends Notify implements ActionInterface
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -103,8 +104,9 @@ protected function __construct()
*/
protected function setId()
{
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
ErrorHandler::fatalLang('not_a_topic', false);
+ }
$this->id = Topic::$topic_id;
}
@@ -116,8 +118,7 @@ protected function setId()
*/
protected function saToMode()
{
- if (!isset($_GET['mode']) && isset($_GET['sa']))
- {
+ if (!isset($_GET['mode']) && isset($_GET['sa'])) {
$_GET['mode'] = $_GET['sa'] == 'on' ? 3 : -1;
unset($_GET['sa']);
}
@@ -139,42 +140,42 @@ protected function changePref()
{
$this->setAlertPref();
- $request = Db::$db->query('', '
- SELECT id_member, id_topic, id_msg, unwatched
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, id_topic, id_msg, unwatched
FROM {db_prefix}log_topics
WHERE id_member = {int:member}
AND {raw:column} = {int:id}',
- array(
+ [
'column' => 'id_' . $this->type,
'id' => $this->id,
'member' => $this->member_info['id'],
- )
+ ],
);
$log = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
- if (empty($log))
- {
+
+ if (empty($log)) {
$insert = true;
- $log = array(
+ $log = [
'id_member' => $this->member_info['id'],
'id_topic' => $this->id,
'id_msg' => 0,
'unwatched' => (int) ($this->mode === parent::MODE_IGNORE),
- );
- }
- else
- {
+ ];
+ } else {
$insert = false;
$log['unwatched'] = (int) ($this->mode === parent::MODE_IGNORE);
}
- Db::$db->insert($insert ? 'insert' : 'replace',
+ Db::$db->insert(
+ $insert ? 'insert' : 'replace',
'{db_prefix}log_topics',
- array(
+ [
'id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int',
- ),
+ ],
$log,
- array('id_member', 'id_topic')
+ ['id_member', 'id_topic'],
);
$this->changeBoardTopicPref();
@@ -187,11 +188,11 @@ protected function getSuccessMsg()
{
return sprintf(Lang::$txt['notify_topic' . (!empty($this->alert_pref & parent::PREF_EMAIL) ? '_subscribed' : '_unsubscribed')], $this->member_info['email']);
}
-
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\NotifyTopic::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\NotifyTopic::exportStatic')) {
NotifyTopic::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/PersonalMessage.php b/Sources/Actions/PersonalMessage.php
index a7f72dd4bf..447dd0303b 100644
--- a/Sources/Actions/PersonalMessage.php
+++ b/Sources/Actions/PersonalMessage.php
@@ -14,21 +14,14 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
-use SMF\BBCodeParser;
use SMF\BrowserDetector;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Menu;
-use SMF\Msg;
-use SMF\Profile;
-use SMF\Theme;
-use SMF\User;
-use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
use SMF\PersonalMessage\{
Conversation,
DraftPM,
@@ -41,6 +34,10 @@
Search,
SearchResult,
};
+use SMF\Profile;
+use SMF\Theme;
+use SMF\User;
+use SMF\Utils;
/**
* This class is mainly meant for controlling the actions related to personal
@@ -56,12 +53,25 @@ class PersonalMessage implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'MessageMain',
- ),
- );
+ 'messageFolder' => 'MessageFolder',
+ 'messagePopup' => 'MessagePopup',
+ 'manageLabels' => 'ManageLabels',
+ 'manageRules' => 'ManageRules',
+ 'messageActionsApply' => 'MessageActionsApply',
+ 'messagePrune' => 'MessagePrune',
+ 'messageKillAll' => 'MessageKillAll',
+ 'reportMessage' => 'ReportMessage',
+ 'messageSearch' => 'MessageSearch',
+ 'messageSearch2' => 'MessageSearch2',
+ 'messagePost' => 'MessagePost',
+ 'messagePost2' => 'MessagePost2',
+ 'messageSettings' => 'MessageSettings',
+ 'messageDrafts' => 'MessageDrafts',
+ ],
+ ];
/*****************
* Class constants
@@ -70,17 +80,17 @@ class PersonalMessage implements ActionInterface
/**
* Display mode to show all personal messages in a paginated list.
*/
- const VIEW_ALL = 0;
+ public const VIEW_ALL = 0;
/**
* Display mode to show one personal message at a time.
*/
- const VIEW_ONE = 1;
+ public const VIEW_ONE = 1;
/**
* Display mode to show personal messages in a conversation view.
*/
- const VIEW_CONV = 2;
+ public const VIEW_CONV = 2;
/*******************
* Public properties
@@ -102,72 +112,72 @@ class PersonalMessage implements ActionInterface
* In this default definintion, all parts of the menu are set as enabled.
* At runtime, however, various parts may be turned on or off.
*/
- public array $pm_areas = array(
- 'folders' => array(
+ public array $pm_areas = [
+ 'folders' => [
'title' => 'pm_messages',
- 'areas' => array(
- 'inbox' => array(
+ 'areas' => [
+ 'inbox' => [
'label' => 'inbox',
'custom_url' => '{scripturl}?action=pm',
'amt' => 0,
- ),
- 'send' => array(
+ ],
+ 'send' => [
'label' => 'new_message',
'custom_url' => '{scripturl}?action=pm;sa=send',
'permission' => 'pm_send',
'amt' => 0,
- ),
- 'sent' => array(
+ ],
+ 'sent' => [
'label' => 'sent_items',
'custom_url' => '{scripturl}?action=pm;f=sent',
'amt' => 0,
- ),
- 'drafts' => array(
+ ],
+ 'drafts' => [
'label' => 'drafts_show',
'custom_url' => '{scripturl}?action=pm;sa=showpmdrafts',
'permission' => 'pm_draft',
'enabled' => true,
'amt' => 0,
- ),
- ),
+ ],
+ ],
'amt' => 0,
- ),
- 'labels' => array(
+ ],
+ 'labels' => [
'title' => 'pm_labels',
- 'areas' => array(),
+ 'areas' => [],
'amt' => 0,
- ),
- 'actions' => array(
+ ],
+ 'actions' => [
'title' => 'pm_actions',
- 'areas' => array(
- 'search' => array(
+ 'areas' => [
+ 'search' => [
'label' => 'pm_search_bar_title',
'custom_url' => '{scripturl}?action=pm;sa=search',
- ),
- 'prune' => array(
+ ],
+ 'prune' => [
'label' => 'pm_prune',
- 'custom_url' => '{scripturl}?action=pm;sa=prune'
- ),
- ),
- ),
- 'pref' => array(
+ 'custom_url' => '{scripturl}?action=pm;sa=prune',
+ ],
+ ],
+ ],
+ 'pref' => [
'title' => 'pm_preferences',
- 'areas' => array(
- 'manlabels' => array(
+ 'areas' => [
+ 'manlabels' => [
'label' => 'pm_manage_labels',
'custom_url' => '{scripturl}?action=pm;sa=manlabels',
- ),
- 'manrules' => array(
+ ],
+ 'manrules' => [
'label' => 'pm_manage_rules',
'custom_url' => '{scripturl}?action=pm;sa=manrules',
- ),
- 'settings' => array(
+ ],
+ 'settings' => [
'label' => 'pm_settings',
'custom_url' => '{scripturl}?action=pm;sa=settings',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
/**
* @var string
@@ -212,7 +222,7 @@ class PersonalMessage implements ActionInterface
*
* Keys are the IDs of some PMs. Values are arrays of label IDs.
*/
- public array $labels_in_use = array();
+ public array $labels_in_use = [];
/**
* @var array
@@ -221,7 +231,7 @@ class PersonalMessage implements ActionInterface
*
* Keys are the IDs of some PMs. Values are booleans.
*/
- public array $replied = array();
+ public array $replied = [];
/**
* @var array
@@ -230,7 +240,7 @@ class PersonalMessage implements ActionInterface
*
* Keys are the IDs of some PMs. Values are booleans.
*/
- public array $unread = array();
+ public array $unread = [];
/**************************
* Public static properties
@@ -241,7 +251,7 @@ class PersonalMessage implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'show' => 'show',
'popup' => 'popup',
'showpmdrafts' => 'drafts',
@@ -256,18 +266,18 @@ class PersonalMessage implements ActionInterface
'manlabels' => 'labels',
'manrules' => 'rules',
'settings' => 'settings',
- );
+ ];
/**
* @var array
*
* Instructions for sorting the personal messages.
*/
- public static $sort_methods = array(
+ public static $sort_methods = [
'date' => 'pm.id_pm',
'name' => 'COALESCE(mem.real_name, \'\')',
'subject' => 'pm.subject',
- );
+ ];
/*********************
* Internal properties
@@ -308,30 +318,26 @@ public function execute(): void
User::$me->isAllowedTo('pm_read');
// If we have unsorted mail, apply our rules!
- if (User::$me->new_pm)
- {
+ if (User::$me->new_pm) {
Rule::apply();
Received::setNotNew();
}
// No menu in AJAX requests or the popup.
- if (!isset($_REQUEST['xml']) && $this->subaction !== 'popup')
- {
- if ($this->subaction === 'show')
- {
+ if (!isset($_REQUEST['xml']) && $this->subaction !== 'popup') {
+ if ($this->subaction === 'show') {
$this->createMenu($this->current_label_id == -1 ? $this->folder : 'label' . $this->current_label_id);
- }
- else
- {
+ } else {
$this->createMenu($this->subaction);
}
}
// Now let's get on with the main job...
- $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);
+ }
}
/**
@@ -355,8 +361,9 @@ public function popup(): void
*/
public function drafts(): void
{
- if (empty(User::$me->id))
+ if (empty(User::$me->id)) {
ErrorHandler::fatalLang('not_a_user', false);
+ }
DraftPM::showInProfile(User::$me->id);
}
@@ -374,7 +381,10 @@ public function send(): void
*/
public function send2(): void
{
- PM::compose2();
+ // Message sent successfully?
+ if (PM::compose2()) {
+ Utils::redirectexit($this->current_label_redirect . ';done=sent');
+ }
}
/**
@@ -400,93 +410,81 @@ public function applyActions(): void
{
User::$me->checkSession('request');
- if (isset($_REQUEST['del_selected']))
+ if (isset($_REQUEST['del_selected'])) {
$_REQUEST['pm_action'] = 'delete';
+ }
- if (isset($_REQUEST['pm_action']) && $_REQUEST['pm_action'] != '' && !empty($_REQUEST['pms']) && is_array($_REQUEST['pms']))
- {
- foreach ($_REQUEST['pms'] as $pm)
+ if (isset($_REQUEST['pm_action']) && $_REQUEST['pm_action'] != '' && !empty($_REQUEST['pms']) && is_array($_REQUEST['pms'])) {
+ foreach ($_REQUEST['pms'] as $pm) {
$_REQUEST['pm_actions'][(int) $pm] = $_REQUEST['pm_action'];
+ }
}
- if (empty($_REQUEST['pm_actions']))
+ if (empty($_REQUEST['pm_actions'])) {
Utils::redirectexit($this->current_label_redirect);
+ }
// Don't act on a conversation unless the view mode and the $_REQUEST var match.
- if (($this->mode == self::VIEW_CONV) != (isset($_REQUEST['conversation'])))
+ if (($this->mode == self::VIEW_CONV) != (isset($_REQUEST['conversation']))) {
Utils::redirectexit($this->current_label_redirect);
+ }
// Don't do labels unless we're in the inbox.
- if ($this->folder !== 'inbox')
- {
- $_REQUEST['pm_actions'] = array_filter($_REQUEST['pm_actions'], fn($action) => $action === 'delete');
+ if ($this->folder !== 'inbox') {
+ $_REQUEST['pm_actions'] = array_filter($_REQUEST['pm_actions'], fn ($action) => $action === 'delete');
}
// If we are in conversation, we may need to apply this to every PM in the conversation.
- if ($this->mode == self::VIEW_CONV)
- {
- foreach (array_keys($_REQUEST['pm_actions']) as $pm)
- {
+ if ($this->mode == self::VIEW_CONV) {
+ foreach (array_keys($_REQUEST['pm_actions']) as $pm) {
$conversation = new Conversation($pm);
- foreach ($conversation->pms as $id => $info)
- {
+ foreach ($conversation->pms as $id => $info) {
// We only label received PMs, not sent ones.
- if ($_REQUEST['pm_actions'][$pm] == 'delete' || $info['sender'] != User::$me->id)
- {
+ if ($_REQUEST['pm_actions'][$pm] == 'delete' || $info['sender'] != User::$me->id) {
$_REQUEST['pm_actions'][$id] = $_REQUEST['pm_actions'][$pm];
}
}
}
}
- $to_delete = array();
- $to_label = array();
- $label_type = array();
- foreach ($_REQUEST['pm_actions'] as $pm => $action)
- {
+ $to_delete = [];
+ $to_label = [];
+ $label_type = [];
+
+ foreach ($_REQUEST['pm_actions'] as $pm => $action) {
// Deleting.
- if ($action === 'delete')
- {
+ if ($action === 'delete') {
$to_delete[] = (int) $pm;
}
// Adding a label.
- elseif (substr($action, 0, 4) == 'add_')
- {
+ elseif (substr($action, 0, 4) == 'add_') {
$type = 'add';
$action = substr($action, 4);
}
// Removing a label.
- elseif (substr($action, 0, 4) == 'rem_')
- {
+ elseif (substr($action, 0, 4) == 'rem_') {
$type = 'rem';
$action = substr($action, 4);
}
- if (in_array($type, array('add', 'rem')) && ($action == '-1' || (int) $action > 0))
- {
+ if (in_array($type, ['add', 'rem']) && ($action == '-1' || (int) $action > 0)) {
$to_label[(int) $pm] = (int) $action;
$label_type[(int) $pm] = $type;
}
}
// Deleting, it looks like?
- if (!empty($to_delete))
- {
+ if (!empty($to_delete)) {
PM::delete($to_delete, $this->folder);
}
// Are we labeling anything?
- if (!empty($to_label) && $this->folder === 'inbox')
- {
- foreach (Received::loadByPm(array_keys($to_label)) as $received)
- {
- if ($label_type[$received->id] === 'add')
- {
+ if (!empty($to_label) && $this->folder === 'inbox') {
+ foreach (Received::loadByPm(array_keys($to_label)) as $received) {
+ if ($label_type[$received->id] === 'add') {
$received->addLabel($to_label[$received->id]);
- }
- elseif ($label_type[$received->id] === 'rem')
- {
+ } elseif ($label_type[$received->id] === 'rem') {
$received->removeLabel($to_label[$received->id]);
}
}
@@ -516,8 +514,7 @@ public function removeAll(): void
*/
public function prune(): void
{
- if (isset($_REQUEST['age']))
- {
+ if (isset($_REQUEST['age'])) {
User::$me->checkSession();
// Calculate the time to delete before.
@@ -531,10 +528,10 @@ public function prune(): void
}
// Build the link tree elements.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=pm;sa=prune',
- 'name' => Lang::$txt['pm_prune']
- );
+ 'name' => Lang::$txt['pm_prune'],
+ ];
Utils::$context['sub_template'] = 'prune';
Utils::$context['page_title'] = Lang::$txt['pm_prune'];
@@ -552,37 +549,39 @@ public function prune(): void
public function report(): void
{
// Check that this feature is even enabled!
- if (empty(Config::$modSettings['enableReportPM']) || empty($_REQUEST['pmsg']))
+ if (empty(Config::$modSettings['enableReportPM']) || empty($_REQUEST['pmsg'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
$pm = current(PM::load((int) $_REQUEST['pmsg']));
// Users are not allowed to report messages that they can't see.
- if (!$pm->canAccess('inbox'))
+ if (!$pm->canAccess('inbox')) {
ErrorHandler::fatalLang('no_access', false);
+ }
Utils::$context['pm_id'] = $pm->id;
Utils::$context['page_title'] = Lang::$txt['pm_report_title'];
// If we're here, just send the user to the template, with a few useful context bits.
- if (!isset($_POST['report']))
- {
+ if (!isset($_POST['report'])) {
Utils::$context['sub_template'] = 'report_message';
// @todo I don't like being able to pick who to send it to. Favoritism, etc. sucks.
// Now, get all the administrators.
- Utils::$context['admins'] = array();
- $request = Db::$db->query('', '
- SELECT id_member, real_name
+ Utils::$context['admins'] = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name
FROM {db_prefix}members
WHERE id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0
ORDER BY real_name',
- array(
+ [
'admin_group' => 1,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Utils::$context['admins'][$row['id_member']] = $row['real_name'];
}
Db::$db->free_result($request);
@@ -591,8 +590,7 @@ public function report(): void
Utils::$context['admin_count'] = count(Utils::$context['admins']);
}
// Otherwise, let's get down to the sending stuff.
- else
- {
+ else {
// Check the session before proceeding any further!
User::$me->checkSession();
@@ -600,80 +598,77 @@ public function report(): void
$body = preg_replace('~ ~i', "\n", $this->body);
// Get any other recipients of the email.
- $recipients = array();
+ $recipients = [];
$hidden_recipients = 0;
- foreach ($pm->received as $received)
- {
- if ($received->member === User::$me->id)
+ foreach ($pm->received as $received) {
+ if ($received->member === User::$me->id) {
continue;
+ }
// If it's hidden still don't reveal their names - privacy after all ;)
- if (!empty($received->bcc))
- {
+ if (!empty($received->bcc)) {
$hidden_recipients++;
- }
- else
- {
+ } else {
$recipients[] = '[url=' . Config::$scripturl . '?action=profile;u=' . $received->member . ']' . $received->name . '[/url]';
}
}
- if ($hidden_recipients)
+ if ($hidden_recipients) {
$recipients[] = sprintf(Lang::$txt['pm_report_pm_hidden'], $hidden_recipients);
+ }
// Prepare the message storage array.
- $messagesToSend = array();
+ $messagesToSend = [];
// Now let's get out and loop through the admins.
$memberFromName = Utils::htmlspecialcharsDecode($this->from_name);
- $request = Db::$db->query('', '
- SELECT id_member, real_name, lngfile
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name, lngfile
FROM {db_prefix}members
WHERE (id_group = {int:admin_id} OR FIND_IN_SET({int:admin_id}, additional_groups) != 0)
' . (empty($_POST['id_admin']) ? '' : 'AND id_member = {int:specific_admin}') . '
ORDER BY lngfile',
- array(
+ [
'admin_id' => 1,
'specific_admin' => isset($_POST['id_admin']) ? (int) $_POST['id_admin'] : 0,
- )
+ ],
);
+
// Maybe we shouldn't advertise this?
- if (Db::$db->num_rows($request) == 0)
- {
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('no_access', false);
}
+
// Loop through each admin, and add them to the right language pile...
- while ($row = Db::$db->fetch_assoc($request))
- {
+ while ($row = Db::$db->fetch_assoc($request)) {
// Need to send in the correct language!
$cur_language = empty($row['lngfile']) || empty(Config::$modSettings['userLanguage']) ? Lang::$default : $row['lngfile'];
- if (!isset($messagesToSend[$cur_language]))
- {
+ if (!isset($messagesToSend[$cur_language])) {
Lang::load('PersonalMessage', $cur_language, false);
// Make the body.
- $report_body = str_replace(array('{REPORTER}', '{SENDER}'), array(Utils::htmlspecialcharsDecode(User::$me->name), $memberFromName), Lang::$txt['pm_report_pm_user_sent']);
+ $report_body = str_replace(['{REPORTER}', '{SENDER}'], [Utils::htmlspecialcharsDecode(User::$me->name), $memberFromName], Lang::$txt['pm_report_pm_user_sent']);
$report_body .= "\n" . '[b]' . $_POST['reason'] . '[/b]' . "\n\n";
- if (!empty($recipients))
- {
+ if (!empty($recipients)) {
$report_body .= Lang::$txt['pm_report_pm_other_recipients'] . ' ' . implode(', ', $recipients) . "\n\n";
}
$report_body .= Lang::$txt['pm_report_pm_unedited_below'] . "\n" . '[quote author=' . (empty($this->member_from) ? '"' . $memberFromName . '"' : $memberFromName . ' link=action=profile;u=' . $this->member_from . ' date=' . $this->msgtime) . ']' . "\n" . Utils::htmlspecialcharsDecode($body) . '[/quote]';
// Plonk it in the array ;)
- $messagesToSend[$cur_language] = array(
+ $messagesToSend[$cur_language] = [
'subject' => (Utils::entityStrpos($this->subject, Lang::$txt['pm_report_pm_subject']) === false ? Lang::$txt['pm_report_pm_subject'] : '') . Utils::htmlspecialcharsDecode($this->subject),
'body' => $report_body,
- 'recipients' => array(
- 'to' => array(),
- 'bcc' => array()
- ),
- );
+ 'recipients' => [
+ 'to' => [],
+ 'bcc' => [],
+ ],
+ ];
}
// Add them to the list.
@@ -682,12 +677,14 @@ public function report(): void
Db::$db->free_result($request);
// Send a different email for each language.
- foreach ($messagesToSend as $lang => $message)
+ foreach ($messagesToSend as $lang => $message) {
PM::send($message['recipients'], $message['subject'], $message['body']);
+ }
// Give the user their own language back!
- if (!empty(Config::$modSettings['userLanguage']))
+ if (!empty(Config::$modSettings['userLanguage'])) {
Lang::load('PersonalMessage', '', false);
+ }
// Leave them with a template.
Utils::$context['sub_template'] = 'report_message_complete';
@@ -744,19 +741,18 @@ public function settings(): void
Profile::$member->loadCustomFields('pmprefs');
// Add our position to the linktree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=pm;sa=settings',
- 'name' => Lang::$txt['pm_settings']
- );
+ 'name' => Lang::$txt['pm_settings'],
+ ];
// Are they saving?
- if (isset($_REQUEST['save']))
- {
+ if (isset($_REQUEST['save'])) {
User::$me->checkSession();
Profile::$member->save();
}
- Profile::$member->setupContext(array('pm_prefs'));
+ Profile::$member->setupContext(['pm_prefs']);
}
/***********************
@@ -770,8 +766,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;
}
@@ -935,14 +932,17 @@ protected function __construct()
{
Lang::load('PersonalMessage+Drafts');
- if (!isset($_REQUEST['xml']))
+ if (!isset($_REQUEST['xml'])) {
Theme::loadTemplate('PersonalMessage');
+ }
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
+ }
- if (isset($_REQUEST['f']) && $_REQUEST['f'] === 'sent')
+ if (isset($_REQUEST['f']) && $_REQUEST['f'] === 'sent') {
$this->folder = 'sent';
+ }
$this->buildLimitBar();
@@ -959,8 +959,9 @@ protected function __construct()
$this->mode = User::$me->pm_prefs & 3;
// A previous message was sent successfully? Show a small indication.
- if (isset($_GET['done']) && ($_GET['done'] == 'sent'))
+ if (isset($_GET['done']) && ($_GET['done'] == 'sent')) {
Utils::$context['pm_sent'] = true;
+ }
// Some context stuff for the templates.
Utils::$context['display_mode'] = &$this->mode;
@@ -977,10 +978,10 @@ protected function __construct()
Utils::$context['drafts_autosave'] = !empty(Utils::$context['drafts_save']) && !empty(Config::$modSettings['drafts_autosave_enabled']) && !empty(Theme::$current->options['drafts_autosave_enabled']);
// Build the linktree for all the actions...
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=pm',
- 'name' => Lang::$txt['personal_messages']
- );
+ 'name' => Lang::$txt['personal_messages'],
+ ];
}
/**
@@ -993,48 +994,45 @@ protected function createMenu($area): void
// Finalize string values in the menu.
array_walk_recursive(
$this->pm_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,
- ));
- }
+ ]);
+ },
);
$this->pm_areas['folders']['areas']['drafts']['enabled'] = !empty(Config::$modSettings['drafts_pm_enabled']);
// Give mods access to the menu.
- IntegrationHook::call('integrate_pm_areas', array(&$this->pm_areas));
+ IntegrationHook::call('integrate_pm_areas', [&$this->pm_areas]);
// Handle labels.
- if (empty(Label::$loaded))
- {
+ if (empty(Label::$loaded)) {
unset($this->pm_areas['labels']);
- }
- else
- {
+ } else {
// Note we send labels by id as it will have less problems in the querystring.
- foreach (Label::$loaded as $label)
- {
- if ($label['id'] == -1)
+ foreach (Label::$loaded as $label) {
+ if ($label['id'] == -1) {
continue;
+ }
// Count the amount of unread items in labels.
$this->pm_areas['labels']['amt'] += $label['unread_messages'];
// Add the label to the menu.
- $this->pm_areas['labels']['areas']['label' . $label['id']] = array(
+ $this->pm_areas['labels']['areas']['label' . $label['id']] = [
'label' => $label['name'],
'custom_url' => Config::$scripturl . '?action=pm;l=' . $label['id'],
'amt' => $label['unread_messages'],
'unread_messages' => $label['unread_messages'],
'messages' => $label['messages'],
'icon' => 'folder',
- );
+ ];
}
}
@@ -1042,25 +1040,25 @@ function(&$value, $key)
$this->pm_areas['folders']['areas']['inbox']['messages'] = Label::$loaded[-1]['messages'];
- if (!empty(Label::$loaded[-1]['unread_messages']))
- {
+ if (!empty(Label::$loaded[-1]['unread_messages'])) {
$this->pm_areas['folders']['areas']['inbox']['amt'] = Label::$loaded[-1]['unread_messages'];
$this->pm_areas['folders']['amt'] = Label::$loaded[-1]['unread_messages'];
}
// Set a few options for the menu.
- $menuOptions = array(
+ $menuOptions = [
'current_area' => $area,
'disable_url_session_check' => true,
- );
+ ];
// Actually create the menu!
$menu = new Menu($this->pm_areas, $menuOptions);
// No menu means no access.
- if (empty($menu->include_data) && (!User::$me->is_guest || User::$me->validateSession()))
+ if (empty($menu->include_data) && (!User::$me->is_guest || User::$me->validateSession())) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Make a note of the Unique ID for this menu.
Utils::$context['pm_menu_id'] = $menu->id;
@@ -1070,8 +1068,9 @@ function(&$value, $key)
Utils::$context['menu_item_selected'] = $menu->current_area;
// Set the template for this area and add the profile layer.
- if (!isset($_REQUEST['xml']))
+ if (!isset($_REQUEST['xml'])) {
Utils::$context['template_layers'][] = 'pm';
+ }
}
/**
@@ -1079,19 +1078,20 @@ function(&$value, $key)
*/
protected function buildLimitBar()
{
- if (User::$me->is_admin)
+ if (User::$me->is_admin) {
return;
+ }
- if (($limit = CacheApi::get('msgLimit:' . User::$me->id, 360)) === null)
- {
+ if (($limit = CacheApi::get('msgLimit:' . User::$me->id, 360)) === null) {
// @todo Why do we do this? It seems like if they have any limit we should use it.
- $request = Db::$db->query('', '
- SELECT MAX(max_messages) AS top_limit, MIN(max_messages) AS bottom_limit
+ $request = Db::$db->query(
+ '',
+ 'SELECT MAX(max_messages) AS top_limit, MIN(max_messages) AS bottom_limit
FROM {db_prefix}membergroups
WHERE id_group IN ({array_int:users_groups})',
- array(
+ [
'users_groups' => User::$me->groups,
- )
+ ],
);
list($maxMessage, $minMessage) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -1103,23 +1103,23 @@ protected function buildLimitBar()
}
// Prepare the context for the capacity bar.
- if (!empty($limit))
- {
+ if (!empty($limit)) {
$bar = round((User::$me->messages * 100) / $limit, 1);
- Utils::$context['limit_bar'] = array(
+ Utils::$context['limit_bar'] = [
'messages' => User::$me->messages,
'allowed' => $limit,
'percent' => $bar,
'bar' => min(100, (int) $bar),
'text' => sprintf(Lang::$txt['pm_currently_using'], User::$me->messages, $bar),
- );
+ ];
}
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\PersonalMessage::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\PersonalMessage::exportStatic')) {
PersonalMessage::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Post.php b/Sources/Actions/Post.php
index 4f23b5b1ba..6315ddd292 100644
--- a/Sources/Actions/Post.php
+++ b/Sources/Actions/Post.php
@@ -13,13 +13,13 @@
namespace SMF\Actions;
-use SMF\BackwardCompatibility;
-
use SMF\Attachment;
-use SMF\BrowserDetector;
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Board;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\Draft;
use SMF\Editor;
use SMF\ErrorHandler;
@@ -36,9 +36,6 @@
use SMF\User;
use SMF\Utils;
use SMF\Verifier;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
-use SMF\Search\SearchApi;
/**
* This class handles posting and modifying replies and new topics.
@@ -52,12 +49,11 @@ class Post implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'post' => 'Post',
+ ],
+ ];
/*****************
* Class constants
@@ -66,9 +62,9 @@ class Post implements ActionInterface
/**
* Constants to indicate what the user intends to do with this post.
*/
- const INTENT_NEW_TOPIC = 0;
- const INTENT_NEW_REPLY = 1;
- const INTENT_EDIT_POST = 2;
+ public const INTENT_NEW_TOPIC = 0;
+ public const INTENT_NEW_REPLY = 1;
+ public const INTENT_EDIT_POST = 2;
/*******************
* Public properties
@@ -86,7 +82,7 @@ class Post implements ActionInterface
*
* Errors encountered while trying to post.
*/
- public array $errors = array();
+ public array $errors = [];
/**
* @var array
@@ -96,7 +92,7 @@ class Post implements ActionInterface
* errors are like warnings that let them know that something with
* their post isn't right.
*/
- public array $minor_errors = array(
+ public array $minor_errors = [
'not_approved',
'new_replies',
'old_topic',
@@ -107,7 +103,7 @@ class Post implements ActionInterface
'topic_stickied',
'topic_unstickied',
'cannot_post_attachment',
- );
+ ];
/**
* @var string
@@ -153,9 +149,9 @@ class Post implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'show' => 'show',
- );
+ ];
/*********************
* Internal properties
@@ -170,7 +166,7 @@ class Post implements ActionInterface
* of that board. Otherwise, it will contain a list of boards that the user
* is allowed to post in.
*/
- protected array $boards = array();
+ protected array $boards = [];
/**
* @var array
@@ -178,7 +174,7 @@ class Post implements ActionInterface
* A list of categories and boards produced by MessageIndex::getBoardList().
* Not used if a board was specified in the URL parameters.
*/
- protected array $board_list = array();
+ protected array $board_list = [];
/**
* @var bool
@@ -220,16 +216,18 @@ public function execute(): void
$this->can_approve = User::$me->allowedTo('approve_posts');
// If there is an existing topic, load it.
- if ($this->intent !== self::INTENT_NEW_TOPIC)
+ if ($this->intent !== self::INTENT_NEW_TOPIC) {
$this->loadTopic();
+ }
// Allow mods to add new sub-actions.
- IntegrationHook::call('integrate_post_subactions', array(&self::$subactions));
+ IntegrationHook::call('integrate_post_subactions', [&self::$subactions]);
- $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);
+ }
}
/**
@@ -248,12 +246,14 @@ public function show(): void
{
Lang::load('Post');
- if (!empty(Config::$modSettings['drafts_post_enabled']))
+ if (!empty(Config::$modSettings['drafts_post_enabled'])) {
Lang::load('Drafts');
+ }
// You can't reply with a poll... hacker.
- if (isset($_REQUEST['poll']) && !empty(Topic::$topic_id) && !isset($_REQUEST['msg']))
+ if (isset($_REQUEST['poll']) && !empty(Topic::$topic_id) && !isset($_REQUEST['msg'])) {
unset($_REQUEST['poll']);
+ }
// Posting an event?
Utils::$context['make_event'] = isset($_REQUEST['calendar']);
@@ -264,8 +264,7 @@ public function show(): void
// Where are we posting this (or where might we)?
$this->setBoards();
- if (isset($_REQUEST['xml']))
- {
+ if (isset($_REQUEST['xml'])) {
Utils::$context['sub_template'] = 'post';
// Just in case of an earlier error...
@@ -277,19 +276,18 @@ public function show(): void
$this->loadNotifyPrefs();
// Replying to an existing topic.
- if ($this->intent !== self::INTENT_NEW_TOPIC)
- {
+ if ($this->intent !== self::INTENT_NEW_TOPIC) {
$this->initiateReply();
}
// Starting a new topic.
- else
- {
+ else {
$this->initiateNewTopic();
}
// Don't allow a post if it's locked and you aren't all powerful.
- if ($this->locked && !User::$me->allowedTo('moderate_board'))
+ if ($this->locked && !User::$me->allowedTo('moderate_board')) {
ErrorHandler::fatalLang('topic_locked', false);
+ }
Utils::$context['notify'] = !empty(Utils::$context['notify']);
@@ -300,7 +298,7 @@ public function show(): void
Utils::$context['can_quote'] = empty(Config::$modSettings['disabledBBC']) || !in_array('quote', explode(',', Config::$modSettings['disabledBBC']));
// An array to hold all the attachments for this topic.
- Utils::$context['current_attachments'] = array();
+ Utils::$context['current_attachments'] = [];
// Does the user want to create a poll?
$this->initiatePoll();
@@ -315,18 +313,15 @@ public function show(): void
$this->setResponsePrefix();
// Previewing, modifying, or posting?
- if (isset($_REQUEST['message']) || isset($_REQUEST['quickReply']) || !empty(Utils::$context['post_error']))
- {
+ if (isset($_REQUEST['message']) || isset($_REQUEST['quickReply']) || !empty(Utils::$context['post_error'])) {
$this->showPreview();
}
// Editing a message...
- elseif ($this->intent === self::INTENT_EDIT_POST)
- {
+ elseif ($this->intent === self::INTENT_EDIT_POST) {
$this->showEdit();
}
// Posting...
- else
- {
+ else {
$this->showNew();
}
@@ -346,7 +341,7 @@ public function show(): void
$this->setLinktree();
Utils::$context['subject'] = addcslashes($this->form_subject, '"');
- Utils::$context['message'] = str_replace(array('"', '<', '>', ' '), array('"', '<', '>', ' '), $this->form_message);
+ Utils::$context['message'] = str_replace(['"', '<', '>', ' '], ['"', '<', '>', ' '], $this->form_message);
// Are there any drafts to show in the editor?
$this->loadDrafts();
@@ -369,19 +364,19 @@ public function show(): void
Security::checkSubmitOnce('register');
// Mentions
- if (!empty(Config::$modSettings['enable_mentions']) && User::$me->allowedTo('mention'))
- {
- Theme::loadJavaScriptFile('jquery.caret.min.js', array('defer' => true), 'smf_caret');
- Theme::loadJavaScriptFile('jquery.atwho.min.js', array('defer' => true), 'smf_atwho');
- Theme::loadJavaScriptFile('mentions.js', array('defer' => true, 'minimize' => true), 'smf_mentions');
+ if (!empty(Config::$modSettings['enable_mentions']) && User::$me->allowedTo('mention')) {
+ Theme::loadJavaScriptFile('jquery.caret.min.js', ['defer' => true], 'smf_caret');
+ Theme::loadJavaScriptFile('jquery.atwho.min.js', ['defer' => true], 'smf_atwho');
+ Theme::loadJavaScriptFile('mentions.js', ['defer' => true, 'minimize' => true], 'smf_mentions');
}
// Load the drafts.js file
- if (Utils::$context['drafts_autosave'])
- Theme::loadJavaScriptFile('drafts.js', array('defer' => false, 'minimize' => true), 'smf_drafts');
+ if (Utils::$context['drafts_autosave']) {
+ Theme::loadJavaScriptFile('drafts.js', ['defer' => false, 'minimize' => true], 'smf_drafts');
+ }
// quotedText.js
- Theme::loadJavaScriptFile('quotedText.js', array('defer' => true, 'minimize' => true), 'smf_quotedText');
+ Theme::loadJavaScriptFile('quotedText.js', ['defer' => true, 'minimize' => true], 'smf_quotedText');
// Knowing the current board ID might be handy.
Theme::addInlineJavaScript('
@@ -391,8 +386,9 @@ public function show(): void
$this->setupPostingFields();
// Finally, load the template.
- if (!isset($_REQUEST['xml']))
+ if (!isset($_REQUEST['xml'])) {
Theme::loadTemplate('Post');
+ }
IntegrationHook::call('integrate_post_end');
}
@@ -408,8 +404,9 @@ public function show(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -427,7 +424,7 @@ public static function call(): void
*
* Needed to allow old mods to pass $post_errors as a function parameter.
*/
- public static function post($post_errors = array()): void
+ public static function post($post_errors = []): void
{
self::load();
self::$obj->errors = (array) $post_errors;
@@ -460,24 +457,23 @@ protected function __construct()
*/
protected function getTopicSummary(): void
{
- if (empty(Topic::$info->id) || empty(Config::$modSettings['topicSummaryPosts']))
+ if (empty(Topic::$info->id) || empty(Config::$modSettings['topicSummaryPosts'])) {
return;
+ }
- if (isset($_REQUEST['xml']))
- {
+ if (isset($_REQUEST['xml'])) {
$limit = '
LIMIT ' . (empty(Utils::$context['new_replies']) ? '0' : Utils::$context['new_replies']);
- }
- else
- {
+ } else {
$limit = empty(Config::$modSettings['topicSummaryPosts']) ? '' : '
LIMIT ' . (int) Config::$modSettings['topicSummaryPosts'];
}
// If you're modifying, get only those posts before the current one. (otherwise get all.)
- Utils::$context['previous_posts'] = array();
- $request = Db::$db->query('', '
- SELECT
+ Utils::$context['previous_posts'] = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT
COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time,
m.body, m.smileys_enabled, m.id_msg, m.id_member
FROM {db_prefix}messages AS m
@@ -486,23 +482,23 @@ protected function getTopicSummary(): void
AND m.id_msg < {int:id_msg}' : '') . (!Config::$modSettings['postmod_active'] || $this->can_approve ? '' : '
AND m.approved = {int:approved}') . '
ORDER BY m.id_msg DESC' . $limit,
- array(
+ [
'current_topic' => Topic::$topic_id,
'id_msg' => isset($_REQUEST['msg']) ? (int) $_REQUEST['msg'] : 0,
'approved' => 1,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Censor, BBC, ...
Lang::censorText($row['body']);
$row['body'] = BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], $row['id_msg']);
- IntegrationHook::call('integrate_getTopic_previous_post', array(&$row));
+ IntegrationHook::call('integrate_getTopic_previous_post', [&$row]);
// ...and store.
- Utils::$context['previous_posts'][] = array(
+ Utils::$context['previous_posts'][] = [
'counter' => $this->counter++,
'poster' => $row['poster_name'],
'message' => $row['body'],
@@ -511,10 +507,11 @@ protected function getTopicSummary(): void
'id' => $row['id_msg'],
'is_new' => !empty(Utils::$context['new_replies']),
'is_ignored' => !empty(Config::$modSettings['enable_buddylist']) && !empty(Theme::$current->options['posts_apply_ignore_list']) && in_array($row['id_member'], User::$me->ignoreusers),
- );
+ ];
- if (!empty(Utils::$context['new_replies']))
+ if (!empty(Utils::$context['new_replies'])) {
Utils::$context['new_replies']--;
+ }
}
Db::$db->free_result($request);
}
@@ -527,14 +524,11 @@ protected function getTopicSummary(): void
*/
protected function loadNotifyPrefs(): void
{
- if (!empty(Topic::$info->id))
- {
+ if (!empty(Topic::$info->id)) {
Utils::$context['notify_prefs'] = Topic::$info->getNotificationPrefs();
Utils::$context['auto_notify'] = !empty(Topic::$info->notify_prefs['msg_auto_notify']);
- }
- else
- {
- Utils::$context['notify_prefs'] = Notify::getNotifyPrefs(User::$me->id, array('topic_notify', 'msg_auto_notify'), true);
+ } else {
+ Utils::$context['notify_prefs'] = Notify::getNotifyPrefs(User::$me->id, ['topic_notify', 'msg_auto_notify'], true);
Utils::$context['auto_notify'] = !empty(Utils::$context['notify_prefs']['msg_auto_notify']);
}
@@ -547,33 +541,33 @@ protected function loadNotifyPrefs(): void
protected function setBoards(): void
{
// Not in a board? Fine, but we'll make them pick one eventually.
- if (empty(Board::$info->id) || Utils::$context['make_event'])
- {
+ if (empty(Board::$info->id) || Utils::$context['make_event']) {
// Get ids of all the boards they can post in.
- $post_permissions = array('post_new');
+ $post_permissions = ['post_new'];
- if (Config::$modSettings['postmod_active'])
+ if (Config::$modSettings['postmod_active']) {
$post_permissions[] = 'post_unapproved_topics';
+ }
$this->boards = User::$me->boardsAllowedTo($post_permissions);
- if (empty($this->boards))
+ if (empty($this->boards)) {
ErrorHandler::fatalLang('cannot_post_new', false);
+ }
// Get a list of boards for the select menu
- $boardListOptions = array(
+ $boardListOptions = [
'included_boards' => in_array(0, $this->boards) ? null : $this->boards,
'not_redirection' => true,
'use_permissions' => true,
'selected_board' => !empty(Board::$info->id) ? Board::$info->id : (Utils::$context['make_event'] && !empty(Config::$modSettings['cal_defaultboard']) ? Config::$modSettings['cal_defaultboard'] : $this->boards[0]),
- );
+ ];
$this->board_list = MessageIndex::getBoardList($boardListOptions);
}
// Let's keep things simple for ourselves.
- else
- {
- $this->boards = array(Board::$info->id);
+ else {
+ $this->boards = [Board::$info->id];
}
}
@@ -584,41 +578,42 @@ protected function setBoards(): void
*/
protected function loadTopic(): void
{
- if (empty(Topic::$topic_id) && !empty($_REQUEST['msg']))
- {
- $request = Db::$db->query('', '
- SELECT id_topic
+ if (empty(Topic::$topic_id) && !empty($_REQUEST['msg'])) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic
FROM {db_prefix}messages
WHERE id_msg = {int:msg}
LIMIT 1',
- array(
+ [
'msg' => (int) $_REQUEST['msg'],
- )
+ ],
);
- if (Db::$db->num_rows($request) != 1)
- {
+
+ if (Db::$db->num_rows($request) != 1) {
unset($_REQUEST['msg'], $_POST['msg'], $_GET['msg']);
- }
- else
- {
+ } else {
list(Topic::$topic_id) = Db::$db->fetch_row($request);
}
Db::$db->free_result($request);
}
// We expected a topic, but we don't have one.
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
ErrorHandler::fatalLang('not_a_topic');
+ }
Topic::load(Topic::$topic_id);
// Though the topic should be there, it might have vanished.
- if (empty(Topic::$info->id))
+ if (empty(Topic::$info->id)) {
ErrorHandler::fatalLang('topic_doesnt_exist', 404);
+ }
// Did this topic suddenly move? Just checking...
- if (isset(Board::$info->id) && Topic::$info->id_board != Board::$info->id)
+ if (isset(Board::$info->id) && Topic::$info->id_board != Board::$info->id) {
ErrorHandler::fatalLang('not_a_topic');
+ }
}
/**
@@ -630,47 +625,36 @@ protected function initiateReply(): void
Utils::$context['topic_last_message'] = Topic::$info->id_last_msg;
// If this topic already has a poll, they sure can't add another.
- if (isset($_REQUEST['poll']) && Topic::$info->id_poll > 0)
+ if (isset($_REQUEST['poll']) && Topic::$info->id_poll > 0) {
unset($_REQUEST['poll']);
+ }
// New reply.
- if ($this->intent === self::INTENT_NEW_REPLY)
- {
+ if ($this->intent === self::INTENT_NEW_REPLY) {
// If guests can't post, kick them out.
- if (User::$me->is_guest && !User::$me->allowedTo('post_reply_any') && (!Config::$modSettings['postmod_active'] || !User::$me->allowedTo('post_unapproved_replies_any')))
- {
+ if (User::$me->is_guest && !User::$me->allowedTo('post_reply_any') && (!Config::$modSettings['postmod_active'] || !User::$me->allowedTo('post_unapproved_replies_any'))) {
User::$me->kickIfGuest();
}
// By default the reply will be approved...
$this->becomes_approved = true;
- if (Topic::$info->id_member_started != User::$me->id || User::$me->is_guest)
- {
- if (Config::$modSettings['postmod_active'] && User::$me->allowedTo('post_unapproved_replies_any') && !User::$me->allowedTo('post_reply_any'))
- {
+ if (Topic::$info->id_member_started != User::$me->id || User::$me->is_guest) {
+ if (Config::$modSettings['postmod_active'] && User::$me->allowedTo('post_unapproved_replies_any') && !User::$me->allowedTo('post_reply_any')) {
$this->becomes_approved = false;
- }
- else
- {
+ } else {
User::$me->isAllowedTo('post_reply_any');
}
- }
- elseif (!User::$me->allowedTo('post_reply_any'))
- {
- if (Config::$modSettings['postmod_active'] && ((User::$me->allowedTo('post_unapproved_replies_own') && !User::$me->allowedTo('post_reply_own')) || User::$me->allowedTo('post_unapproved_replies_any')))
- {
+ } elseif (!User::$me->allowedTo('post_reply_any')) {
+ if (Config::$modSettings['postmod_active'] && ((User::$me->allowedTo('post_unapproved_replies_own') && !User::$me->allowedTo('post_reply_own')) || User::$me->allowedTo('post_unapproved_replies_any'))) {
$this->becomes_approved = false;
- }
- else
- {
+ } else {
User::$me->isAllowedTo('post_reply_own');
}
}
}
// Modifying an existing reply.
- else
- {
+ else {
$this->becomes_approved = true;
}
@@ -688,9 +672,8 @@ protected function initiateReply(): void
Utils::$context['sticky'] = isset($_REQUEST['sticky']) ? !empty($_REQUEST['sticky']) : Topic::$info->is_sticky;
// Check whether this is a really old post being bumped...
- if (!empty(Config::$modSettings['oldTopicDays']) && Topic::$info->updated_timestamp + Config::$modSettings['oldTopicDays'] * 86400 < time() && empty(Topic::$info->is_sticky) && !isset($_REQUEST['subject']))
- {
- $this->errors[] = array('old_topic', array(Config::$modSettings['oldTopicDays']));
+ if (!empty(Config::$modSettings['oldTopicDays']) && Topic::$info->updated_timestamp + Config::$modSettings['oldTopicDays'] * 86400 < time() && empty(Topic::$info->is_sticky) && !isset($_REQUEST['subject'])) {
+ $this->errors[] = ['old_topic', [Config::$modSettings['oldTopicDays']]];
}
}
@@ -702,12 +685,9 @@ protected function initiateNewTopic(): void
// @todo Should use JavaScript to hide and show the warning based on the selection in the board select menu
$this->becomes_approved = true;
- if (Config::$modSettings['postmod_active'] && !User::$me->allowedTo('post_new', $this->boards, true) && User::$me->allowedTo('post_unapproved_topics', $this->boards, true))
- {
+ if (Config::$modSettings['postmod_active'] && !User::$me->allowedTo('post_new', $this->boards, true) && User::$me->allowedTo('post_unapproved_topics', $this->boards, true)) {
$this->becomes_approved = false;
- }
- else
- {
+ } else {
User::$me->isAllowedTo('post_new', $this->boards, true);
}
@@ -717,7 +697,7 @@ protected function initiateNewTopic(): void
Utils::$context['sticky'] = !empty($_REQUEST['sticky']);
// What options should we show?
- Utils::$context['can_lock'] = User::$me->allowedTo(array('lock_any', 'lock_own'), $this->boards, true);
+ Utils::$context['can_lock'] = User::$me->allowedTo(['lock_any', 'lock_own'], $this->boards, true);
Utils::$context['can_sticky'] = User::$me->allowedTo('make_sticky', $this->boards, true);
Utils::$context['can_move'] = User::$me->allowedTo('move_any', $this->boards, true);
Utils::$context['can_announce'] = User::$me->allowedTo('announce_topic', $this->boards, true) && $this->becomes_approved;
@@ -730,10 +710,10 @@ protected function initiateNewTopic(): void
protected function initiatePoll(): void
{
// Check the users permissions - is the user allowed to add or post a poll?
- if (!isset($_REQUEST['poll']) || Config::$modSettings['pollMode'] != '1')
- {
+ if (!isset($_REQUEST['poll']) || Config::$modSettings['pollMode'] != '1') {
unset($_REQUEST['poll'], $_POST['poll'], $_GET['poll']);
Utils::$context['make_poll'] = false;
+
return;
}
@@ -751,19 +731,23 @@ protected function initiatePoll(): void
*/
protected function initiateEvent(): void
{
- if (empty(Utils::$context['make_event']))
+ if (empty(Utils::$context['make_event'])) {
return;
+ }
// They might want to pick a board.
- if (!isset(Utils::$context['current_board']))
+ if (!isset(Utils::$context['current_board'])) {
Utils::$context['current_board'] = 0;
+ }
// Start loading up the event info.
- if (isset($_REQUEST['eventid']))
+ if (isset($_REQUEST['eventid'])) {
list(Utils::$context['event']) = Event::load((int) $_REQUEST['eventid']);
+ }
- if (!(Utils::$context['event'] instanceof Event))
+ if (!(Utils::$context['event'] instanceof Event)) {
Utils::$context['event'] = new Event(-1);
+ }
// Permissions check!
User::$me->isAllowedTo('calendar_post');
@@ -772,27 +756,22 @@ protected function initiateEvent(): void
$time_string = Time::getShortTimeFormat();
// Editing an event? (but NOT previewing!?)
- if (empty(Utils::$context['event']->new) && !isset($_REQUEST['subject']))
- {
+ if (empty(Utils::$context['event']->new) && !isset($_REQUEST['subject'])) {
// If the user doesn't have permission to edit the post in this topic, redirect them.
- if ((empty(Topic::$info->id_member_started) || Topic::$info->id_member_started != User::$me->id || !User::$me->allowedTo('modify_own')) && !User::$me->allowedTo('modify_any'))
- {
+ if ((empty(Topic::$info->id_member_started) || Topic::$info->id_member_started != User::$me->id || !User::$me->allowedTo('modify_own')) && !User::$me->allowedTo('modify_any')) {
$calendar_action = Calendar::load();
$calendar_action->subaction = 'post';
$calendar_action->execute();
+
return;
}
- }
- else
- {
+ } else {
// Make sure the year and month are in the valid range.
- if (Utils::$context['event']->month < 1 || Utils::$context['event']->month > 12)
- {
+ if (Utils::$context['event']->month < 1 || Utils::$context['event']->month > 12) {
ErrorHandler::fatalLang('invalid_month', false);
}
- if (Utils::$context['event']->year < Config::$modSettings['cal_minyear'] || Utils::$context['event']->year > Config::$modSettings['cal_maxyear'])
- {
+ if (Utils::$context['event']->year < Config::$modSettings['cal_minyear'] || Utils::$context['event']->year > Config::$modSettings['cal_maxyear']) {
ErrorHandler::fatalLang('invalid_year', false);
}
@@ -800,8 +779,7 @@ protected function initiateEvent(): void
}
// An all day event? Set up some nice defaults in case the user wants to change that
- if (Utils::$context['event']->allday == true)
- {
+ if (Utils::$context['event']->allday == true) {
Utils::$context['event']->tz = User::getTimezone();
Utils::$context['event']->start->modify(Time::create('now')->format('%H:%M:%S'));
Utils::$context['event']->end->modify(Time::create('now + 1 hour')->format('%H:%M:%S'));
@@ -833,42 +811,42 @@ protected function initiateEvent(): void
protected function checkForNewReplies(): void
{
// Only check if the user is trying to submit a new reply to a topic.
- if (!empty($_REQUEST['msg']) || empty(Topic::$info->id))
+ if (!empty($_REQUEST['msg']) || empty(Topic::$info->id)) {
return;
+ }
// Only check if the user wants to be warned about new replies.
- if (!empty(Theme::$current->options['no_new_reply_warning']))
+ if (!empty(Theme::$current->options['no_new_reply_warning'])) {
return;
+ }
// Is the last post when they started writing still the last post now?
- if (!isset($_REQUEST['last_msg']) || Topic::$info->id_last_msg <= $_REQUEST['last_msg'])
+ if (!isset($_REQUEST['last_msg']) || Topic::$info->id_last_msg <= $_REQUEST['last_msg']) {
return;
+ }
// Figure out how many new replies were made while the user was writing.
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}messages
WHERE id_topic = {int:current_topic}
AND id_msg > {int:last_msg}' . (!Config::$modSettings['postmod_active'] || $this->can_approve ? '' : '
AND approved = {int:approved}') . '
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$info->id,
'last_msg' => (int) $_REQUEST['last_msg'],
'approved' => 1,
- )
+ ],
);
list(Utils::$context['new_replies']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- if (!empty(Utils::$context['new_replies']))
- {
- if (Utils::$context['new_replies'] == 1)
- {
+ if (!empty(Utils::$context['new_replies'])) {
+ if (Utils::$context['new_replies'] == 1) {
Lang::$txt['error_new_replies'] = isset($_GET['last_msg']) ? Lang::$txt['error_new_reply_reading'] : Lang::$txt['error_new_reply'];
- }
- else
- {
+ } else {
Lang::$txt['error_new_replies'] = sprintf(isset($_GET['last_msg']) ? Lang::$txt['error_new_replies_reading'] : Lang::$txt['error_new_replies'], Utils::$context['new_replies']);
}
@@ -883,14 +861,10 @@ protected function checkForNewReplies(): void
*/
protected function setResponsePrefix(): void
{
- if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix')))
- {
- if (Lang::$default === User::$me->language)
- {
+ if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix'))) {
+ if (Lang::$default === User::$me->language) {
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
- }
- else
- {
+ } else {
Lang::load('index', Lang::$default, false);
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
Lang::load('index');
@@ -904,25 +878,26 @@ protected function setResponsePrefix(): void
*/
protected function showPreview(): void
{
- if (isset($_REQUEST['quickReply']))
+ if (isset($_REQUEST['quickReply'])) {
$_REQUEST['message'] = $_REQUEST['quickReply'];
+ }
// Validate inputs.
- if (empty(Utils::$context['post_error']))
- {
+ if (empty(Utils::$context['post_error'])) {
// This means they didn't click Post and get an error.
$really_previewing = true;
- }
- else
- {
- if (!isset($_REQUEST['subject']))
+ } else {
+ if (!isset($_REQUEST['subject'])) {
$_REQUEST['subject'] = '';
+ }
- if (!isset($_REQUEST['message']))
+ if (!isset($_REQUEST['message'])) {
$_REQUEST['message'] = '';
+ }
- if (!isset($_REQUEST['icon']))
+ if (!isset($_REQUEST['icon'])) {
$_REQUEST['icon'] = 'xx';
+ }
// They are previewing if they asked to preview (i.e. came from quick reply).
$really_previewing = !empty($_POST['preview']);
@@ -934,58 +909,57 @@ protected function showPreview(): void
Utils::$context['can_announce'] &= $this->becomes_approved;
// Set up the inputs for the form.
- $this->form_subject = strtr(Utils::htmlspecialchars($_REQUEST['subject']), array("\r" => '', "\n" => '', "\t" => ''));
+ $this->form_subject = strtr(Utils::htmlspecialchars($_REQUEST['subject']), ["\r" => '', "\n" => '', "\t" => '']);
$this->form_message = Utils::htmlspecialchars($_REQUEST['message'], ENT_QUOTES);
// Make sure the subject isn't too long - taking into account special characters.
- if (Utils::entityStrlen($this->form_subject) > 100)
+ if (Utils::entityStrlen($this->form_subject) > 100) {
$this->form_subject = Utils::entitySubstr($this->form_subject, 0, 100);
+ }
- if (isset($_REQUEST['poll']))
- {
+ if (isset($_REQUEST['poll'])) {
Utils::$context['question'] = isset($_REQUEST['question']) ? Utils::htmlspecialchars(trim($_REQUEST['question'])) : '';
- Utils::$context['choices'] = array();
+ Utils::$context['choices'] = [];
$choice_id = 0;
- $_POST['options'] = empty($_POST['options']) ? array() : Utils::htmlspecialcharsRecursive($_POST['options']);
- foreach ($_POST['options'] as $option)
- {
- if (trim($option) == '')
+ $_POST['options'] = empty($_POST['options']) ? [] : Utils::htmlspecialcharsRecursive($_POST['options']);
+
+ foreach ($_POST['options'] as $option) {
+ if (trim($option) == '') {
continue;
+ }
- Utils::$context['choices'][] = array(
+ Utils::$context['choices'][] = [
'id' => $choice_id++,
'number' => $choice_id,
'label' => $option,
- 'is_last' => false
- );
+ 'is_last' => false,
+ ];
}
// One empty option for those with js disabled...I know are few... :P
- Utils::$context['choices'][] = array(
+ Utils::$context['choices'][] = [
'id' => $choice_id++,
'number' => $choice_id,
'label' => '',
- 'is_last' => false
- );
+ 'is_last' => false,
+ ];
- if (count(Utils::$context['choices']) < 2)
- {
- Utils::$context['choices'][] = array(
+ if (count(Utils::$context['choices']) < 2) {
+ Utils::$context['choices'][] = [
'id' => $choice_id++,
'number' => $choice_id,
'label' => '',
- 'is_last' => false
- );
+ 'is_last' => false,
+ ];
}
Utils::$context['last_choice_id'] = $choice_id;
Utils::$context['choices'][count(Utils::$context['choices']) - 1]['is_last'] = true;
}
// Are you... a guest?
- if (User::$me->is_guest)
- {
+ if (User::$me->is_guest) {
$_REQUEST['guestname'] = !isset($_REQUEST['guestname']) ? '' : trim($_REQUEST['guestname']);
$_REQUEST['email'] = !isset($_REQUEST['email']) ? '' : trim($_REQUEST['email']);
@@ -998,8 +972,7 @@ protected function showPreview(): void
}
// Only show the preview stuff if they hit Preview.
- if (($really_previewing == true || isset($_REQUEST['xml'])) && !isset($_REQUEST['save_draft']))
- {
+ if (($really_previewing == true || isset($_REQUEST['xml'])) && !isset($_REQUEST['save_draft'])) {
// Set up the preview message and subject and censor them...
Utils::$context['preview_message'] = $this->form_message;
Msg::preparsecode($this->form_message, true);
@@ -1009,23 +982,19 @@ protected function showPreview(): void
Utils::$context['preview_message'] = BBCodeParser::load()->parse(Utils::$context['preview_message'], !isset($_REQUEST['ns']));
Lang::censorText(Utils::$context['preview_message']);
- if ($this->form_subject != '')
- {
+ if ($this->form_subject != '') {
Utils::$context['preview_subject'] = $this->form_subject;
Lang::censorText(Utils::$context['preview_subject']);
- }
- else
- {
+ } else {
Utils::$context['preview_subject'] = '' . Lang::$txt['no_subject'] . '';
}
- IntegrationHook::call('integrate_preview_post', array(&$this->form_message, &$this->form_subject));
+ IntegrationHook::call('integrate_preview_post', [&$this->form_message, &$this->form_subject]);
// Protect any CDATA blocks.
- if (isset($_REQUEST['xml']))
- {
- Utils::$context['preview_message'] = strtr(Utils::$context['preview_message'], array(']]>' => ']]]]>'));
+ if (isset($_REQUEST['xml'])) {
+ Utils::$context['preview_message'] = strtr(Utils::$context['preview_message'], [']]>' => ']]]]>']);
}
}
@@ -1033,7 +1002,7 @@ protected function showPreview(): void
Utils::$context['notify'] = !empty($_REQUEST['notify']);
Utils::$context['use_smileys'] = !isset($_REQUEST['ns']);
- Utils::$context['icon'] = isset($_REQUEST['icon']) ? preg_replace('~[\./\\\\*\':"<>]~', '', $_REQUEST['icon']) : 'xx';
+ Utils::$context['icon'] = isset($_REQUEST['icon']) ? preg_replace('~[./\\\\*\':"<>]~', '', $_REQUEST['icon']) : 'xx';
// Set the destination action for submission.
Utils::$context['destination'] = 'post2;start=' . $_REQUEST['start'] . (isset($_REQUEST['msg']) ? ';msg=' . $_REQUEST['msg'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'] : '') . (isset($_REQUEST['poll']) ? ';poll' : '');
@@ -1041,11 +1010,11 @@ protected function showPreview(): void
Utils::$context['submit_label'] = isset($_REQUEST['msg']) ? Lang::$txt['save'] : Lang::$txt['post'];
// Previewing an edit?
- if (isset($_REQUEST['msg']) && !empty(Topic::$info->id))
- {
+ if (isset($_REQUEST['msg']) && !empty(Topic::$info->id)) {
// Get the existing message. Previewing.
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
m.id_member, m.modified_time, m.smileys_enabled, m.body,
m.poster_name, m.poster_email, m.subject, m.icon, m.approved,
t.id_member_started AS id_member_poster,
@@ -1055,76 +1024,63 @@ protected function showPreview(): void
LEFT JOIN {db_prefix}log_actions AS log ON (m.id_topic = log.id_topic AND log.action = {string:announce_action})
WHERE m.id_msg = {int:id_msg}
AND m.id_topic = {int:current_topic}',
- array(
+ [
'current_topic' => Topic::$info->id,
'id_msg' => $_REQUEST['msg'],
'announce_action' => 'announce_topic',
- )
+ ],
);
+
// The message they were trying to edit was most likely deleted.
// @todo Change this error message?
- if (Db::$db->num_rows($request) == 0)
- {
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('no_board', false);
}
$row = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
- if ($row['id_member'] == User::$me->id && !User::$me->allowedTo('modify_any'))
- {
+ if ($row['id_member'] == User::$me->id && !User::$me->allowedTo('modify_any')) {
// Give an extra five minutes over the disable time threshold, so they can type - assuming the post is public.
- if ($row['approved'] && !empty(Config::$modSettings['edit_disable_time']) && $row['poster_time'] + (Config::$modSettings['edit_disable_time'] + 5) * 60 < time())
- {
+ if ($row['approved'] && !empty(Config::$modSettings['edit_disable_time']) && $row['poster_time'] + (Config::$modSettings['edit_disable_time'] + 5) * 60 < time()) {
ErrorHandler::fatalLang('modify_post_time_passed', false);
- }
- elseif ($row['id_member_poster'] == User::$me->id && !User::$me->allowedTo('modify_own'))
- {
+ } elseif ($row['id_member_poster'] == User::$me->id && !User::$me->allowedTo('modify_own')) {
User::$me->isAllowedTo('modify_replies');
- }
- else
- {
+ } else {
User::$me->isAllowedTo('modify_own');
}
- }
- elseif ($row['id_member_poster'] == User::$me->id && !User::$me->allowedTo('modify_any'))
- {
+ } elseif ($row['id_member_poster'] == User::$me->id && !User::$me->allowedTo('modify_any')) {
User::$me->isAllowedTo('modify_replies');
- }
- else
- {
+ } else {
User::$me->isAllowedTo('modify_any');
}
- if (Utils::$context['can_announce'] && !empty($row['id_action']) && $row['id_first_msg'] == $_REQUEST['msg'])
- {
+ if (Utils::$context['can_announce'] && !empty($row['id_action']) && $row['id_first_msg'] == $_REQUEST['msg']) {
Lang::load('Errors');
Utils::$context['post_error']['already_announced'] = Lang::$txt['error_topic_already_announced'];
}
- if (!empty(Config::$modSettings['attachmentEnable']))
- {
+ if (!empty(Config::$modSettings['attachmentEnable'])) {
Utils::$context['current_attachments'] = Attachment::loadByMsg($_REQUEST['msg'], Attachment::APPROVED_ANY);
}
// Allow moderators to change names....
- if (User::$me->allowedTo('moderate_forum') && !empty(Topic::$info->id))
- {
- $request = Db::$db->query('', '
- SELECT id_member, poster_name, poster_email
+ if (User::$me->allowedTo('moderate_forum') && !empty(Topic::$info->id)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, poster_name, poster_email
FROM {db_prefix}messages
WHERE id_msg = {int:id_msg}
AND id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$info->id,
'id_msg' => (int) $_REQUEST['msg'],
- )
+ ],
);
$row = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
- if (empty($row['id_member']))
- {
+ if (empty($row['id_member'])) {
Utils::$context['name'] = Utils::htmlspecialchars($row['poster_name']);
Utils::$context['email'] = Utils::htmlspecialchars($row['poster_email']);
}
@@ -1145,8 +1101,9 @@ protected function showEdit(): void
$_REQUEST['msg'] = (int) $_REQUEST['msg'];
// Get the existing message. Editing.
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
m.id_member, m.modified_time, m.modified_name, m.modified_reason, m.smileys_enabled, m.body,
m.poster_name, m.poster_email, m.subject, m.icon, m.approved,
t.id_member_started AS id_member_poster,
@@ -1156,54 +1113,42 @@ protected function showEdit(): void
LEFT JOIN {db_prefix}log_actions AS log ON (m.id_topic = log.id_topic AND log.action = {string:announce_action})
WHERE m.id_msg = {int:id_msg}
AND m.id_topic = {int:current_topic}',
- array(
+ [
'current_topic' => Topic::$info->id,
'id_msg' => $_REQUEST['msg'],
'announce_action' => 'announce_topic',
- )
+ ],
);
+
// The message they were trying to edit was most likely deleted.
- if (Db::$db->num_rows($request) == 0)
- {
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('no_message', false);
}
$row = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
- if ($row['id_member'] == User::$me->id && !User::$me->allowedTo('modify_any'))
- {
+ if ($row['id_member'] == User::$me->id && !User::$me->allowedTo('modify_any')) {
// Give an extra five minutes over the disable time threshold, so they can type - assuming the post is public.
- if ($row['approved'] && !empty(Config::$modSettings['edit_disable_time']) && $row['poster_time'] + (Config::$modSettings['edit_disable_time'] + 5) * 60 < time())
- {
+ if ($row['approved'] && !empty(Config::$modSettings['edit_disable_time']) && $row['poster_time'] + (Config::$modSettings['edit_disable_time'] + 5) * 60 < time()) {
ErrorHandler::fatalLang('modify_post_time_passed', false);
- }
- elseif ($row['id_member_poster'] == User::$me->id && !User::$me->allowedTo('modify_own'))
- {
+ } elseif ($row['id_member_poster'] == User::$me->id && !User::$me->allowedTo('modify_own')) {
User::$me->isAllowedTo('modify_replies');
- }
- else
- {
+ } else {
User::$me->isAllowedTo('modify_own');
}
- }
- elseif ($row['id_member_poster'] == User::$me->id && !User::$me->allowedTo('modify_any'))
- {
+ } elseif ($row['id_member_poster'] == User::$me->id && !User::$me->allowedTo('modify_any')) {
User::$me->isAllowedTo('modify_replies');
- }
- else
- {
+ } else {
User::$me->isAllowedTo('modify_any');
}
- if (Utils::$context['can_announce'] && !empty($row['id_action']) && $row['id_first_msg'] == $_REQUEST['msg'])
- {
+ if (Utils::$context['can_announce'] && !empty($row['id_action']) && $row['id_first_msg'] == $_REQUEST['msg']) {
Lang::load('Errors');
Utils::$context['post_error']['already_announced'] = Lang::$txt['error_topic_already_announced'];
}
// When was it last modified?
- if (!empty($row['modified_time']))
- {
+ if (!empty($row['modified_time'])) {
Utils::$context['last_modified'] = Time::create('@' . $row['modified_time'])->format();
Utils::$context['last_modified_reason'] = Lang::censorText($row['modified_reason']);
Utils::$context['last_modified_text'] = sprintf(Lang::$txt['last_edit_by'], Utils::$context['last_modified'], $row['modified_name']) . empty($row['modified_reason']) ? '' : ' ' . Lang::$txt['last_edit_reason'] . ': ' . $row['modified_reason'];
@@ -1220,18 +1165,17 @@ protected function showEdit(): void
Utils::$context['icon'] = $row['icon'];
// Leave the approval checkbox unchecked by default for unapproved messages.
- if (!$row['approved'] && !empty(Utils::$context['show_approval']))
+ if (!$row['approved'] && !empty(Utils::$context['show_approval'])) {
Utils::$context['show_approval'] = 1;
+ }
// Load up 'em attachments!
- if (!empty(Config::$modSettings['attachmentEnable']))
- {
+ if (!empty(Config::$modSettings['attachmentEnable'])) {
Utils::$context['current_attachments'] = Attachment::loadByMsg($_REQUEST['msg'], Attachment::APPROVED_ANY);
}
// Allow moderators to change names....
- if (User::$me->allowedTo('moderate_forum') && empty($row['id_member']))
- {
+ if (User::$me->allowedTo('moderate_forum') && empty($row['id_member'])) {
Utils::$context['name'] = Utils::htmlspecialchars($row['poster_name']);
Utils::$context['email'] = Utils::htmlspecialchars($row['poster_email']);
}
@@ -1251,21 +1195,20 @@ protected function showNew(): void
Utils::$context['use_smileys'] = true;
Utils::$context['icon'] = 'xx';
- if (User::$me->is_guest)
- {
- Utils::$context['name'] = isset($_SESSION['guest_name']) ? $_SESSION['guest_name'] : '';
- Utils::$context['email'] = isset($_SESSION['guest_email']) ? $_SESSION['guest_email'] : '';
+ if (User::$me->is_guest) {
+ Utils::$context['name'] = $_SESSION['guest_name'] ?? '';
+ Utils::$context['email'] = $_SESSION['guest_email'] ?? '';
}
Utils::$context['destination'] = 'post2;start=' . $_REQUEST['start'] . (isset($_REQUEST['poll']) ? ';poll' : '');
Utils::$context['submit_label'] = Lang::$txt['post'];
// Posting a quoted reply?
- if (!empty(Topic::$info->id) && !empty($_REQUEST['quote']))
- {
+ if (!empty(Topic::$info->id) && !empty($_REQUEST['quote'])) {
// Make sure they _can_ quote this post, and if so get it.
- $request = Db::$db->query('', '
- SELECT m.subject, COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.body
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.subject, COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.body
FROM {db_prefix}messages AS m
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (!Config::$modSettings['postmod_active'] || $this->can_approve ? '' : '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)') . '
@@ -1274,21 +1217,20 @@ protected function showNew(): void
AND m.approved = {int:is_approved}
AND t.approved = {int:is_approved}') . '
LIMIT 1',
- array(
+ [
'id_msg' => (int) $_REQUEST['quote'],
'is_approved' => 1,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('quoted_post_deleted', false);
}
list($this->form_subject, $mname, $mdate, $this->form_message) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Add 'Re: ' to the front of the quoted subject.
- if (trim(Utils::$context['response_prefix']) != '' && Utils::entityStrpos($this->form_subject, trim(Utils::$context['response_prefix'])) !== 0)
- {
+ if (trim(Utils::$context['response_prefix']) != '' && Utils::entityStrpos($this->form_subject, trim(Utils::$context['response_prefix'])) !== 0) {
$this->form_subject = Utils::$context['response_prefix'] . $this->form_subject;
}
@@ -1297,22 +1239,20 @@ protected function showNew(): void
Lang::censorText($this->form_subject);
// But if it's in HTML world, turn them into htmlspecialchar's so they can be edited!
- if (strpos($this->form_message, '[html]') !== false)
- {
+ if (strpos($this->form_message, '[html]') !== false) {
$parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $this->form_message, -1, PREG_SPLIT_DELIM_CAPTURE);
- for ($i = 0, $n = count($parts); $i < $n; $i++)
- {
+ for ($i = 0, $n = count($parts); $i < $n; $i++) {
// It goes 0 = outside, 1 = begin tag, 2 = inside, 3 = close tag, repeat.
- if ($i % 4 == 0)
+ if ($i % 4 == 0) {
$parts[$i] = preg_replace_callback(
'~\[html\](.+?)\[/html\]~is',
- function($m)
- {
- return '[html]' . preg_replace('~ ~i', '<br /> ', "$m[1]") . '[/html]';
+ function ($m) {
+ return '[html]' . preg_replace('~ ~i', '<br /> ', "{$m[1]}") . '[/html]';
},
- $parts[$i]
+ $parts[$i],
);
+ }
}
$this->form_message = implode('', $parts);
@@ -1321,23 +1261,20 @@ function($m)
$this->form_message = preg_replace('~ ~i', "\n", $this->form_message);
// Remove any nested quotes, if necessary.
- if (!empty(Config::$modSettings['removeNestedQuotes']))
- {
- $this->form_message = preg_replace(array('~\n?\[quote.*?\].+?\[/quote\]\n?~is', '~^\n~', '~\[/quote\]~'), '', $this->form_message);
+ if (!empty(Config::$modSettings['removeNestedQuotes'])) {
+ $this->form_message = preg_replace(['~\n?\[quote.*?\].+?\[/quote\]\n?~is', '~^\n~', '~\[/quote\]~'], '', $this->form_message);
}
// Add a quote string on the front and end.
$this->form_message = '[quote author=' . $mname . ' link=msg=' . (int) $_REQUEST['quote'] . ' date=' . $mdate . ']' . "\n" . rtrim($this->form_message) . "\n" . '[/quote]';
}
// Posting a reply without a quote?
- elseif (!empty(Topic::$info->id) && empty($_REQUEST['quote']))
- {
+ elseif (!empty(Topic::$info->id) && empty($_REQUEST['quote'])) {
// Get the first message's subject.
$this->form_subject = Topic::$info->subject;
// Add 'Re: ' to the front of the subject.
- if (trim(Utils::$context['response_prefix']) != '' && $this->form_subject != '' && Utils::entityStrpos($this->form_subject, trim(Utils::$context['response_prefix'])) !== 0)
- {
+ if (trim(Utils::$context['response_prefix']) != '' && $this->form_subject != '' && Utils::entityStrpos($this->form_subject, trim(Utils::$context['response_prefix'])) !== 0) {
$this->form_subject = Utils::$context['response_prefix'] . $this->form_subject;
}
@@ -1345,10 +1282,8 @@ function($m)
Lang::censorText($this->form_subject);
$this->form_message = '';
- }
- else
- {
- $this->form_subject = isset($_GET['subject']) ? $_GET['subject'] : '';
+ } else {
+ $this->form_subject = $_GET['subject'] ?? '';
$this->form_message = '';
}
}
@@ -1359,132 +1294,115 @@ function($m)
protected function showAttachments(): void
{
// Clear out prior attachment activity when starting afresh
- if (empty($_REQUEST['message']) && empty($_REQUEST['preview']) && !empty($_SESSION['already_attached']))
- {
- foreach ($_SESSION['already_attached'] as $attachID => $attachment)
- Attachment::remove(array('id_attach' => $attachID));
+ if (empty($_REQUEST['message']) && empty($_REQUEST['preview']) && !empty($_SESSION['already_attached'])) {
+ foreach ($_SESSION['already_attached'] as $attachID => $attachment) {
+ Attachment::remove(['id_attach' => $attachID]);
+ }
unset($_SESSION['already_attached']);
}
Utils::$context['can_post_attachment'] = !empty(Config::$modSettings['attachmentEnable']) && Config::$modSettings['attachmentEnable'] == 1 && (User::$me->allowedTo('post_attachment', $this->boards, true) || (Config::$modSettings['postmod_active'] && User::$me->allowedTo('post_unapproved_attachments', $this->boards, true)));
- if (Utils::$context['can_post_attachment'])
- {
+ if (Utils::$context['can_post_attachment']) {
// If there are attachments, calculate the total size and how many.
Utils::$context['attachments']['total_size'] = 0;
Utils::$context['attachments']['quantity'] = 0;
// If this isn't a new post, check the current attachments.
- if (isset($_REQUEST['msg']))
- {
+ if (isset($_REQUEST['msg'])) {
Utils::$context['attachments']['quantity'] = count(Utils::$context['current_attachments']);
- foreach (Utils::$context['current_attachments'] as $attachment)
+ foreach (Utils::$context['current_attachments'] as $attachment) {
Utils::$context['attachments']['total_size'] += $attachment['size'];
+ }
}
// A bit of house keeping first.
- if (!empty($_SESSION['temp_attachments']) && count($_SESSION['temp_attachments']) == 1)
+ if (!empty($_SESSION['temp_attachments']) && count($_SESSION['temp_attachments']) == 1) {
unset($_SESSION['temp_attachments']);
+ }
- if (!empty($_SESSION['temp_attachments']))
- {
+ if (!empty($_SESSION['temp_attachments'])) {
// Is this a request to delete them?
- if (isset($_GET['delete_temp']))
- {
- foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
- {
- if (strpos($attachID, 'post_tmp_' . User::$me->id) !== false)
- {
- if (file_exists($attachment['tmp_name']))
+ if (isset($_GET['delete_temp'])) {
+ foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
+ if (strpos($attachID, 'post_tmp_' . User::$me->id) !== false) {
+ if (file_exists($attachment['tmp_name'])) {
unlink($attachment['tmp_name']);
+ }
}
}
$this->errors[] = 'temp_attachments_gone';
- $_SESSION['temp_attachments'] = array();
+ $_SESSION['temp_attachments'] = [];
}
// Hmm, coming in fresh and there are files in session.
- elseif ($this->subaction != 'submit' || !empty($_POST['from_qr']))
- {
+ elseif ($this->subaction != 'submit' || !empty($_POST['from_qr'])) {
// Let's be nice and see if they belong here first.
- if ((empty($_REQUEST['msg']) && empty($_SESSION['temp_attachments']['post']['msg']) && $_SESSION['temp_attachments']['post']['board'] == (!empty(Board::$info->id) ? Board::$info->id : 0)) || (!empty($_REQUEST['msg']) && $_SESSION['temp_attachments']['post']['msg'] == $_REQUEST['msg']))
- {
+ if ((empty($_REQUEST['msg']) && empty($_SESSION['temp_attachments']['post']['msg']) && $_SESSION['temp_attachments']['post']['board'] == (!empty(Board::$info->id) ? Board::$info->id : 0)) || (!empty($_REQUEST['msg']) && $_SESSION['temp_attachments']['post']['msg'] == $_REQUEST['msg'])) {
// See if any files still exist before showing the warning message and the files attached.
- foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
- {
- if (strpos($attachID, 'post_tmp_' . User::$me->id) === false)
+ foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
+ if (strpos($attachID, 'post_tmp_' . User::$me->id) === false) {
continue;
+ }
- if (file_exists($attachment['tmp_name']))
- {
+ if (file_exists($attachment['tmp_name'])) {
$this->errors[] = 'temp_attachments_new';
Utils::$context['files_in_session_warning'] = Lang::$txt['attached_files_in_session'];
unset($_SESSION['temp_attachments']['post']['files']);
break;
}
}
- }
- else
- {
+ } else {
// Since, they don't belong here. Let's inform the user that they exist..
- if (!empty(Topic::$info->id))
- {
+ if (!empty(Topic::$info->id)) {
$delete_url = Config::$scripturl . '?action=post' . (!empty($_REQUEST['msg']) ? (';msg=' . $_REQUEST['msg']) : '') . (!empty($_REQUEST['last_msg']) ? (';last_msg=' . $_REQUEST['last_msg']) : '') . ';topic=' . Topic::$info->id . ';delete_temp';
- }
- else
- {
+ } else {
$delete_url = Config::$scripturl . '?action=post' . (!empty(Board::$info->id) ? ';board=' . Board::$info->id : '') . ';delete_temp';
}
// Compile a list of the files to show the user.
- $file_list = array();
+ $file_list = [];
- foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
- {
- if (strpos($attachID, 'post_tmp_' . User::$me->id) !== false)
+ foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
+ if (strpos($attachID, 'post_tmp_' . User::$me->id) !== false) {
$file_list[] = $attachment['name'];
+ }
}
$_SESSION['temp_attachments']['post']['files'] = $file_list;
$file_list = '' . implode(' ', $file_list) . ' ';
- if (!empty($_SESSION['temp_attachments']['post']['msg']))
- {
+ if (!empty($_SESSION['temp_attachments']['post']['msg'])) {
// We have a message id, so we can link back to the old topic they were trying to edit..
$goback_url = Config::$scripturl . '?action=post' . (!empty($_SESSION['temp_attachments']['post']['msg']) ? (';msg=' . $_SESSION['temp_attachments']['post']['msg']) : '') . (!empty($_SESSION['temp_attachments']['post']['last_msg']) ? (';last_msg=' . $_SESSION['temp_attachments']['post']['last_msg']) : '') . ';topic=' . $_SESSION['temp_attachments']['post']['topic'] . ';additionalOptions';
- $this->errors[] = array('temp_attachments_found', array($delete_url, $goback_url, $file_list));
+ $this->errors[] = ['temp_attachments_found', [$delete_url, $goback_url, $file_list]];
Utils::$context['ignore_temp_attachments'] = true;
- }
- else
- {
- $this->errors[] = array('temp_attachments_lost', array($delete_url, $file_list));
+ } else {
+ $this->errors[] = ['temp_attachments_lost', [$delete_url, $file_list]];
Utils::$context['ignore_temp_attachments'] = true;
}
}
}
- if (!empty(Utils::$context['we_are_history']))
+ if (!empty(Utils::$context['we_are_history'])) {
$this->errors[] = Utils::$context['we_are_history'];
+ }
- foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
- {
- if (isset(Utils::$context['ignore_temp_attachments']) || isset($_SESSION['temp_attachments']['post']['files']))
- {
+ foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
+ if (isset(Utils::$context['ignore_temp_attachments']) || isset($_SESSION['temp_attachments']['post']['files'])) {
break;
}
- if ($attachID != 'initial_error' && strpos($attachID, 'post_tmp_' . User::$me->id) === false)
- {
+ if ($attachID != 'initial_error' && strpos($attachID, 'post_tmp_' . User::$me->id) === false) {
continue;
}
- if ($attachID == 'initial_error')
- {
+ if ($attachID == 'initial_error') {
Lang::$txt['error_attach_initial_error'] = Lang::$txt['attach_no_upload'] . '' . (is_array($attachment) ? vsprintf(Lang::$txt[$attachment[0]], (array) $attachment[1]) : Lang::$txt[$attachment]) . ' ';
$this->errors[] = 'attach_initial_error';
@@ -1495,14 +1413,12 @@ protected function showAttachments(): void
}
// Show any errors which might have occurred.
- if (!empty($attachment['errors']))
- {
+ if (!empty($attachment['errors'])) {
Lang::$txt['error_attach_errors'] = empty(Lang::$txt['error_attach_errors']) ? ' ' : '';
Lang::$txt['error_attach_errors'] .= sprintf(Lang::$txt['attach_warning'], $attachment['name']) . '';
- foreach ($attachment['errors'] as $error)
- {
+ foreach ($attachment['errors'] as $error) {
Lang::$txt['error_attach_errors'] .= (is_array($error) ? vsprintf(Lang::$txt[$error[0]], (array) $error[1]) : Lang::$txt[$error]) . ' ';
}
@@ -1513,15 +1429,15 @@ protected function showAttachments(): void
// Take out the trash.
unset($_SESSION['temp_attachments'][$attachID]);
- if (file_exists($attachment['tmp_name']))
+ if (file_exists($attachment['tmp_name'])) {
unlink($attachment['tmp_name']);
+ }
continue;
}
// More house keeping.
- if (!file_exists($attachment['tmp_name']))
- {
+ if (!file_exists($attachment['tmp_name'])) {
unset($_SESSION['temp_attachments'][$attachID]);
continue;
@@ -1530,12 +1446,11 @@ protected function showAttachments(): void
Utils::$context['attachments']['quantity']++;
Utils::$context['attachments']['total_size'] += $attachment['size'];
- if (!isset(Utils::$context['files_in_session_warning']))
- {
+ if (!isset(Utils::$context['files_in_session_warning'])) {
Utils::$context['files_in_session_warning'] = Lang::$txt['attached_files_in_session'];
}
- Utils::$context['current_attachments'][$attachID] = array(
+ Utils::$context['current_attachments'][$attachID] = [
'name' => $attachment['name'],
'size' => $attachment['size'],
'attachID' => $attachID,
@@ -1544,67 +1459,59 @@ protected function showAttachments(): void
'approved' => 1,
'mime_type' => '',
'thumb' => 0,
- );
+ ];
}
}
}
// Allow user to see previews for all of this post's attachments, even if the post hasn't been submitted yet.
- if (!isset($_SESSION['attachments_can_preview']))
- $_SESSION['attachments_can_preview'] = array();
+ if (!isset($_SESSION['attachments_can_preview'])) {
+ $_SESSION['attachments_can_preview'] = [];
+ }
- if (!empty($_SESSION['already_attached']))
- {
+ if (!empty($_SESSION['already_attached'])) {
$_SESSION['attachments_can_preview'] += array_fill_keys(array_keys($_SESSION['already_attached']), true);
}
- foreach (Utils::$context['current_attachments'] as $attachID => $attachment)
- {
+ foreach (Utils::$context['current_attachments'] as $attachID => $attachment) {
$_SESSION['attachments_can_preview'][$attachID] = true;
- if (!empty($attachment['thumb']))
+ if (!empty($attachment['thumb'])) {
$_SESSION['attachments_can_preview'][$attachment['thumb']] = true;
+ }
}
// Previously uploaded attachments have 2 flavors:
// - Existing post - at this point, now in Utils::$context['current_attachments']
// - Just added, current session only - at this point, now in $_SESSION['already_attached']
// We need to make sure *all* of these are in Utils::$context['current_attachments'], otherwise they won't show in dropzone during edits.
- if (!empty($_SESSION['already_attached']))
- {
+ if (!empty($_SESSION['already_attached'])) {
Utils::$context['current_attachments'] = Attachment::load($_SESSION['already_attached'], Attachment::APPROVED_ANY, Attachment::TYPE_STANDARD);
}
// If the user can post attachments prepare the warning labels.
- if (Utils::$context['can_post_attachment'])
- {
+ if (Utils::$context['can_post_attachment']) {
// If they've unchecked an attachment, they may still want to attach that many more files, but don't allow more than num_allowed_attachments.
Utils::$context['num_allowed_attachments'] = empty(Config::$modSettings['attachmentNumPerPostLimit']) ? PHP_INT_MAX : Config::$modSettings['attachmentNumPerPostLimit'];
Utils::$context['can_post_attachment_unapproved'] = User::$me->allowedTo('post_attachment');
- Utils::$context['attachment_restrictions'] = array();
+ Utils::$context['attachment_restrictions'] = [];
- Utils::$context['allowed_extensions'] = !empty(Config::$modSettings['attachmentCheckExtensions']) ? (strtr(strtolower(Config::$modSettings['attachmentExtensions']), array(',' => ', '))) : '';
+ Utils::$context['allowed_extensions'] = !empty(Config::$modSettings['attachmentCheckExtensions']) ? (strtr(strtolower(Config::$modSettings['attachmentExtensions']), [',' => ', '])) : '';
- $attachmentRestrictionTypes = array('attachmentNumPerPostLimit', 'attachmentPostLimit', 'attachmentSizeLimit');
+ $attachmentRestrictionTypes = ['attachmentNumPerPostLimit', 'attachmentPostLimit', 'attachmentSizeLimit'];
- foreach ($attachmentRestrictionTypes as $type)
- {
- if (!empty(Config::$modSettings[$type]))
- {
+ foreach ($attachmentRestrictionTypes as $type) {
+ if (!empty(Config::$modSettings[$type])) {
Utils::$context['attachment_restrictions'][$type] = sprintf(Lang::$txt['attach_restrict_' . $type . (Config::$modSettings[$type] >= 1024 ? '_MB' : '')], Lang::numberFormat(Config::$modSettings[$type] >= 1024 ? Config::$modSettings[$type] / 1024 : Config::$modSettings[$type], 2));
// Show the max number of attachments if not 0.
- if ($type == 'attachmentNumPerPostLimit')
- {
+ if ($type == 'attachmentNumPerPostLimit') {
Utils::$context['attachment_restrictions'][$type] .= ' (' . sprintf(Lang::$txt['attach_remaining'], max(Config::$modSettings['attachmentNumPerPostLimit'] - Utils::$context['attachments']['quantity'], 0)) . ')';
+ } elseif ($type == 'attachmentPostLimit' && Utils::$context['attachments']['total_size'] > 0) {
+ Utils::$context['attachment_restrictions'][$type] .= ' (' . sprintf(Lang::$txt['attach_available'], round(max(Config::$modSettings['attachmentPostLimit'] - (Utils::$context['attachments']['total_size'] / 1024), 0), 2)) . ')';
}
- elseif ($type == 'attachmentPostLimit' && Utils::$context['attachments']['total_size'] > 0)
- {
- Utils::$context['attachment_restrictions'][$type] .= ' (' . sprintf(Lang::$txt['attach_available'], round(max(Config::$modSettings['attachmentPostLimit'] - (Utils::$context['attachments']['total_size'] / 1024), 0), 2)) . ')';
- }
-
}
}
}
@@ -1612,10 +1519,9 @@ protected function showAttachments(): void
Theme::addInlineJavaScript('
var current_attachments = [];');
- if (!empty(Utils::$context['current_attachments']))
- {
+ if (!empty(Utils::$context['current_attachments'])) {
// Mock files to show already attached files.
- foreach (Utils::$context['current_attachments'] as $key => $mock)
+ foreach (Utils::$context['current_attachments'] as $key => $mock) {
Theme::addInlineJavaScript('
current_attachments.push({
name: ' . Utils::JavaScriptEscape($mock['name']) . ',
@@ -1625,21 +1531,20 @@ protected function showAttachments(): void
type: ' . Utils::JavaScriptEscape(!empty($mock['mime_type']) ? $mock['mime_type'] : '') . ',
thumbID: ' . (!empty($mock['thumb']) ? $mock['thumb'] : 0) . '
});');
+ }
}
// File Upload.
- if (Utils::$context['can_post_attachment'])
- {
+ if (Utils::$context['can_post_attachment']) {
$acceptedFiles = empty(Utils::$context['allowed_extensions']) ? '' : implode(',', array_map(
- function ($val)
- {
+ function ($val) {
return !empty($val) ? ('.' . Utils::htmlTrim($val)) : '';
},
- explode(',', Utils::$context['allowed_extensions'])
+ explode(',', Utils::$context['allowed_extensions']),
));
- Theme::loadJavaScriptFile('dropzone.min.js', array('defer' => true), 'smf_dropzone');
- Theme::loadJavaScriptFile('smf_fileUpload.js', array('defer' => true, 'minimize' => true), 'smf_fileUpload');
+ Theme::loadJavaScriptFile('dropzone.min.js', ['defer' => true], 'smf_dropzone');
+ Theme::loadJavaScriptFile('smf_fileUpload.js', ['defer' => true, 'minimize' => true], 'smf_fileUpload');
Theme::addInlineJavaScript('
$(function() {
smf_fileUpload({
@@ -1671,7 +1576,7 @@ function ($val)
});', true);
}
- Theme::loadCSSFile('attachments.css', array('minimize' => true, 'order_pos' => 450), 'smf_attachments');
+ Theme::loadCSSFile('attachments.css', ['minimize' => true, 'order_pos' => 450], 'smf_attachments');
}
/**
@@ -1681,12 +1586,14 @@ protected function showVerification(): void
{
Utils::$context['require_verification'] = !User::$me->is_mod && !User::$me->is_admin && !empty(Config::$modSettings['posts_require_captcha']) && (User::$me->posts < Config::$modSettings['posts_require_captcha'] || (User::$me->is_guest && Config::$modSettings['posts_require_captcha'] == -1));
- if (Utils::$context['require_verification'])
- $verifier = new Verifier(array('id' => 'post'));
+ if (Utils::$context['require_verification']) {
+ $verifier = new Verifier(['id' => 'post']);
+ }
// If they came from quick reply, and have to enter verification details, give them some notice.
- if (!empty($_REQUEST['from_qr']) && !empty(Utils::$context['require_verification']))
+ if (!empty($_REQUEST['from_qr']) && !empty(Utils::$context['require_verification'])) {
$this->errors[] = 'need_qr_verification';
+ }
}
/**
@@ -1694,33 +1601,32 @@ protected function showVerification(): void
*/
protected function checkForErrors(): void
{
- IntegrationHook::call('integrate_post_errors', array(&$this->errors, &$this->minor_errors, $this->form_message, $this->form_subject));
+ IntegrationHook::call('integrate_post_errors', [&$this->errors, &$this->minor_errors, $this->form_message, $this->form_subject]);
- if (empty($this->errors))
+ if (empty($this->errors)) {
return;
+ }
Lang::load('Errors');
Utils::$context['error_type'] = 'minor';
- foreach ($this->errors as $post_error)
- {
- if (is_array($post_error))
- {
+ foreach ($this->errors as $post_error) {
+ if (is_array($post_error)) {
$post_error_id = $post_error[0];
Utils::$context['post_error'][$post_error_id] = vsprintf(Lang::$txt['error_' . $post_error_id], (array) $post_error[1]);
// If it's not a minor error flag it as such.
- if (!in_array($post_error_id, $this->minor_errors))
+ if (!in_array($post_error_id, $this->minor_errors)) {
Utils::$context['error_type'] = 'serious';
- }
- else
- {
+ }
+ } else {
Utils::$context['post_error'][$post_error] = Lang::$txt['error_' . $post_error];
// If it's not a minor error flag it as such.
- if (!in_array($post_error, $this->minor_errors))
+ if (!in_array($post_error, $this->minor_errors)) {
Utils::$context['error_type'] = 'serious';
+ }
}
}
}
@@ -1730,28 +1636,17 @@ protected function checkForErrors(): void
*/
protected function setPageTitle(): void
{
- if (isset($_REQUEST['poll']))
- {
+ if (isset($_REQUEST['poll'])) {
Utils::$context['page_title'] = Lang::$txt['new_poll'];
- }
- elseif (Utils::$context['make_event'])
- {
+ } elseif (Utils::$context['make_event']) {
Utils::$context['page_title'] = Utils::$context['event']->id == -1 ? Lang::$txt['calendar_post_event'] : Lang::$txt['calendar_edit'];
- }
- elseif (isset($_REQUEST['msg']))
- {
+ } elseif (isset($_REQUEST['msg'])) {
Utils::$context['page_title'] = Lang::$txt['modify_msg'];
- }
- elseif (isset($_REQUEST['subject'], Utils::$context['preview_subject']))
- {
+ } elseif (isset($_REQUEST['subject'], Utils::$context['preview_subject'])) {
Utils::$context['page_title'] = Lang::$txt['preview'] . ' - ' . strip_tags(Utils::$context['preview_subject']);
- }
- elseif (empty(Topic::$info->id))
- {
+ } elseif (empty(Topic::$info->id)) {
Utils::$context['page_title'] = Lang::$txt['start_new_topic'];
- }
- else
- {
+ } else {
Utils::$context['page_title'] = Lang::$txt['post_reply'];
}
}
@@ -1761,20 +1656,17 @@ protected function setPageTitle(): void
*/
protected function setLinktree(): void
{
- if (empty(Topic::$info->id))
- {
- Utils::$context['linktree'][] = array(
- 'name' => ' ' . Lang::$txt['start_new_topic'] . ''
- );
- }
- else
- {
- Utils::$context['linktree'][] = array(
+ if (empty(Topic::$info->id)) {
+ Utils::$context['linktree'][] = [
+ 'name' => ' ' . Lang::$txt['start_new_topic'] . '',
+ ];
+ } else {
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?topic=' . Topic::$info->id . '.' . $_REQUEST['start'],
'name' => $this->form_subject,
'extra_before' => ' ' . Utils::$context['page_title'] . ' (',
- 'extra_after' => ' )'
- );
+ 'extra_after' => ' )',
+ ];
}
}
@@ -1789,14 +1681,12 @@ protected function loadDrafts(): void
Utils::$context['drafts_autosave'] = !empty(Utils::$context['drafts_save']) && !empty(Config::$modSettings['drafts_autosave_enabled']) && User::$me->allowedTo('post_autosave_draft') && !empty(Theme::$current->options['drafts_autosave_enabled']);
// Build a list of drafts that they can load in to the editor
- if (!empty(Utils::$context['drafts_save']))
- {
+ if (!empty(Utils::$context['drafts_save'])) {
Draft::showInEditor(User::$me->id, Topic::$topic_id);
// Has a specific draft has been selected?
// Load its data if there is not a message already in the editor.
- if (isset($_REQUEST['id_draft']) && empty($_POST['subject']) && empty($_POST['message']))
- {
+ if (isset($_REQUEST['id_draft']) && empty($_POST['subject']) && empty($_POST['message'])) {
$draft = new Draft((int) $_REQUEST['id_draft'], true);
$draft->prepare();
}
@@ -1808,19 +1698,19 @@ protected function loadDrafts(): void
*/
protected function loadEditor(): void
{
- new Editor(array(
+ new Editor([
'id' => 'message',
'value' => Utils::$context['message'],
- 'labels' => array(
+ 'labels' => [
'post_button' => Utils::$context['submit_label'],
- ),
+ ],
// add height and width for the editor
'height' => '175px',
'width' => '100%',
// We do XML preview here.
'preview_type' => Editor::PREVIEW_XML,
'required' => true,
- ));
+ ]);
}
/**
@@ -1831,16 +1721,14 @@ protected function setMessageIcons(): void
// Message icons - customized icons are off?
Utils::$context['icons'] = Editor::getMessageIcons(!empty(Board::$info->id) ? Board::$info->id : 0);
- if (!empty(Utils::$context['icons']))
+ if (!empty(Utils::$context['icons'])) {
Utils::$context['icons'][count(Utils::$context['icons']) - 1]['is_last'] = true;
+ }
// Are we starting a poll? if set the poll icon as selected if its available
- if (isset($_REQUEST['poll']))
- {
- foreach (Utils::$context['icons'] as $icons)
- {
- if (isset($icons['value']) && $icons['value'] == 'poll')
- {
+ if (isset($_REQUEST['poll'])) {
+ foreach (Utils::$context['icons'] as $icons) {
+ if (isset($icons['value']) && $icons['value'] == 'poll') {
// if found we are done
Utils::$context['icon'] = 'poll';
break;
@@ -1850,25 +1738,24 @@ protected function setMessageIcons(): void
Utils::$context['icon_url'] = '';
- for ($i = 0, $n = count(Utils::$context['icons']); $i < $n; $i++)
- {
+ for ($i = 0, $n = count(Utils::$context['icons']); $i < $n; $i++) {
Utils::$context['icons'][$i]['selected'] = Utils::$context['icon'] == Utils::$context['icons'][$i]['value'];
- if (Utils::$context['icons'][$i]['selected'])
+ if (Utils::$context['icons'][$i]['selected']) {
Utils::$context['icon_url'] = Utils::$context['icons'][$i]['url'];
+ }
}
- if (empty(Utils::$context['icon_url']))
- {
+ if (empty(Utils::$context['icon_url'])) {
Utils::$context['icon_url'] = Theme::$current->settings[file_exists(Theme::$current->settings['theme_dir'] . '/images/post/' . Utils::$context['icon'] . '.png') ? 'images_url' : 'default_images_url'] . '/post/' . Utils::$context['icon'] . '.png';
- array_unshift(Utils::$context['icons'], array(
+ array_unshift(Utils::$context['icons'], [
'value' => Utils::$context['icon'],
'name' => Lang::$txt['current_icon'],
'url' => Utils::$context['icon_url'],
'is_last' => empty(Utils::$context['icons']),
'selected' => true,
- ));
+ ]);
}
}
@@ -1998,139 +1885,134 @@ protected function setupPostingFields(): void
normally be generated in the template file using the other
information in the array. This should be avoided if at all possible.
*/
- Utils::$context['posting_fields'] = array();
+ Utils::$context['posting_fields'] = [];
// Guests must supply their name and email.
- if (isset(Utils::$context['name']) && isset(Utils::$context['email']))
- {
- Utils::$context['posting_fields']['guestname'] = array(
- 'label' => array(
+ if (isset(Utils::$context['name'], Utils::$context['email'])) {
+ Utils::$context['posting_fields']['guestname'] = [
+ 'label' => [
'text' => Lang::$txt['name'],
'class' => isset(Utils::$context['post_error']['long_name']) || isset(Utils::$context['post_error']['no_name']) || isset(Utils::$context['post_error']['bad_name']) ? 'error' : '',
- ),
- 'input' => array(
+ ],
+ 'input' => [
'type' => 'text',
- 'attributes' => array(
+ 'attributes' => [
'size' => 25,
'maxlength' => 25,
'value' => Utils::$context['name'],
'required' => true,
- ),
- ),
- );
+ ],
+ ],
+ ];
- if (empty(Config::$modSettings['guest_post_no_email']))
- {
- Utils::$context['posting_fields']['email'] = array(
- 'label' => array(
+ if (empty(Config::$modSettings['guest_post_no_email'])) {
+ Utils::$context['posting_fields']['email'] = [
+ 'label' => [
'text' => Lang::$txt['email'],
'class' => isset(Utils::$context['post_error']['no_email']) || isset(Utils::$context['post_error']['bad_email']) ? 'error' : '',
- ),
- 'input' => array(
+ ],
+ 'input' => [
'type' => 'email',
- 'attributes' => array(
+ 'attributes' => [
'size' => 25,
'value' => Utils::$context['email'],
'required' => true,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
}
// Gotta post it somewhere.
- if (empty(Board::$info->id))
- {
- Utils::$context['posting_fields']['board'] = array(
- 'label' => array(
+ if (empty(Board::$info->id)) {
+ Utils::$context['posting_fields']['board'] = [
+ 'label' => [
'text' => Lang::$txt['calendar_post_in'],
- ),
- 'input' => array(
+ ],
+ 'input' => [
'type' => 'select',
- 'options' => array(),
- ),
- );
+ 'options' => [],
+ ],
+ ];
- foreach ($this->board_list as $category)
- {
- Utils::$context['posting_fields']['board']['input']['options'][$category['name']] = array('options' => array());
+ foreach ($this->board_list as $category) {
+ Utils::$context['posting_fields']['board']['input']['options'][$category['name']] = ['options' => []];
- foreach ($category['boards'] as $brd)
- {
- Utils::$context['posting_fields']['board']['input']['options'][$category['name']]['options'][$brd['name']] = array(
+ foreach ($category['boards'] as $brd) {
+ Utils::$context['posting_fields']['board']['input']['options'][$category['name']]['options'][$brd['name']] = [
'value' => $brd['id'],
'selected' => (bool) $brd['selected'],
'label' => ($brd['child_level'] > 0 ? str_repeat('==', $brd['child_level'] - 1) . '=>' : '') . ' ' . $brd['name'],
- );
+ ];
}
}
}
// Gotta have a subject.
- Utils::$context['posting_fields']['subject'] = array(
- 'label' => array(
+ Utils::$context['posting_fields']['subject'] = [
+ 'label' => [
'text' => Lang::$txt['subject'],
'class' => isset(Utils::$context['post_error']['no_subject']) ? 'error' : '',
- ),
- 'input' => array(
+ ],
+ 'input' => [
'type' => 'text',
- 'attributes' => array(
+ 'attributes' => [
'size' => 80,
'maxlength' => 80 + (!empty(Topic::$info->id) ? Utils::entityStrlen(Utils::$context['response_prefix']) : 0),
'value' => Utils::$context['subject'],
'required' => true,
- ),
- ),
- );
+ ],
+ ],
+ ];
// Icons are fun.
- Utils::$context['posting_fields']['icon'] = array(
- 'label' => array(
+ Utils::$context['posting_fields']['icon'] = [
+ 'label' => [
'text' => Lang::$txt['message_icon'],
- ),
- 'input' => array(
+ ],
+ 'input' => [
'type' => 'select',
- 'attributes' => array(
+ 'attributes' => [
'id' => 'icon',
'onchange' => 'showimage();',
- ),
- 'options' => array(),
+ ],
+ 'options' => [],
'after' => ' ',
- ),
- );
- foreach (Utils::$context['icons'] as $icon)
- {
- Utils::$context['posting_fields']['icon']['input']['options'][$icon['name']] = array(
+ ],
+ ];
+
+ foreach (Utils::$context['icons'] as $icon) {
+ Utils::$context['posting_fields']['icon']['input']['options'][$icon['name']] = [
'value' => $icon['value'],
'selected' => $icon['value'] == Utils::$context['icon'],
- );
+ ];
}
// If we're editing and displaying edit details, show a box where they can say why.
- if (isset(Utils::$context['editing']) && Config::$modSettings['show_modify'])
- {
- Utils::$context['posting_fields']['modify_reason'] = array(
- 'label' => array(
+ if (isset(Utils::$context['editing']) && Config::$modSettings['show_modify']) {
+ Utils::$context['posting_fields']['modify_reason'] = [
+ 'label' => [
'text' => Lang::$txt['reason_for_edit'],
- ),
- 'input' => array(
+ ],
+ 'input' => [
'type' => 'text',
- 'attributes' => array(
+ 'attributes' => [
'size' => 80,
'maxlength' => 80,
// If same user is editing again, keep the previous edit reason by default.
'value' => isset($modified_reason) && isset(Utils::$context['last_modified_name']) && Utils::$context['last_modified_name'] === User::$me->name ? $modified_reason : '',
- ),
+ ],
// If message has been edited before, show info about that.
'after' => empty(Utils::$context['last_modified_text']) ? '' : ' ' . Utils::$context['last_modified_text'] . ' ',
- ),
- );
+ ],
+ ];
}
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Post::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Post::exportStatic')) {
Post::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Post2.php b/Sources/Actions/Post2.php
index a099db69a9..9ea07257d0 100644
--- a/Sources/Actions/Post2.php
+++ b/Sources/Actions/Post2.php
@@ -13,31 +13,29 @@
namespace SMF\Actions;
-use SMF\BackwardCompatibility;
-
use SMF\Attachment;
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
-use SMF\BrowserDetector;
use SMF\Board;
+use SMF\BrowserDetector;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\Draft;
use SMF\ErrorHandler;
use SMF\Event;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Logging;
-use SMF\MessageIndex;
use SMF\Msg;
use SMF\Poll;
+use SMF\Search\SearchApi;
use SMF\Security;
use SMF\Theme;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
use SMF\Verifier;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
-use SMF\Search\SearchApi;
/**
* This class handles posting and modifying replies and new topics.
@@ -51,12 +49,11 @@ class Post2 extends Post
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'Post2',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -88,10 +85,10 @@ class Post2 extends Post
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'submit' => 'submit',
'show' => 'show',
- );
+ ];
/*********************
* Internal properties
@@ -136,16 +133,18 @@ public function execute(): void
$this->can_approve = User::$me->allowedTo('approve_posts');
// If there is an existing topic, load it.
- if ($this->intent !== self::INTENT_NEW_TOPIC)
+ if ($this->intent !== self::INTENT_NEW_TOPIC) {
$this->loadTopic();
+ }
// Allow mods to add new sub-actions.
- IntegrationHook::call('integrate_post2_subactions', array(&self::$subactions));
+ IntegrationHook::call('integrate_post2_subactions', [&self::$subactions]);
- $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);
+ }
}
/**
@@ -159,18 +158,12 @@ public function execute(): void
public function submit(): void
{
// Sneaking off, are we?
- if (empty($_POST))
- {
- if (!empty(Topic::$topic_id))
- {
+ if (empty($_POST)) {
+ if (!empty(Topic::$topic_id)) {
Utils::redirectexit('action=post;topic=' . Topic::$topic_id . '.0');
- }
- elseif (empty($_SERVER['CONTENT_LENGTH']))
- {
+ } elseif (empty($_SERVER['CONTENT_LENGTH'])) {
Utils::redirectexit('action=post;board=' . Board::$info->id . '.0');
- }
- else
- {
+ } else {
ErrorHandler::fatalLang('post_upload_error', false);
}
}
@@ -182,24 +175,24 @@ public function submit(): void
Security::checkSubmitOnce('check');
// No errors as yet.
- $this->errors = array();
+ $this->errors = [];
// If the session has timed out, let the user re-submit their form.
- if (User::$me->checkSession('post', '', false) != '')
+ if (User::$me->checkSession('post', '', false) != '') {
$this->errors[] = 'session_timeout';
+ }
// Wrong verification code?
$this->checkVerification();
Lang::load('Post');
- IntegrationHook::call('integrate_post2_start', array(&$this->errors));
+ IntegrationHook::call('integrate_post2_start', [&$this->errors]);
$this->submitAttachments();
// Replies to unapproved topics are unapproved by default (but not for moderators)
- if (empty(Topic::$info->is_approved) && !$this->can_approve)
- {
+ if (empty(Topic::$info->is_approved) && !$this->can_approve) {
$this->becomes_approved = false;
// Set a nice session var...
@@ -207,54 +200,47 @@ public function submit(): void
}
// Replying to a topic?
- if ($this->intent === self::INTENT_NEW_REPLY)
- {
+ if ($this->intent === self::INTENT_NEW_REPLY) {
$this->prepareNewReply();
}
// Posting a new topic.
- elseif ($this->intent === self::INTENT_NEW_TOPIC)
- {
+ elseif ($this->intent === self::INTENT_NEW_TOPIC) {
$this->prepareNewTopic();
}
// Modifying an existing message?
- elseif ($this->intent === self::INTENT_EDIT_POST)
- {
+ elseif ($this->intent === self::INTENT_EDIT_POST) {
$this->prepareEdit();
}
// In case we have approval permissions and want to override.
- if ($this->can_approve && Config::$modSettings['postmod_active'])
- {
+ if ($this->can_approve && Config::$modSettings['postmod_active']) {
$this->becomes_approved = isset($_POST['quickReply']) || !empty($_REQUEST['approve']) ? 1 : 0;
$approve_has_changed = isset($this->existing_msg->approved) ? $this->existing_msg->approved != $this->becomes_approved : false;
}
// If the poster is a guest evaluate the legality of name and email.
- if ($this->authorIsGuest)
- {
- $_POST['guestname'] = !isset($_POST['guestname']) ? '' : trim(Utils::normalizeSpaces(Utils::sanitizeChars($_POST['guestname'], 1, ' '), true, true, array('no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true)));
+ if ($this->authorIsGuest) {
+ $_POST['guestname'] = !isset($_POST['guestname']) ? '' : trim(Utils::normalizeSpaces(Utils::sanitizeChars($_POST['guestname'], 1, ' '), true, true, ['no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true]));
$_POST['email'] = !isset($_POST['email']) ? '' : trim($_POST['email']);
- if ($_POST['guestname'] == '' || $_POST['guestname'] == '_')
+ if ($_POST['guestname'] == '' || $_POST['guestname'] == '_') {
$this->errors[] = 'no_name';
+ }
- if (Utils::entityStrlen($_POST['guestname']) > 25)
+ if (Utils::entityStrlen($_POST['guestname']) > 25) {
$this->errors[] = 'long_name';
+ }
- if (empty(Config::$modSettings['guest_post_no_email']))
- {
+ if (empty(Config::$modSettings['guest_post_no_email'])) {
// Only check if they changed it!
- if (!isset($this->existing_msg) || $this->existing_msg->poster_email != $_POST['email'])
- {
- if (!User::$me->allowedTo('moderate_forum') && (!isset($_POST['email']) || $_POST['email'] == ''))
- {
+ if (!isset($this->existing_msg) || $this->existing_msg->poster_email != $_POST['email']) {
+ if (!User::$me->allowedTo('moderate_forum') && (!isset($_POST['email']) || $_POST['email'] == '')) {
$this->errors[] = 'no_email';
}
- if (!User::$me->allowedTo('moderate_forum') && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
- {
+ if (!User::$me->allowedTo('moderate_forum') && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$this->errors[] = 'bad_email';
}
}
@@ -264,250 +250,227 @@ public function submit(): void
}
// In case they are making multiple posts this visit, help them along by storing their name.
- if (empty($this->errors))
- {
+ if (empty($this->errors)) {
$_SESSION['guest_name'] = $_POST['guestname'];
$_SESSION['guest_email'] = $_POST['email'];
}
}
// Coming from the quickReply?
- if (isset($_POST['quickReply']))
+ if (isset($_POST['quickReply'])) {
$_POST['message'] = $_POST['quickReply'];
+ }
// Check the subject and message.
- if (!isset($_POST['subject']) || Utils::htmlTrim(Utils::htmlspecialchars($_POST['subject'])) === '')
- {
+ if (!isset($_POST['subject']) || Utils::htmlTrim(Utils::htmlspecialchars($_POST['subject'])) === '') {
$this->errors[] = 'no_subject';
}
- if (!isset($_POST['message']) || Utils::htmlTrim(Utils::htmlspecialchars($_POST['message']), ENT_QUOTES) === '')
- {
+ if (!isset($_POST['message']) || Utils::htmlTrim(Utils::htmlspecialchars($_POST['message']), ENT_QUOTES) === '') {
$this->errors[] = 'no_message';
- }
- elseif (!empty(Config::$modSettings['max_messageLength']) && Utils::entityStrlen($_POST['message']) > Config::$modSettings['max_messageLength'])
- {
- $this->errors[] = array('long_message', array(Config::$modSettings['max_messageLength']));
- }
- else
- {
+ } elseif (!empty(Config::$modSettings['max_messageLength']) && Utils::entityStrlen($_POST['message']) > Config::$modSettings['max_messageLength']) {
+ $this->errors[] = ['long_message', [Config::$modSettings['max_messageLength']]];
+ } else {
// Prepare the message a bit for some additional testing.
$_POST['message'] = Utils::htmlspecialchars($_POST['message'], ENT_QUOTES);
// Preparse code. (Zef)
- if (User::$me->is_guest)
+ if (User::$me->is_guest) {
User::$me->name = $_POST['guestname'];
+ }
Msg::preparsecode($_POST['message']);
// Let's see if there's still some content left without the tags.
- if (Utils::htmlTrim(strip_tags(BBCodeParser::load()->parse($_POST['message'], false), implode('', Utils::$context['allowed_html_tags']))) === '' && (!User::$me->allowedTo('bbc_html') || strpos($_POST['message'], '[html]') === false))
- {
+ if (Utils::htmlTrim(strip_tags(BBCodeParser::load()->parse($_POST['message'], false), implode('', Utils::$context['allowed_html_tags']))) === '' && (!User::$me->allowedTo('bbc_html') || strpos($_POST['message'], '[html]') === false)) {
$this->errors[] = 'no_message';
}
-
}
- if (isset($_POST['calendar']) && !isset($_REQUEST['deleteevent']) && Utils::htmlTrim($_POST['evtitle']) === '')
- {
+ if (isset($_POST['calendar']) && !isset($_REQUEST['deleteevent']) && Utils::htmlTrim($_POST['evtitle']) === '') {
$this->errors[] = 'no_event';
}
// You are not!
- if (isset($_POST['message']) && strtolower($_POST['message']) == 'i am the administrator.' && !User::$me->is_admin)
- {
+ if (isset($_POST['message']) && strtolower($_POST['message']) == 'i am the administrator.' && !User::$me->is_admin) {
ErrorHandler::fatal('Knave! Masquerader! Charlatan!', false);
}
// Build the poll...
- if (isset($_REQUEST['poll']) && Config::$modSettings['pollMode'] == '1')
- {
- if (!empty(Topic::$topic_id) && !isset($_REQUEST['msg']))
+ if (isset($_REQUEST['poll']) && Config::$modSettings['pollMode'] == '1') {
+ if (!empty(Topic::$topic_id) && !isset($_REQUEST['msg'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
$poll = Poll::create($this->errors);
}
- if ($this->authorIsGuest)
- {
+ if ($this->authorIsGuest) {
// If user is a guest, make sure the chosen name isn't taken.
- if (User::isReservedName($_POST['guestname'], 0, true, false) && (!isset($this->existing_msg->poster_name) || $_POST['guestname'] != $this->existing_msg->poster_name))
- {
+ if (User::isReservedName($_POST['guestname'], 0, true, false) && (!isset($this->existing_msg->poster_name) || $_POST['guestname'] != $this->existing_msg->poster_name)) {
$this->errors[] = 'bad_name';
}
}
// If the user isn't a guest, get his or her name and email.
- elseif (!isset($_REQUEST['msg']))
- {
+ elseif (!isset($_REQUEST['msg'])) {
$_POST['guestname'] = User::$me->username;
$_POST['email'] = User::$me->email;
}
- IntegrationHook::call('integrate_post2_pre', array(&$this->errors));
+ IntegrationHook::call('integrate_post2_pre', [&$this->errors]);
// Any mistakes?
- if (!empty($this->errors))
- {
+ if (!empty($this->errors)) {
// Previewing.
$_REQUEST['preview'] = true;
$this->show();
+
return;
}
// Previewing? Go back to start.
- if (isset($_REQUEST['preview']))
- {
- if (User::$me->checkSession('post', '', false) != '')
- {
+ if (isset($_REQUEST['preview'])) {
+ if (User::$me->checkSession('post', '', false) != '') {
Lang::load('Errors');
$this->errors[] = 'session_timeout';
unset($_POST['preview'], $_REQUEST['xml']); // just in case
}
$this->show();
+
return;
}
// Make sure the user isn't spamming the board.
- if (!isset($_REQUEST['msg']))
+ if (!isset($_REQUEST['msg'])) {
Security::spamProtection('post');
+ }
// At about this point, we're posting and that's that.
ignore_user_abort(true);
@set_time_limit(300);
// Add special html entities to the subject, name, and email.
- $_POST['subject'] = strtr(Utils::htmlspecialchars($_POST['subject']), array("\r" => '', "\n" => '', "\t" => ''));
+ $_POST['subject'] = strtr(Utils::htmlspecialchars($_POST['subject']), ["\r" => '', "\n" => '', "\t" => '']);
$_POST['guestname'] = Utils::htmlspecialchars($_POST['guestname']);
$_POST['email'] = Utils::htmlspecialchars($_POST['email']);
- $_POST['modify_reason'] = empty($_POST['modify_reason']) ? '' : strtr(Utils::htmlspecialchars($_POST['modify_reason']), array("\r" => '', "\n" => '', "\t" => ''));
+ $_POST['modify_reason'] = empty($_POST['modify_reason']) ? '' : strtr(Utils::htmlspecialchars($_POST['modify_reason']), ["\r" => '', "\n" => '', "\t" => '']);
// At this point, we want to make sure the subject isn't too long.
- if (Utils::entityStrlen($_POST['subject']) > 100)
+ if (Utils::entityStrlen($_POST['subject']) > 100) {
$_POST['subject'] = Utils::entitySubstr($_POST['subject'], 0, 100);
+ }
// Same with the "why did you edit this" text.
- if (Utils::entityStrlen($_POST['modify_reason']) > 100)
+ if (Utils::entityStrlen($_POST['modify_reason']) > 100) {
$_POST['modify_reason'] = Utils::entitySubstr($_POST['modify_reason'], 0, 100);
+ }
// Attach any new files.
- if (Utils::$context['can_post_attachment'] && !empty($_SESSION['temp_attachments']) && empty($_POST['from_qr']))
- {
- $attachIDs = array();
- $attach_errors = array();
+ if (Utils::$context['can_post_attachment'] && !empty($_SESSION['temp_attachments']) && empty($_POST['from_qr'])) {
+ $attachIDs = [];
+ $attach_errors = [];
- if (!empty(Utils::$context['we_are_history']))
- {
+ if (!empty(Utils::$context['we_are_history'])) {
$attach_errors[] = ' ' . Lang::$txt['error_temp_attachments_flushed'] . '
';
}
- foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
- {
- if ($attachID != 'initial_error' && strpos($attachID, 'post_tmp_' . User::$me->id) === false)
- {
+ foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
+ if ($attachID != 'initial_error' && strpos($attachID, 'post_tmp_' . User::$me->id) === false) {
continue;
}
// If there was an initial error just show that message.
- if ($attachID == 'initial_error')
- {
+ if ($attachID == 'initial_error') {
$attach_errors[] = ' ' . Lang::$txt['attach_no_upload'] . '';
$attach_errors[] = ' ' . (is_array($attachment) ? vsprintf(Lang::$txt[$attachment[0]], (array) $attachment[1]) : Lang::$txt[$attachment]) . '';
unset($_SESSION['temp_attachments']);
+
break;
}
- $attachmentOptions = array(
- 'post' => isset($_REQUEST['msg']) ? $_REQUEST['msg'] : 0,
+ $attachmentOptions = [
+ 'post' => $_REQUEST['msg'] ?? 0,
'poster' => User::$me->id,
'name' => $attachment['name'],
'tmp_name' => $attachment['tmp_name'],
- 'size' => isset($attachment['size']) ? $attachment['size'] : 0,
- 'mime_type' => isset($attachment['type']) ? $attachment['type'] : '',
- 'id_folder' => isset($attachment['id_folder']) ? $attachment['id_folder'] : Config::$modSettings['currentAttachmentUploadDir'],
+ 'size' => $attachment['size'] ?? 0,
+ 'mime_type' => $attachment['type'] ?? '',
+ 'id_folder' => $attachment['id_folder'] ?? Config::$modSettings['currentAttachmentUploadDir'],
'approved' => !Config::$modSettings['postmod_active'] || User::$me->allowedTo('post_attachment'),
'errors' => $attachment['errors'],
- );
+ ];
- if (empty($attachment['errors']))
- {
- if (Attachment::create($attachmentOptions))
- {
+ if (empty($attachment['errors'])) {
+ if (Attachment::create($attachmentOptions)) {
$attachIDs[] = $attachmentOptions['id'];
- if (!empty($attachmentOptions['thumb']))
+ if (!empty($attachmentOptions['thumb'])) {
$attachIDs[] = $attachmentOptions['thumb'];
+ }
}
- }
- else
- {
+ } else {
$attach_errors[] = ' ';
}
- if (!empty($attachmentOptions['errors']))
- {
+ if (!empty($attachmentOptions['errors'])) {
// Sort out the errors for display and delete any associated files.
$attach_errors[] = ' ' . sprintf(Lang::$txt['attach_warning'], $attachment['name']) . '';
- $log_these = array('attachments_no_create', 'attachments_no_write', 'attach_timeout', 'ran_out_of_space', 'cant_access_upload_path', 'attach_0_byte_file');
+ $log_these = ['attachments_no_create', 'attachments_no_write', 'attach_timeout', 'ran_out_of_space', 'cant_access_upload_path', 'attach_0_byte_file'];
- foreach ($attachmentOptions['errors'] as $error)
- {
- if (!is_array($error))
- {
+ foreach ($attachmentOptions['errors'] as $error) {
+ if (!is_array($error)) {
$attach_errors[] = ' ' . Lang::$txt[$error] . '';
- if (in_array($error, $log_these))
+ if (in_array($error, $log_these)) {
ErrorHandler::log($attachment['name'] . ': ' . Lang::$txt[$error], 'critical');
- }
- else
- {
+ }
+ } else {
$attach_errors[] = ' ' . vsprintf(Lang::$txt[$error[0]], (array) $error[1]) . '';
}
}
- if (file_exists($attachment['tmp_name']))
+ if (file_exists($attachment['tmp_name'])) {
unlink($attachment['tmp_name']);
+ }
}
}
}
unset($_SESSION['temp_attachments']);
// Save the poll to the database.
- if (isset($poll))
+ if (isset($poll)) {
$poll->save();
+ }
// Creating a new topic?
$newTopic = empty($_REQUEST['msg']) && empty(Topic::$topic_id);
// Check the icon.
- if (!isset($_POST['icon']))
- {
+ if (!isset($_POST['icon'])) {
$_POST['icon'] = 'xx';
- }
- else
- {
+ } else {
$_POST['icon'] = Utils::htmlspecialchars($_POST['icon']);
// Need to figure it out if this is a valid icon name.
- if ((!file_exists(Theme::$current->settings['theme_dir'] . '/images/post/' . $_POST['icon'] . '.png')) && (!file_exists(Theme::$current->settings['default_theme_dir'] . '/images/post/' . $_POST['icon'] . '.png')))
- {
+ if ((!file_exists(Theme::$current->settings['theme_dir'] . '/images/post/' . $_POST['icon'] . '.png')) && (!file_exists(Theme::$current->settings['default_theme_dir'] . '/images/post/' . $_POST['icon'] . '.png'))) {
$_POST['icon'] = 'xx';
}
}
// Collect all parameters for the creation or modification of a post.
- $msgOptions = array(
+ $msgOptions = [
'id' => empty($_REQUEST['msg']) ? 0 : (int) $_REQUEST['msg'],
'subject' => $_POST['subject'],
'body' => $_POST['message'],
- 'icon' => preg_replace('~[\./\\\\*:"\'<>]~', '', $_POST['icon']),
+ 'icon' => preg_replace('~[./\\\\*:"\'<>]~', '', $_POST['icon']),
'smileys_enabled' => !isset($_POST['ns']),
- 'attachments' => empty($attachIDs) ? array() : $attachIDs,
+ 'attachments' => empty($attachIDs) ? [] : $attachIDs,
'approved' => $this->becomes_approved,
- );
- $topicOptions = array(
+ ];
+ $topicOptions = [
'id' => empty(Topic::$topic_id) ? 0 : Topic::$topic_id,
'board' => Board::$info->id,
'poll' => isset($poll) ? $poll->id : null,
@@ -517,20 +480,18 @@ public function submit(): void
'is_approved' => !Config::$modSettings['postmod_active'] || empty(Topic::$topic_id) || !empty(Board::$info->cur_topic_approved),
'first_msg' => empty(Topic::$info->id_first_msg) ? null : Topic::$info->id_first_msg,
'last_msg' => empty(Topic::$info->id_last_msg) ? null : Topic::$info->id_last_msg,
- );
- $posterOptions = array(
+ ];
+ $posterOptions = [
'id' => User::$me->id,
'name' => $_POST['guestname'],
'email' => $_POST['email'],
'update_post_count' => !User::$me->is_guest && !isset($_REQUEST['msg']) && Board::$info->posts_count,
- );
+ ];
// This is an already existing message. Edit it.
- if (!empty($_REQUEST['msg']))
- {
+ if (!empty($_REQUEST['msg'])) {
// Have admins allowed people to hide their screwups?
- if (time() - $this->existing_msg->poster_time > Config::$modSettings['edit_wait_time'] || User::$me->id != $this->existing_msg->id_member)
- {
+ if (time() - $this->existing_msg->poster_time > Config::$modSettings['edit_wait_time'] || User::$me->id != $this->existing_msg->id_member) {
$msgOptions['modify_time'] = time();
$msgOptions['modify_name'] = User::$me->name;
$msgOptions['modify_reason'] = $_POST['modify_reason'];
@@ -540,180 +501,166 @@ public function submit(): void
Msg::modify($msgOptions, $topicOptions, $posterOptions);
}
// This is a new topic or an already existing one. Save it.
- else
- {
+ else {
Msg::create($msgOptions, $topicOptions, $posterOptions);
- if (isset($topicOptions['id']))
+ if (isset($topicOptions['id'])) {
Topic::$topic_id = $topicOptions['id'];
+ }
}
// Are there attachments already uploaded and waiting to be assigned?
- if (!empty($msgOptions['id']) && !empty($_SESSION['already_attached']))
- {
+ if (!empty($msgOptions['id']) && !empty($_SESSION['already_attached'])) {
Attachment::assign($_SESSION['already_attached'], $msgOptions['id']);
unset($_SESSION['already_attached']);
}
// If we had a draft for this, its time to remove it since it was just posted
- if (!empty(Config::$modSettings['drafts_post_enabled']) && !empty($_POST['id_draft']))
+ if (!empty(Config::$modSettings['drafts_post_enabled']) && !empty($_POST['id_draft'])) {
Draft::delete($_POST['id_draft']);
+ }
// Editing or posting an event?
- if (isset($_POST['calendar']) && (!isset($_REQUEST['eventid']) || $_REQUEST['eventid'] == -1))
- {
+ if (isset($_POST['calendar']) && (!isset($_REQUEST['eventid']) || $_REQUEST['eventid'] == -1)) {
// Make sure they can link an event to this post.
Calendar::canLinkEvent();
// Insert the event.
- $eventOptions = array(
+ $eventOptions = [
'board' => Board::$info->id,
'topic' => Topic::$topic_id,
'title' => $_POST['evtitle'],
'location' => $_POST['event_location'],
'member' => User::$me->id,
- );
+ ];
Event::create($eventOptions);
- }
- elseif (isset($_POST['calendar']))
- {
+ } elseif (isset($_POST['calendar'])) {
$_REQUEST['eventid'] = (int) $_REQUEST['eventid'];
// Validate the post...
Calendar::validateEventPost();
// If you're not allowed to edit any and all events, you have to be the poster.
- if (!User::$me->allowedTo('calendar_edit_any'))
- {
- User::$me->isAllowedTo('calendar_edit_' . (!empty(User::$me->id) && self::getEventPoster($_REQUEST['eventid']) == User::$me->id ? 'own' : 'any'));
+ if (!User::$me->allowedTo('calendar_edit_any')) {
+ User::$me->isAllowedTo('calendar_edit_' . (!empty(User::$me->id) && Calendar::getEventPoster($_REQUEST['eventid']) == User::$me->id ? 'own' : 'any'));
}
// Delete it?
- if (isset($_REQUEST['deleteevent']))
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}calendar
+ if (isset($_REQUEST['deleteevent'])) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}calendar
WHERE id_event = {int:id_event}',
- array(
+ [
'id_event' => $_REQUEST['eventid'],
- )
+ ],
);
}
// ... or just update it?
- else
- {
+ else {
// Set up our options
- $eventOptions = array(
+ $eventOptions = [
'board' => Board::$info->id,
'topic' => Topic::$topic_id,
'title' => $_POST['evtitle'],
'location' => $_POST['event_location'],
'member' => User::$me->id,
- );
+ ];
Event::modify($_REQUEST['eventid'], $eventOptions);
}
}
// Marking read should be done even for editing messages....
// Mark all the parents read. (since you just posted and they will be unread.)
- if (!User::$me->is_guest && !empty(Board::$info->parent_boards))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}log_boards
+ if (!User::$me->is_guest && !empty(Board::$info->parent_boards)) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_boards
SET id_msg = {int:id_msg}
WHERE id_member = {int:current_member}
AND id_board IN ({array_int:board_list})',
- array(
+ [
'current_member' => User::$me->id,
'board_list' => array_keys(Board::$info->parent_boards),
'id_msg' => Config::$modSettings['maxMsgID'],
- )
+ ],
);
}
// Turn notification on or off. (note this just blows smoke if it's already on or off.)
- if (!empty($_POST['notify']) && !User::$me->is_guest)
- {
- Db::$db->insert('ignore',
+ if (!empty($_POST['notify']) && !User::$me->is_guest) {
+ Db::$db->insert(
+ 'ignore',
'{db_prefix}log_notify',
- array('id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int'),
- array(User::$me->id, Topic::$topic_id, 0),
- array('id_member', 'id_topic', 'id_board')
+ ['id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int'],
+ [User::$me->id, Topic::$topic_id, 0],
+ ['id_member', 'id_topic', 'id_board'],
);
- }
- elseif (!$newTopic)
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_notify
+ } elseif (!$newTopic) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_notify
WHERE id_member = {int:current_member}
AND id_topic = {int:current_topic}',
- array(
+ [
'current_member' => User::$me->id,
'current_topic' => Topic::$topic_id,
- )
+ ],
);
}
// Log an act of moderation - modifying.
- if (!empty($moderationAction))
- {
- Logging::logAction('modify', array('topic' => $this->existing_msg->id_topic, 'message' => $this->existing_msg->id, 'member' => $this->existing_msg->id_member, 'board' => $this->existing_msg->id_board));
+ if (!empty($moderationAction)) {
+ Logging::logAction('modify', ['topic' => $this->existing_msg->id_topic, 'message' => $this->existing_msg->id, 'member' => $this->existing_msg->id_member, 'board' => $this->existing_msg->id_board]);
}
- if (isset($_POST['lock']) && $_POST['lock'] != 2)
- {
- Logging::logAction(empty($_POST['lock']) ? 'unlock' : 'lock', array('topic' => $topicOptions['id'], 'board' => $topicOptions['board']));
+ if (isset($_POST['lock']) && $_POST['lock'] != 2) {
+ Logging::logAction(empty($_POST['lock']) ? 'unlock' : 'lock', ['topic' => $topicOptions['id'], 'board' => $topicOptions['board']]);
}
- if (isset($_POST['sticky']))
- {
- Logging::logAction(empty($_POST['sticky']) ? 'unsticky' : 'sticky', array('topic' => $topicOptions['id'], 'board' => $topicOptions['board']));
+ if (isset($_POST['sticky'])) {
+ Logging::logAction(empty($_POST['sticky']) ? 'unsticky' : 'sticky', ['topic' => $topicOptions['id'], 'board' => $topicOptions['board']]);
}
// Returning to the topic?
- if (!empty($_REQUEST['goback']))
- {
+ if (!empty($_REQUEST['goback'])) {
// Mark the board as read.... because it might get confusing otherwise.
- Db::$db->query('', '
- UPDATE {db_prefix}log_boards
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_boards
SET id_msg = {int:maxMsgID}
WHERE id_member = {int:current_member}
AND id_board = {int:current_board}',
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'maxMsgID' => Config::$modSettings['maxMsgID'],
- )
+ ],
);
}
- if (Board::$info->num_topics == 0)
+ if (Board::$info->num_topics == 0) {
CacheApi::put('board-' . Board::$info->id, null, 120);
+ }
IntegrationHook::call('integrate_post2_end');
- if (!empty($_POST['announce_topic']) && User::$me->allowedTo('announce_topic'))
- {
+ if (!empty($_POST['announce_topic']) && User::$me->allowedTo('announce_topic')) {
Utils::redirectexit('action=announce;sa=selectgroup;topic=' . Topic::$topic_id . (!empty($_POST['move']) && User::$me->allowedTo('move_any') ? ';move' : '') . (empty($_REQUEST['goback']) ? '' : ';goback'));
}
- if (!empty($_POST['move']) && User::$me->allowedTo('move_any'))
- {
+ if (!empty($_POST['move']) && User::$me->allowedTo('move_any')) {
Utils::redirectexit('action=movetopic;topic=' . Topic::$topic_id . '.0' . (empty($_REQUEST['goback']) ? '' : ';goback'));
}
// Return to post if the mod is on.
- if (isset($_REQUEST['msg']) && !empty($_REQUEST['goback']))
- {
+ if (isset($_REQUEST['msg']) && !empty($_REQUEST['goback'])) {
Utils::redirectexit('topic=' . Topic::$topic_id . '.msg' . $_REQUEST['msg'] . '#msg' . $_REQUEST['msg'], BrowserDetector::isBrowser('ie'));
- }
- elseif (!empty($_REQUEST['goback']))
- {
+ } elseif (!empty($_REQUEST['goback'])) {
Utils::redirectexit('topic=' . Topic::$topic_id . '.new#new', BrowserDetector::isBrowser('ie'));
}
// Dut-dut-duh-duh-DUH-duh-dut-duh-duh! *dances to the Final Fantasy Fanfare...*
- else
- {
+ else {
Utils::redirectexit('board=' . Board::$info->id . '.0');
}
}
@@ -729,8 +676,9 @@ public function submit(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -771,9 +719,8 @@ protected function checkVerification(): void
&& Config::$modSettings['posts_require_captcha'] == -1
)
)
- )
- {
- $verifier = new Verifier(array('id' => 'post'));
+ ) {
+ $verifier = new Verifier(['id' => 'post']);
$this->errors = array_merge($this->errors, $verifier->errors);
}
}
@@ -784,27 +731,20 @@ protected function checkVerification(): void
protected function submitAttachments(): void
{
// First check to see if they are trying to delete any current attachments.
- if (isset($_POST['attach_del']))
- {
- $keep_temp = array();
- $keep_ids = array();
-
- foreach ($_POST['attach_del'] as $dummy)
- {
- if (strpos($dummy, 'post_tmp_' . User::$me->id) !== false)
- {
+ if (isset($_POST['attach_del'])) {
+ $keep_temp = [];
+ $keep_ids = [];
+
+ foreach ($_POST['attach_del'] as $dummy) {
+ if (strpos($dummy, 'post_tmp_' . User::$me->id) !== false) {
$keep_temp[] = $dummy;
- }
- else
- {
+ } else {
$keep_ids[] = (int) $dummy;
}
}
- if (isset($_SESSION['temp_attachments']))
- {
- foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
- {
+ if (isset($_SESSION['temp_attachments'])) {
+ foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
if (
(
isset($_SESSION['temp_attachments']['post']['files'], $attachment['name'])
@@ -812,8 +752,7 @@ protected function submitAttachments(): void
)
|| in_array($attachID, $keep_temp)
|| strpos($attachID, 'post_tmp_' . User::$me->id) === false
- )
- {
+ ) {
continue;
}
@@ -822,13 +761,12 @@ protected function submitAttachments(): void
}
}
- if (!empty($_REQUEST['msg']))
- {
- $attachmentQuery = array(
+ if (!empty($_REQUEST['msg'])) {
+ $attachmentQuery = [
'attachment_type' => 0,
'id_msg' => (int) $_REQUEST['msg'],
'not_id_attach' => $keep_ids,
- );
+ ];
Attachment::remove($attachmentQuery);
}
}
@@ -836,21 +774,20 @@ protected function submitAttachments(): void
// Then try to upload any attachments.
Utils::$context['can_post_attachment'] = !empty(Config::$modSettings['attachmentEnable']) && Config::$modSettings['attachmentEnable'] == 1 && (User::$me->allowedTo('post_attachment') || (Config::$modSettings['postmod_active'] && User::$me->allowedTo('post_unapproved_attachments')));
- if (Utils::$context['can_post_attachment'] && empty($_POST['from_qr']))
- {
+ if (Utils::$context['can_post_attachment'] && empty($_POST['from_qr'])) {
Attachment::process();
}
// They've already uploaded some attachments, but they don't have permission to post them
// This can sometimes happen when they came from ?action=calendar;sa=post
- if (!Utils::$context['can_post_attachment'] && !empty($_SESSION['already_attached']))
- {
- foreach ($_SESSION['already_attached'] as $attachID => $attachment)
- Attachment::remove(array('id_attach' => $attachID));
+ if (!Utils::$context['can_post_attachment'] && !empty($_SESSION['already_attached'])) {
+ foreach ($_SESSION['already_attached'] as $attachID => $attachment) {
+ Attachment::remove(['id_attach' => $attachID]);
+ }
unset($_SESSION['already_attached']);
- $this->errors[] = array('cannot_post_attachment', array(Board::$info->name));
+ $this->errors[] = ['cannot_post_attachment', [Board::$info->name]];
}
}
@@ -860,102 +797,82 @@ protected function submitAttachments(): void
protected function prepareNewReply(): void
{
// Don't allow a post if it's locked.
- if (Topic::$info->is_locked != 0 && !User::$me->allowedTo('moderate_board'))
+ if (Topic::$info->is_locked != 0 && !User::$me->allowedTo('moderate_board')) {
ErrorHandler::fatalLang('topic_locked', false);
+ }
// Sorry, multiple polls aren't allowed... yet. You should stop giving me ideas :P.
- if (isset($_REQUEST['poll']) && Topic::$info->id_poll > 0)
+ if (isset($_REQUEST['poll']) && Topic::$info->id_poll > 0) {
unset($_REQUEST['poll']);
+ }
- if (Topic::$info->id_member_started != User::$me->id)
- {
- if (Config::$modSettings['postmod_active'] && User::$me->allowedTo('post_unapproved_replies_any') && !User::$me->allowedTo('post_reply_any'))
- {
+ if (Topic::$info->id_member_started != User::$me->id) {
+ if (Config::$modSettings['postmod_active'] && User::$me->allowedTo('post_unapproved_replies_any') && !User::$me->allowedTo('post_reply_any')) {
$this->becomes_approved = false;
- }
- else
- {
+ } else {
User::$me->isAllowedTo('post_reply_any');
}
- }
- elseif (!User::$me->allowedTo('post_reply_any'))
- {
- if (Config::$modSettings['postmod_active'] && User::$me->allowedTo('post_unapproved_replies_own') && !User::$me->allowedTo('post_reply_own'))
- {
+ } elseif (!User::$me->allowedTo('post_reply_any')) {
+ if (Config::$modSettings['postmod_active'] && User::$me->allowedTo('post_unapproved_replies_own') && !User::$me->allowedTo('post_reply_own')) {
$this->becomes_approved = false;
- }
- else
- {
+ } else {
User::$me->isAllowedTo('post_reply_own');
}
}
- if (isset($_POST['lock']))
- {
+ if (isset($_POST['lock'])) {
// Nothing is changed to the lock.
- if (empty(Topic::$info->is_locked) == empty($_POST['lock']))
- {
+ if (empty(Topic::$info->is_locked) == empty($_POST['lock'])) {
unset($_POST['lock']);
}
// You have no permission to lock this topic.
- elseif (!User::$me->allowedTo(array('lock_any', 'lock_own')) || (!User::$me->allowedTo('lock_any') && User::$me->id != Topic::$info->id_member_started))
- {
+ elseif (!User::$me->allowedTo(['lock_any', 'lock_own']) || (!User::$me->allowedTo('lock_any') && User::$me->id != Topic::$info->id_member_started)) {
unset($_POST['lock']);
}
// You are allowed to (un)lock your own topic only.
- elseif (!User::$me->allowedTo('lock_any'))
- {
+ elseif (!User::$me->allowedTo('lock_any')) {
// You cannot override a moderator lock.
- if (Topic::$info->is_locked == 1)
- {
+ if (Topic::$info->is_locked == 1) {
unset($_POST['lock']);
- }
- else
- {
+ } else {
$_POST['lock'] = empty($_POST['lock']) ? 0 : 2;
}
}
// Hail mighty moderator, (un)lock this topic immediately.
- else
- {
+ else {
$_POST['lock'] = empty($_POST['lock']) ? 0 : 1;
// Did someone (un)lock this while you were posting?
- if (isset($_POST['already_locked']) && $_POST['already_locked'] != Topic::$info->is_locked)
- {
+ if (isset($_POST['already_locked']) && $_POST['already_locked'] != Topic::$info->is_locked) {
$this->errors[] = 'topic_' . (empty(Topic::$info->is_locked) ? 'un' : '') . 'locked';
}
}
}
// So you wanna (un)sticky this...let's see.
- if (isset($_POST['sticky']) && ($_POST['sticky'] == Topic::$info->is_sticky || !User::$me->allowedTo('make_sticky')))
- {
+ if (isset($_POST['sticky']) && ($_POST['sticky'] == Topic::$info->is_sticky || !User::$me->allowedTo('make_sticky'))) {
unset($_POST['sticky']);
- }
- elseif (isset($_POST['sticky']))
- {
+ } elseif (isset($_POST['sticky'])) {
// Did someone (un)sticky this while you were posting?
- if (isset($_POST['already_sticky']) && $_POST['already_sticky'] != Topic::$info->is_sticky)
- {
+ if (isset($_POST['already_sticky']) && $_POST['already_sticky'] != Topic::$info->is_sticky) {
$this->errors[] = 'topic_' . (empty(Topic::$info->is_sticky) ? 'un' : '') . 'sticky';
}
}
// If drafts are enabled, then pass this off
- if (!empty(Config::$modSettings['drafts_post_enabled']) && isset($_POST['save_draft']))
- {
+ if (!empty(Config::$modSettings['drafts_post_enabled']) && isset($_POST['save_draft'])) {
$draft = new Draft((int) $_POST['id_draft']);
$draft->save($this->errors);
$this->show();
+
return;
}
// If the number of replies has changed, if the setting is enabled, go back to Post() - which handles the error.
- if (empty(Theme::$current->options['no_new_reply_warning']) && isset($_POST['last_msg']) && Topic::$info->id_last_msg > $_POST['last_msg'])
- {
+ if (empty(Theme::$current->options['no_new_reply_warning']) && isset($_POST['last_msg']) && Topic::$info->id_last_msg > $_POST['last_msg']) {
$_REQUEST['preview'] = true;
$this->show();
+
return;
}
@@ -975,43 +892,37 @@ protected function prepareNewTopic(): void
// Do like, the permissions, for safety and stuff...
$this->becomes_approved = true;
- if (Config::$modSettings['postmod_active'] && !User::$me->allowedTo('post_new') && User::$me->allowedTo('post_unapproved_topics'))
- {
+ if (Config::$modSettings['postmod_active'] && !User::$me->allowedTo('post_new') && User::$me->allowedTo('post_unapproved_topics')) {
$this->becomes_approved = false;
- }
- else
- {
+ } else {
User::$me->isAllowedTo('post_new');
}
- if (isset($_POST['lock']))
- {
+ if (isset($_POST['lock'])) {
// New topics are by default not locked.
- if (empty($_POST['lock']))
- {
+ if (empty($_POST['lock'])) {
unset($_POST['lock']);
}
// Besides, you need permission.
- elseif (!User::$me->allowedTo(array('lock_any', 'lock_own')))
- {
+ elseif (!User::$me->allowedTo(['lock_any', 'lock_own'])) {
unset($_POST['lock']);
}
// A moderator-lock (1) can override a user-lock (2).
- else
- {
+ else {
$_POST['lock'] = User::$me->allowedTo('lock_any') ? 1 : 2;
}
}
- if (isset($_POST['sticky']) && (empty($_POST['sticky']) || !User::$me->allowedTo('make_sticky')))
+ if (isset($_POST['sticky']) && (empty($_POST['sticky']) || !User::$me->allowedTo('make_sticky'))) {
unset($_POST['sticky']);
+ }
// Saving your new topic as a draft first?
- if (!empty(Config::$modSettings['drafts_post_enabled']) && isset($_POST['save_draft']))
- {
+ if (!empty(Config::$modSettings['drafts_post_enabled']) && isset($_POST['save_draft'])) {
$draft = new Draft((int) $_POST['id_draft']);
$draft->save($this->errors);
$this->show();
+
return;
}
@@ -1029,69 +940,58 @@ protected function prepareEdit(): void
$msgs = Msg::load($_REQUEST['msg']);
- if (empty($msgs))
+ if (empty($msgs)) {
ErrorHandler::fatalLang('cant_find_messages', false);
+ }
$this->existing_msg = current($msgs);
- if (!empty(Topic::$info->is_locked) && !User::$me->allowedTo('moderate_board'))
+ if (!empty(Topic::$info->is_locked) && !User::$me->allowedTo('moderate_board')) {
ErrorHandler::fatalLang('topic_locked', false);
+ }
- if (isset($_POST['lock']))
- {
+ if (isset($_POST['lock'])) {
// Nothing changes to the lock status.
- if ((empty($_POST['lock']) && empty(Topic::$info->is_locked)) || (!empty($_POST['lock']) && !empty(Topic::$info->is_locked)))
- {
+ if ((empty($_POST['lock']) && empty(Topic::$info->is_locked)) || (!empty($_POST['lock']) && !empty(Topic::$info->is_locked))) {
unset($_POST['lock']);
}
// You're simply not allowed to (un)lock this.
- elseif (!User::$me->allowedTo(array('lock_any', 'lock_own')) || (!User::$me->allowedTo('lock_any') && User::$me->id != Topic::$info->id_member_started))
- {
+ elseif (!User::$me->allowedTo(['lock_any', 'lock_own']) || (!User::$me->allowedTo('lock_any') && User::$me->id != Topic::$info->id_member_started)) {
unset($_POST['lock']);
}
// You're only allowed to lock your own topics.
- elseif (!User::$me->allowedTo('lock_any'))
- {
+ elseif (!User::$me->allowedTo('lock_any')) {
// You're not allowed to break a moderator's lock.
- if (Topic::$info->is_locked == 1)
- {
+ if (Topic::$info->is_locked == 1) {
unset($_POST['lock']);
}
// Lock it with a soft lock or unlock it.
- else
- {
+ else {
$_POST['lock'] = empty($_POST['lock']) ? 0 : 2;
}
}
// You must be the moderator.
- else
- {
+ else {
$_POST['lock'] = empty($_POST['lock']) ? 0 : 1;
// Did someone (un)lock this while you were posting?
- if (isset($_POST['already_locked']) && $_POST['already_locked'] != Topic::$info->is_locked)
- {
+ if (isset($_POST['already_locked']) && $_POST['already_locked'] != Topic::$info->is_locked) {
$this->errors[] = 'topic_' . (empty(Topic::$info->is_locked) ? 'un' : '') . 'locked';
}
}
}
// Change the sticky status of this topic?
- if (isset($_POST['sticky']) && (!User::$me->allowedTo('make_sticky') || $_POST['sticky'] == Topic::$info->is_sticky))
- {
+ if (isset($_POST['sticky']) && (!User::$me->allowedTo('make_sticky') || $_POST['sticky'] == Topic::$info->is_sticky)) {
unset($_POST['sticky']);
- }
- elseif (isset($_POST['sticky']))
- {
+ } elseif (isset($_POST['sticky'])) {
// Did someone (un)sticky this while you were posting?
- if (isset($_POST['already_sticky']) && $_POST['already_sticky'] != Topic::$info->is_sticky)
- {
+ if (isset($_POST['already_sticky']) && $_POST['already_sticky'] != Topic::$info->is_sticky) {
$this->errors[] = 'topic_' . (empty(Topic::$info->is_locked) ? 'un' : '') . 'stickied';
}
}
- if ($this->existing_msg->id_member == User::$me->id && !User::$me->allowedTo('modify_any'))
- {
+ if ($this->existing_msg->id_member == User::$me->id && !User::$me->allowedTo('modify_any')) {
if (
(
!Config::$modSettings['postmod_active']
@@ -1099,41 +999,33 @@ protected function prepareEdit(): void
)
&& !empty(Config::$modSettings['edit_disable_time'])
&& $this->existing_msg->poster_time + (Config::$modSettings['edit_disable_time'] + 5) * 60 < time()
- )
- {
+ ) {
ErrorHandler::fatalLang('modify_post_time_passed', false);
- }
- elseif (Topic::$info->id_member_started == User::$me->id && !User::$me->allowedTo('modify_own'))
- {
+ } elseif (Topic::$info->id_member_started == User::$me->id && !User::$me->allowedTo('modify_own')) {
User::$me->isAllowedTo('modify_replies');
- }
- else
- {
+ } else {
User::$me->isAllowedTo('modify_own');
}
- }
- elseif (Topic::$info->id_member_started == User::$me->id && !User::$me->allowedTo('modify_any'))
- {
+ } elseif (Topic::$info->id_member_started == User::$me->id && !User::$me->allowedTo('modify_any')) {
User::$me->isAllowedTo('modify_replies');
// If you're modifying a reply, I say it better be logged...
$moderationAction = true;
- }
- else
- {
+ } else {
User::$me->isAllowedTo('modify_any');
// Log it, assuming you're not modifying your own post.
- if ($this->existing_msg->id_member != User::$me->id)
+ if ($this->existing_msg->id_member != User::$me->id) {
$moderationAction = true;
+ }
}
// If drafts are enabled, then lets send this off to save
- if (!empty(Config::$modSettings['drafts_post_enabled']) && isset($_POST['save_draft']))
- {
+ if (!empty(Config::$modSettings['drafts_post_enabled']) && isset($_POST['save_draft'])) {
$draft = new Draft((int) $_POST['id_draft']);
$draft->save($this->errors);
$this->show();
+
return;
}
@@ -1145,8 +1037,7 @@ protected function prepareEdit(): void
$approve_checked = (!empty($REQUEST['approve']) ? 1 : 0);
$this->becomes_approved = Config::$modSettings['postmod_active'] ? ($this->can_approve && !$this->existing_msg->approved ? $approve_checked : $this->existing_msg->approved) : 1;
- if (!User::$me->allowedTo('moderate_forum') || !$this->authorIsGuest)
- {
+ if (!User::$me->allowedTo('moderate_forum') || !$this->authorIsGuest) {
$_POST['guestname'] = $this->existing_msg->poster_name;
$_POST['email'] = $this->existing_msg->poster_email;
}
@@ -1154,14 +1045,15 @@ protected function prepareEdit(): void
// Update search api
$searchAPI = SearchApi::load();
- if ($searchAPI->supportsMethod('postRemoved'))
+ if ($searchAPI->supportsMethod('postRemoved')) {
$searchAPI->postRemoved($_REQUEST['msg']);
+ }
}
-
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Post2::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Post2::exportStatic')) {
Post2::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/Account.php b/Sources/Actions/Profile/Account.php
index c4ebacfba8..0910f92674 100644
--- a/Sources/Actions/Profile/Account.php
+++ b/Sources/Actions/Profile/Account.php
@@ -13,9 +13,8 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Lang;
use SMF\Profile;
use SMF\User;
@@ -33,12 +32,11 @@ class Account implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'account',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -63,34 +61,33 @@ public function execute(): void
{
Profile::$member->loadThemeOptions();
- if (User::$me->allowedTo(array('profile_identity_own', 'profile_identity_any', 'profile_password_own', 'profile_password_any')))
- {
+ if (User::$me->allowedTo(['profile_identity_own', 'profile_identity_any', 'profile_password_own', 'profile_password_any'])) {
Profile::$member->loadCustomFields('account');
}
Utils::$context['page_desc'] = Lang::$txt['account_info'];
Profile::$member->setupContext(
- array(
- 'member_name',
- 'real_name',
- 'date_registered',
- 'posts',
- 'lngfile',
- 'hr',
- 'id_group',
- 'hr',
- 'email_address',
- 'show_online',
- 'hr',
- 'tfa',
- 'hr',
- 'passwrd1',
- 'passwrd2',
- 'hr',
- 'secret_question',
+ [
+ 'member_name',
+ 'real_name',
+ 'date_registered',
+ 'posts',
+ 'lngfile',
+ 'hr',
+ 'id_group',
+ 'hr',
+ 'email_address',
+ 'show_online',
+ 'hr',
+ 'tfa',
+ 'hr',
+ 'passwrd1',
+ 'passwrd2',
+ 'hr',
+ 'secret_question',
'secret_answer',
- ),
+ ],
);
}
@@ -105,8 +102,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;
}
@@ -128,13 +126,15 @@ public static function call(): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Account::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Account::exportStatic')) {
Account::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/Activate.php b/Sources/Actions/Profile/Activate.php
index 5218d44a68..9da1631d8c 100644
--- a/Sources/Actions/Profile/Activate.php
+++ b/Sources/Actions/Profile/Activate.php
@@ -13,17 +13,14 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
use SMF\IntegrationHook;
use SMF\Logging;
use SMF\Profile;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* Activates an account.
@@ -37,12 +34,11 @@ class Activate implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'activateAccount',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -67,11 +63,9 @@ public function execute(): void
{
User::$me->isAllowedTo('moderate_forum');
- if (isset($_REQUEST['save']) && isset(Profile::$member->is_activated) && Profile::$member->is_activated != 1)
- {
+ if (isset($_REQUEST['save'], Profile::$member->is_activated) && Profile::$member->is_activated != 1) {
// If we are approving the deletion of an account, we do something special ;)
- if (Profile::$member->is_activated == 4)
- {
+ if (Profile::$member->is_activated == 4) {
User::delete(Utils::$context['id_member']);
Utils::redirectexit();
}
@@ -79,18 +73,17 @@ public function execute(): void
$prev_is_activated = Profile::$member->is_activated;
// Let the integrations know of the activation.
- IntegrationHook::call('integrate_activate', array(Profile::$member->username));
+ IntegrationHook::call('integrate_activate', [Profile::$member->username]);
// Actually update this member now, as it guarantees the unapproved count can't get corrupted.
- User::updateMemberData(Utils::$context['id_member'], array('is_activated' => Profile::$member->is_activated >= 10 ? 11 : 1, 'validation_code' => ''));
+ User::updateMemberData(Utils::$context['id_member'], ['is_activated' => Profile::$member->is_activated >= 10 ? 11 : 1, 'validation_code' => '']);
// Log what we did?
- Logging::logAction('approve_member', array('member' => Profile::$member->id), 'admin');
+ Logging::logAction('approve_member', ['member' => Profile::$member->id], 'admin');
// If we are doing approval, update the stats for the member just in case.
- if (in_array($prev_is_activated, array(3, 4, 5, 13, 14, 15)))
- {
- Config::updateModSettings(array('unapprovedMembers' => max(0, Config::$modSettings['unapprovedMembers'] - 1)));
+ if (in_array($prev_is_activated, [3, 4, 5, 13, 14, 15])) {
+ Config::updateModSettings(['unapprovedMembers' => max(0, Config::$modSettings['unapprovedMembers'] - 1)]);
}
// Make sure we update the stats too.
@@ -109,8 +102,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;
}
@@ -132,13 +126,15 @@ public static function call(): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// 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/Profile/AlertsPopup.php b/Sources/Actions/Profile/AlertsPopup.php
index a142ae4629..bee62be9e9 100644
--- a/Sources/Actions/Profile/AlertsPopup.php
+++ b/Sources/Actions/Profile/AlertsPopup.php
@@ -13,10 +13,9 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
use SMF\Alert;
+use SMF\BackwardCompatibility;
use SMF\Config;
use SMF\Lang;
use SMF\User;
@@ -34,12 +33,11 @@ class AlertsPopup implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'alerts_popup',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -66,20 +64,19 @@ public function execute(): void
Config::$db_show_debug = false;
// We only want to output our little layer here.
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
// No funny business allowed
$counter = isset($_REQUEST['counter']) ? max(0, (int) $_REQUEST['counter']) : 0;
$limit = !empty(Config::$modSettings['alerts_per_page']) && (int) Config::$modSettings['alerts_per_page'] < 1000 ? min((int) Config::$modSettings['alerts_per_page'], 1000) : 25;
- Utils::$context['unread_alerts'] = array();
+ Utils::$context['unread_alerts'] = [];
- if ($counter < User::$me->alerts)
- {
+ if ($counter < User::$me->alerts) {
// Now fetch me my unread alerts, pronto!
Utils::$context['unread_alerts'] = Alert::fetch(User::$me->id, false, !empty($counter) ? User::$me->alerts - $counter : $limit, 0, !isset($_REQUEST['counter']));
- }
+ }
}
/***********************
@@ -93,8 +90,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;
}
@@ -122,7 +120,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\AlertsPopup::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\AlertsPopup::exportStatic')) {
AlertsPopup::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/BuddyIgnoreLists.php b/Sources/Actions/Profile/BuddyIgnoreLists.php
index 908be0ac0a..ff8c398a47 100644
--- a/Sources/Actions/Profile/BuddyIgnoreLists.php
+++ b/Sources/Actions/Profile/BuddyIgnoreLists.php
@@ -13,11 +13,11 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -26,7 +26,6 @@
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Show all the users buddies, as well as a add/delete interface.
@@ -40,12 +39,13 @@ class BuddyIgnoreLists implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'editBuddyIgnoreLists',
- ),
- );
+ 'editBuddies' => 'editBuddies',
+ 'editIgnoreList' => 'editIgnoreList',
+ ],
+ ];
/*******************
* Public properties
@@ -68,20 +68,20 @@ class BuddyIgnoreLists implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'buddies' => 'buddies',
'ignore' => 'ignore',
- );
+ ];
/**
* @var array
*
* Available sub-actions.
*/
- public static array $subtemplates = array(
+ public static array $subtemplates = [
'buddies' => 'editBuddies',
'ignore' => 'editIgnoreList',
- );
+ ];
/****************************
* Internal static properties
@@ -105,8 +105,9 @@ class BuddyIgnoreLists implements ActionInterface
public function execute(): void
{
// Do a quick check to ensure people aren't getting here illegally!
- if (!User::$me->is_owner || empty(Config::$modSettings['enable_buddylist']))
+ if (!User::$me->is_owner || empty(Config::$modSettings['enable_buddylist'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Can we email the user directly?
Utils::$context['can_moderate_forum'] = User::$me->allowedTo('moderate_forum');
@@ -115,22 +116,23 @@ public function execute(): void
Utils::$context['sub_template'] = self::$subtemplates[$this->subaction];
// Create the tabs for the template.
- Menu::$loaded['profile']->tab_data = array(
+ Menu::$loaded['profile']->tab_data = [
'title' => Lang::$txt['editBuddyIgnoreLists'],
'description' => Lang::$txt['buddy_ignore_desc'],
'icon_class' => 'main_icons profile_hd',
- 'tabs' => array(
- 'buddies' => array(),
- 'ignore' => array(),
- ),
- );
+ 'tabs' => [
+ 'buddies' => [],
+ 'ignore' => [],
+ ],
+ ];
- Theme::loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
-
- $call = method_exists($this, self::$subactions[$this->subaction]) ? array($this, self::$subactions[$this->subaction]) : Utils::getCallable(self::$subactions[$this->subaction]);
+ Theme::loadJavaScriptFile('suggest.js', ['defer' => false, 'minimize' => true], 'smf_suggest');
- if (!empty($call))
+ $call = method_exists($this, self::$subactions[$this->subaction]) ? [$this, self::$subactions[$this->subaction]] : Utils::getCallable(self::$subactions[$this->subaction]);
+
+ if (!empty($call)) {
call_user_func($call);
+ }
}
/**
@@ -141,26 +143,23 @@ public function buddies(): void
// For making changes!
$buddiesArray = explode(',', Profile::$member->data['buddy_list']);
- foreach ($buddiesArray as $k => $dummy)
- {
- if ($dummy == '')
+ foreach ($buddiesArray as $k => $dummy) {
+ if ($dummy == '') {
unset($buddiesArray[$k]);
+ }
}
// Removing a buddy?
- if (isset($_GET['remove']))
- {
+ if (isset($_GET['remove'])) {
User::$me->checkSession('get');
- IntegrationHook::call('integrate_remove_buddy', array(Profile::$member->id));
+ IntegrationHook::call('integrate_remove_buddy', [Profile::$member->id]);
$_SESSION['prf-save'] = Lang::$txt['could_not_remove_person'];
// Heh, I'm lazy, do it the easy way...
- foreach ($buddiesArray as $key => $buddy)
- {
- if ($buddy == (int) $_GET['remove'])
- {
+ foreach ($buddiesArray as $key => $buddy) {
+ if ($buddy == (int) $_GET['remove']) {
unset($buddiesArray[$key]);
$_SESSION['prf-save'] = true;
}
@@ -168,58 +167,56 @@ public function buddies(): void
// Make the changes.
Profile::$member->data['buddy_list'] = implode(',', $buddiesArray);
- User::updateMemberData(Profile::$member->id, array('buddy_list' => Profile::$member->data['buddy_list']));
+ User::updateMemberData(Profile::$member->id, ['buddy_list' => Profile::$member->data['buddy_list']]);
// Redirect off the page because we don't like all this ugly query stuff to stick in the history.
Utils::redirectexit('action=profile;area=lists;sa=buddies;u=' . Profile::$member->id);
}
// Adding a buddy?
- if (isset($_POST['new_buddy']))
- {
+ if (isset($_POST['new_buddy'])) {
User::$me->checkSession();
// Prepare the string for extraction...
- $_POST['new_buddy'] = strtr(Utils::htmlspecialchars($_POST['new_buddy'], ENT_QUOTES), array('"' => '"'));
+ $_POST['new_buddy'] = strtr(Utils::htmlspecialchars($_POST['new_buddy'], ENT_QUOTES), ['"' => '"']);
preg_match_all('~"([^"]+)"~', $_POST['new_buddy'], $matches);
$new_buddies = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_buddy']))));
- foreach ($new_buddies as $k => $dummy)
- {
- $new_buddies[$k] = strtr(trim($new_buddies[$k]), array('\'' => '''));
+ foreach ($new_buddies as $k => $dummy) {
+ $new_buddies[$k] = strtr(trim($new_buddies[$k]), ['\'' => ''']);
- if (strlen($new_buddies[$k]) == 0 || in_array($new_buddies[$k], array(Profile::$member->data['member_name'], Profile::$member->data['real_name'])))
- {
+ if (strlen($new_buddies[$k]) == 0 || in_array($new_buddies[$k], [Profile::$member->data['member_name'], Profile::$member->data['real_name']])) {
unset($new_buddies[$k]);
}
}
- IntegrationHook::call('integrate_add_buddies', array(Profile::$member->id, &$new_buddies));
+ IntegrationHook::call('integrate_add_buddies', [Profile::$member->id, &$new_buddies]);
$_SESSION['prf-save'] = Lang::$txt['could_not_add_person'];
- if (!empty($new_buddies))
- {
+ if (!empty($new_buddies)) {
// Now find out the id_member of the buddy.
- $request = Db::$db->query('', '
- SELECT id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}members
WHERE member_name IN ({array_string:new_buddies}) OR real_name IN ({array_string:new_buddies})
LIMIT {int:count_new_buddies}',
- array(
+ [
'new_buddies' => $new_buddies,
'count_new_buddies' => count($new_buddies),
- )
+ ],
);
+
// Add the new member to the buddies array.
- while ($row = Db::$db->fetch_assoc($request))
- {
+ while ($row = Db::$db->fetch_assoc($request)) {
$_SESSION['prf-save'] = true;
- if (in_array($row['id_member'], $buddiesArray))
+ if (in_array($row['id_member'], $buddiesArray)) {
continue;
+ }
$buddiesArray[] = (int) $row['id_member'];
}
@@ -227,7 +224,7 @@ public function buddies(): void
// Now update the current user's buddy list.
Profile::$member->data['buddy_list'] = implode(',', $buddiesArray);
- User::updateMemberData(Profile::$member->id, array('buddy_list' => Profile::$member->data['buddy_list']));
+ User::updateMemberData(Profile::$member->id, ['buddy_list' => Profile::$member->data['buddy_list']]);
}
// Back to the buddy list!
@@ -235,53 +232,53 @@ public function buddies(): void
}
// Get all the users "buddies"...
- $buddies = array();
+ $buddies = [];
// Gotta load the custom profile fields names.
- Utils::$context['custom_pf'] = array();
-
- $disabled_fields = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : array();
-
- $request = Db::$db->query('', '
- SELECT col_name, field_name, field_desc, field_type, field_options, show_mlist, bbc, enclose
+ Utils::$context['custom_pf'] = [];
+
+ $disabled_fields = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : [];
+
+ $request = Db::$db->query(
+ '',
+ 'SELECT col_name, field_name, field_desc, field_type, field_options, show_mlist, bbc, enclose
FROM {db_prefix}custom_fields
WHERE active = {int:active}
AND private < {int:private_level}',
- array(
+ [
'active' => 1,
'private_level' => 2,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (!isset($disabled_fields[$row['col_name']]) && !empty($row['show_mlist']))
- {
- Utils::$context['custom_pf'][$row['col_name']] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (!isset($disabled_fields[$row['col_name']]) && !empty($row['show_mlist'])) {
+ Utils::$context['custom_pf'][$row['col_name']] = [
'label' => Lang::tokenTxtReplace($row['field_name']),
'type' => $row['field_type'],
- 'options' => !empty($row['field_options']) ? explode(',', $row['field_options']) : array(),
+ 'options' => !empty($row['field_options']) ? explode(',', $row['field_options']) : [],
'bbc' => !empty($row['bbc']),
'enclose' => $row['enclose'],
- );
+ ];
}
}
Db::$db->free_result($request);
- if (!empty($buddiesArray))
- {
- $result = Db::$db->query('', '
- SELECT id_member
+ if (!empty($buddiesArray)) {
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}members
WHERE id_member IN ({array_int:buddy_list})
ORDER BY real_name
LIMIT {int:buddy_list_count}',
- array(
+ [
'buddy_list' => $buddiesArray,
'buddy_list_count' => count(explode(',', Profile::$member->data['buddy_list'])),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$buddies[] = $row['id_member'];
}
Db::$db->free_result($result);
@@ -293,76 +290,62 @@ public function buddies(): void
User::load($buddies, User::LOAD_BY_ID, 'profile');
// Setup the context for each buddy.
- Utils::$context['buddies'] = array();
+ Utils::$context['buddies'] = [];
- foreach ($buddies as $buddy)
- {
+ foreach ($buddies as $buddy) {
Utils::$context['buddies'][$buddy] = User::$loaded[$buddy]->format();
// Make sure to load the appropriate fields for each user
- if (!empty(Utils::$context['custom_pf']))
- {
- foreach (Utils::$context['custom_pf'] as $key => $column)
- {
+ if (!empty(Utils::$context['custom_pf'])) {
+ foreach (Utils::$context['custom_pf'] as $key => $column) {
// Don't show anything if there isn't anything to show.
- if (!isset(Utils::$context['buddies'][$buddy]['options'][$key]))
- {
+ if (!isset(Utils::$context['buddies'][$buddy]['options'][$key])) {
Utils::$context['buddies'][$buddy]['options'][$key] = '';
+
continue;
}
$currentKey = 0;
- if (!empty($column['options']))
- {
- foreach ($column['options'] as $k => $v)
- {
- if (empty($currentKey))
- {
+
+ if (!empty($column['options'])) {
+ foreach ($column['options'] as $k => $v) {
+ if (empty($currentKey)) {
$currentKey = $v == Utils::$context['buddies'][$buddy]['options'][$key] ? $k : 0;
}
}
}
- if ($column['bbc'] && !empty(Utils::$context['buddies'][$buddy]['options'][$key]))
- {
+ if ($column['bbc'] && !empty(Utils::$context['buddies'][$buddy]['options'][$key])) {
Utils::$context['buddies'][$buddy]['options'][$key] = strip_tags(BBCodeParser::load()->parse(Utils::$context['buddies'][$buddy]['options'][$key]));
- }
-
- elseif ($column['type'] == 'check')
- {
+ } elseif ($column['type'] == 'check') {
Utils::$context['buddies'][$buddy]['options'][$key] = Utils::$context['buddies'][$buddy]['options'][$key] == 0 ? Lang::$txt['no'] : Lang::$txt['yes'];
}
// Enclosing the user input within some other text?
- if (!empty($column['enclose']) && !empty(Utils::$context['buddies'][$buddy]['options'][$key]))
- {
- Utils::$context['buddies'][$buddy]['options'][$key] = strtr($column['enclose'], array(
+ if (!empty($column['enclose']) && !empty(Utils::$context['buddies'][$buddy]['options'][$key])) {
+ Utils::$context['buddies'][$buddy]['options'][$key] = strtr($column['enclose'], [
'{SCRIPTURL}' => Config::$scripturl,
'{IMAGES_URL}' => Theme::$current->settings['images_url'],
'{DEFAULT_IMAGES_URL}' => Theme::$current->settings['default_images_url'],
'{KEY}' => $currentKey,
'{INPUT}' => Lang::tokenTxtReplace(Utils::$context['buddies'][$buddy]['options'][$key]),
- ));
+ ]);
}
}
}
}
- if (isset($_SESSION['prf-save']))
- {
- if ($_SESSION['prf-save'] === true)
- {
+ if (isset($_SESSION['prf-save'])) {
+ if ($_SESSION['prf-save'] === true) {
Utils::$context['saved_successful'] = true;
- }
- else
- {
+ } else {
Utils::$context['saved_failed'] = $_SESSION['prf-save'];
}
unset($_SESSION['prf-save']);
}
- IntegrationHook::call('integrate_view_buddies', array(Profile::$member->id));
+ IntegrationHook::call('integrate_view_buddies', [Profile::$member->id]);
}
/**
@@ -373,24 +356,21 @@ public function ignore(): void
// For making changes!
$ignoreArray = explode(',', Profile::$member->data['pm_ignore_list']);
- foreach ($ignoreArray as $k => $dummy)
- {
- if ($dummy == '')
+ foreach ($ignoreArray as $k => $dummy) {
+ if ($dummy == '') {
unset($ignoreArray[$k]);
+ }
}
// Removing a member from the ignore list?
- if (isset($_GET['remove']))
- {
+ if (isset($_GET['remove'])) {
User::$me->checkSession('get');
$_SESSION['prf-save'] = Lang::$txt['could_not_remove_person'];
// Heh, I'm lazy, do it the easy way...
- foreach ($ignoreArray as $key => $id_remove)
- {
- if ($id_remove == (int) $_GET['remove'])
- {
+ foreach ($ignoreArray as $key => $id_remove) {
+ if ($id_remove == (int) $_GET['remove']) {
unset($ignoreArray[$key]);
$_SESSION['prf-save'] = true;
}
@@ -398,56 +378,54 @@ public function ignore(): void
// Make the changes.
Profile::$member->data['pm_ignore_list'] = implode(',', $ignoreArray);
- User::updateMemberData(Profile::$member->id, array('pm_ignore_list' => Profile::$member->data['pm_ignore_list']));
+ User::updateMemberData(Profile::$member->id, ['pm_ignore_list' => Profile::$member->data['pm_ignore_list']]);
// Redirect off the page because we don't like all this ugly query stuff to stick in the history.
Utils::redirectexit('action=profile;area=lists;sa=ignore;u=' . Profile::$member->id);
}
-
+
// Adding a member to the ignore list?
- if (isset($_POST['new_ignore']))
- {
+ if (isset($_POST['new_ignore'])) {
User::$me->checkSession();
-
+
// Prepare the string for extraction...
- $_POST['new_ignore'] = strtr(Utils::htmlspecialchars($_POST['new_ignore'], ENT_QUOTES), array('"' => '"'));
-
+ $_POST['new_ignore'] = strtr(Utils::htmlspecialchars($_POST['new_ignore'], ENT_QUOTES), ['"' => '"']);
+
preg_match_all('~"([^"]+)"~', $_POST['new_ignore'], $matches);
-
+
$new_entries = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_ignore']))));
- foreach ($new_entries as $k => $dummy)
- {
- $new_entries[$k] = strtr(trim($new_entries[$k]), array('\'' => '''));
+ foreach ($new_entries as $k => $dummy) {
+ $new_entries[$k] = strtr(trim($new_entries[$k]), ['\'' => ''']);
- if (strlen($new_entries[$k]) == 0 || in_array($new_entries[$k], array(Profile::$member->data['member_name'], Profile::$member->data['real_name'])))
- {
+ if (strlen($new_entries[$k]) == 0 || in_array($new_entries[$k], [Profile::$member->data['member_name'], Profile::$member->data['real_name']])) {
unset($new_entries[$k]);
}
}
$_SESSION['prf-save'] = Lang::$txt['could_not_add_person'];
- if (!empty($new_entries))
- {
+ if (!empty($new_entries)) {
// Now find out the id_member for the members in question.
- $request = Db::$db->query('', '
- SELECT id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}members
WHERE member_name IN ({array_string:new_entries}) OR real_name IN ({array_string:new_entries})
LIMIT {int:count_new_entries}',
- array(
+ [
'new_entries' => $new_entries,
'count_new_entries' => count($new_entries),
- )
+ ],
);
+
// Add the new member to the ignored array.
- while ($row = Db::$db->fetch_assoc($request))
- {
+ while ($row = Db::$db->fetch_assoc($request)) {
$_SESSION['prf-save'] = true;
- if (in_array($row['id_member'], $ignoreArray))
+ if (in_array($row['id_member'], $ignoreArray)) {
continue;
+ }
$ignoreArray[] = (int) $row['id_member'];
}
@@ -455,7 +433,7 @@ public function ignore(): void
// Now update the current user's ignored list.
Profile::$member->data['pm_ignore_list'] = implode(',', $ignoreArray);
- User::updateMemberData(Profile::$member->id, array('pm_ignore_list' => Profile::$member->data['pm_ignore_list']));
+ User::updateMemberData(Profile::$member->id, ['pm_ignore_list' => Profile::$member->data['pm_ignore_list']]);
}
// Back to the list of pitiful people!
@@ -463,23 +441,23 @@ public function ignore(): void
}
// Initialise the list of members we're ignoring.
- $ignored = array();
+ $ignored = [];
- if (!empty($ignoreArray))
- {
- $result = Db::$db->query('', '
- SELECT id_member
+ if (!empty($ignoreArray)) {
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}members
WHERE id_member IN ({array_int:ignore_list})
ORDER BY real_name
LIMIT {int:ignore_list_count}',
- array(
+ [
'ignore_list' => $ignoreArray,
'ignore_list_count' => count(explode(',', Profile::$member->data['pm_ignore_list'])),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$ignored[] = $row['id_member'];
}
Db::$db->free_result($result);
@@ -491,21 +469,16 @@ public function ignore(): void
User::load($ignored, User::LOAD_BY_ID, 'profile');
// Setup the context for each buddy.
- Utils::$context['ignore_list'] = array();
+ Utils::$context['ignore_list'] = [];
- foreach ($ignored as $ignore_member)
- {
+ foreach ($ignored as $ignore_member) {
Utils::$context['ignore_list'][$ignore_member] = User::$loaded[$ignore_member]->format();
}
- if (isset($_SESSION['prf-save']))
- {
- if ($_SESSION['prf-save'] === true)
- {
+ if (isset($_SESSION['prf-save'])) {
+ if ($_SESSION['prf-save'] === true) {
Utils::$context['saved_successful'] = true;
- }
- else
- {
+ } else {
Utils::$context['saved_failed'] = $_SESSION['prf-save'];
}
@@ -524,8 +497,9 @@ public function ignore(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -573,16 +547,19 @@ public static function editIgnoreList($memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
- 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__ . '\BuddyIgnoreLists::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\BuddyIgnoreLists::exportStatic')) {
BuddyIgnoreLists::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/Delete.php b/Sources/Actions/Profile/Delete.php
index 8f80b18138..9bb256b64a 100644
--- a/Sources/Actions/Profile/Delete.php
+++ b/Sources/Actions/Profile/Delete.php
@@ -13,10 +13,11 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\Actions\Logout;
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Msg;
@@ -24,8 +25,6 @@
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Actions\Logout;
-use SMF\Db\DatabaseApi as Db;
/**
* Handles deleting an account.
@@ -39,12 +38,12 @@ class Delete implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'deleteAccount',
- ),
- );
+ 'deleteAccount2' => 'deleteAccount2',
+ ],
+ ];
/****************************
* Internal static properties
@@ -67,12 +66,9 @@ class Delete implements ActionInterface
*/
public function execute(): void
{
- if (!empty(Utils::$context['completed_save']))
- {
+ if (!empty(Utils::$context['completed_save'])) {
$this->delete();
- }
- else
- {
+ } else {
$this->show();
}
}
@@ -82,12 +78,9 @@ public function execute(): void
*/
public function show(): void
{
- if (!User::$me->is_owner)
- {
+ if (!User::$me->is_owner) {
User::$me->isAllowedTo('profile_remove_any');
- }
- elseif (!User::$me->allowedTo('profile_remove_any'))
- {
+ } elseif (!User::$me->allowedTo('profile_remove_any')) {
User::$me->isAllowedTo('profile_remove_own');
}
@@ -103,18 +96,14 @@ public function show(): void
Utils::$context['page_title'] = Lang::$txt['deleteAccount'] . ': ' . Profile::$member->name;
}
-
/**
* Actually deletes the account.
*/
public function delete()
{
- if (!User::$me->is_owner)
- {
+ if (!User::$me->is_owner) {
User::$me->isAllowedTo('profile_remove_any');
- }
- elseif (!User::$me->allowedTo('profile_remove_any'))
- {
+ } elseif (!User::$me->allowedTo('profile_remove_any')) {
User::$me->isAllowedTo('profile_remove_own');
}
@@ -124,119 +113,122 @@ public function delete()
User::$me->checkSession();
// Too often, people remove/delete their own only account.
- if (in_array(1, Profile::$member->groups))
- {
+ if (in_array(1, Profile::$member->groups)) {
// Are you allowed to administrate the forum, as they are?
User::$me->isAllowedTo('admin_forum');
- $request = Db::$db->query('', '
- SELECT id_member
+ $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 id_member != {int:selected_member}
LIMIT 1',
- array(
+ [
'admin_group' => 1,
'selected_member' => Profile::$member->id,
- )
+ ],
);
list($another) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- if (empty($another))
+ if (empty($another)) {
ErrorHandler::fatalLang('at_least_one_admin', 'critical');
+ }
}
// Deleting someone else's account.
- if (!User::$me->is_owner)
- {
+ if (!User::$me->is_owner) {
// Now, have you been naughty and need your posts deleting?
// @todo Should this check board permissions?
- if (!empty($_POST['deleteVotes']) && User::$me->allowedTo('moderate_forum'))
- {
+ if (!empty($_POST['deleteVotes']) && User::$me->allowedTo('moderate_forum')) {
// First we find any polls that this user has voted in...
- $polls_to_update = array();
- $get_voted_polls = Db::$db->query('', '
- SELECT DISTINCT id_poll
+ $polls_to_update = [];
+ $get_voted_polls = Db::$db->query(
+ '',
+ 'SELECT DISTINCT id_poll
FROM {db_prefix}log_polls
WHERE id_member = {int:selected_member}',
- array(
+ [
'selected_member' => Profile::$member->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($get_voted_polls))
- {
+
+ while ($row = Db::$db->fetch_assoc($get_voted_polls)) {
$polls_to_update[] = $row['id_poll'];
}
Db::$db->free_result($get_voted_polls);
// Now we delete the votes and update the polls
- if (!empty($polls_to_update))
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_polls
+ if (!empty($polls_to_update)) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_polls
WHERE id_member = {int:selected_member}',
- array(
+ [
'selected_member' => Profile::$member->id,
- )
+ ],
);
- Db::$db->query('', '
- UPDATE {db_prefix}polls
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}polls
SET votes = votes - 1
WHERE id_poll IN ({array_int:polls_to_update})',
- array(
- 'polls_to_update' => $polls_to_update
- )
+ [
+ 'polls_to_update' => $polls_to_update,
+ ],
);
}
// Next, delete the posts, if requested.
- if (in_array($_POST['remove_type'], array('posts', 'topics')))
- {
+ if (in_array($_POST['remove_type'], ['posts', 'topics'])) {
$extra = empty($_POST['perma_delete']) ? ' AND t.id_board != {int:recycle_board}' : '';
$recycle_board = empty(Config::$modSettings['recycle_board']) ? 0 : Config::$modSettings['recycle_board'];
// First off we delete any topics the member has started, if requested.
- if ($_POST['remove_type'] == 'topics')
- {
+ if ($_POST['remove_type'] == 'topics') {
// Fetch all topics started by this user.
- $request = Db::$db->query('', '
- SELECT t.id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_topic
FROM {db_prefix}topics AS t
WHERE t.id_member_started = {int:selected_member}' . $extra,
- array(
+ [
'selected_member' => Profile::$member->id,
'recycle_board' => $recycle_board,
- )
+ ],
);
$topic_ids = Db::$db->fetch_all($request);
Db::$db->free_result($request);
// Actually remove the topics.
// Ignore recycling if we want to perma-delete things...
- if (!empty($topic_ids))
+ if (!empty($topic_ids)) {
Topic::remove($topic_ids, true, !empty($extra));
+ }
}
// Now delete the remaining messages.
- $request = Db::$db->query('', '
- SELECT m.id_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT 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_first_msg != m.id_msg)
WHERE m.id_member = {int:selected_member}' . $extra,
- array(
+ [
'selected_member' => Profile::$member->id,
'recycle_board' => $recycle_board,
- )
+ ],
);
+
// This could take a while... but ya know it's gonna be worth it in the end.
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (function_exists('apache_reset_timeout'))
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (function_exists('apache_reset_timeout')) {
@apache_reset_timeout();
+ }
Msg::remove($row['id_msg']);
}
@@ -245,21 +237,20 @@ public function delete()
}
// Only delete this poor member's account if they are actually being booted out of camp.
- if (isset($_POST['deleteAccount']))
+ if (isset($_POST['deleteAccount'])) {
User::delete(Profile::$member->id);
+ }
}
// Deleting their own account, but they need approval to delete.
- elseif (!empty(Config::$modSettings['approveAccountDeletion']) && !User::$me->allowedTo('moderate_forum'))
- {
+ elseif (!empty(Config::$modSettings['approveAccountDeletion']) && !User::$me->allowedTo('moderate_forum')) {
// Setup their account for deletion.
- User::updateMemberData(Profile::$member->id, array('is_activated' => 4));
+ User::updateMemberData(Profile::$member->id, ['is_activated' => 4]);
// Another account needs approval...
- Config::updateModSettings(array('unapprovedMembers' => true), true);
+ Config::updateModSettings(['unapprovedMembers' => true], true);
}
// Deleting their own account, and they don't need approval.
- else
- {
+ else {
User::delete(Profile::$member->id);
Logout::call(true);
@@ -279,8 +270,9 @@ public function delete()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -324,13 +316,15 @@ public static function deleteAccount2(int $memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Delete::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Delete::exportStatic')) {
Delete::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/Export.php b/Sources/Actions/Profile/Export.php
index ecc97edcd6..48146a96c0 100644
--- a/Sources/Actions/Profile/Export.php
+++ b/Sources/Actions/Profile/Export.php
@@ -13,10 +13,10 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Security;
@@ -25,7 +25,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This class contains functions to export a member's profile data to a
@@ -42,14 +41,13 @@ class Export implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'export_profile_data',
'createDir' => 'create_export_dir',
'getFormats' => 'get_export_formats',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -84,25 +82,25 @@ class Export implements ActionInterface
* Supported formats for the export files.
* Protected to force access via Export::getFormats()
*/
- protected static $formats = array(
- 'XML_XSLT' => array(
+ protected static $formats = [
+ 'XML_XSLT' => [
'extension' => 'styled.xml',
'mime' => 'text/xml',
'description' => 'export_format_xml_xslt',
'per_page' => 500,
- ),
- 'HTML' => array(
+ ],
+ 'HTML' => [
'extension' => 'html',
'mime' => 'text/html',
'description' => 'export_format_html',
'per_page' => 500,
- ),
- 'XML' => array(
+ ],
+ 'XML' => [
'extension' => 'xml',
'mime' => 'text/xml',
'description' => 'export_format_xml',
'per_page' => 2000,
- ),
+ ],
// 'CSV' => array(
// 'extension' => 'csv',
// 'mime' => 'text/csv',
@@ -115,7 +113,7 @@ class Export implements ActionInterface
// 'description' => 'export_format_json',
// 'per_page' => 2000,
// ),
- );
+ ];
/**
* @var object
@@ -134,8 +132,7 @@ class Export implements ActionInterface
*/
public function execute(): void
{
- if (empty(Config::$modSettings['export_dir']) || !is_dir(Config::$modSettings['export_dir']) || !Utils::makeWritable(Config::$modSettings['export_dir']))
- {
+ if (empty(Config::$modSettings['export_dir']) || !is_dir(Config::$modSettings['export_dir']) || !Utils::makeWritable(Config::$modSettings['export_dir'])) {
self::createDir();
}
@@ -144,124 +141,118 @@ public function execute(): void
$idhash = hash_hmac('sha1', Utils::$context['id_member'], Config::getAuthSecret());
$dltoken = hash_hmac('sha1', $idhash, Config::getAuthSecret());
- Utils::$context['completed_exports'] = array();
- Utils::$context['active_exports'] = array();
- $existing_export_formats = array();
- $latest = array();
+ Utils::$context['completed_exports'] = [];
+ Utils::$context['active_exports'] = [];
+ $existing_export_formats = [];
+ $latest = [];
- foreach (self::$formats as $format => $format_settings)
- {
+ foreach (self::$formats as $format => $format_settings) {
$idhash_ext = $idhash . '.' . $format_settings['extension'];
$done = null;
- Utils::$context['outdated_exports'][$idhash_ext] = array();
+ Utils::$context['outdated_exports'][$idhash_ext] = [];
// $realfile needs to be the highest numbered one, or 1_*** if none exist.
$filenum = 1;
$realfile = $export_dir_slash . $filenum . '_' . $idhash_ext;
- while (file_exists($export_dir_slash . ($filenum + 1) . '_' . $idhash_ext))
+
+ while (file_exists($export_dir_slash . ($filenum + 1) . '_' . $idhash_ext)) {
$realfile = $export_dir_slash . ++$filenum . '_' . $idhash_ext;
+ }
$tempfile = $export_dir_slash . $idhash_ext . '.tmp';
$progressfile = $export_dir_slash . $idhash_ext . '.progress.json';
// If requested by the user, delete any existing export files and background tasks.
- if (isset($_POST['delete']) && isset($_POST['format']) && $_POST['format'] === $format && isset($_POST['t']) && $_POST['t'] === $dltoken)
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}background_tasks
+ if (isset($_POST['delete'], $_POST['format']) && $_POST['format'] === $format && isset($_POST['t']) && $_POST['t'] === $dltoken) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}background_tasks
WHERE task_class = {string:class}
AND task_data LIKE {string:details}',
- array(
- 'class' => 'SMF\Tasks\ExportProfileData',
- 'details' => substr(Utils::jsonEncode(array('format' => $format, 'uid' => Utils::$context['id_member'])), 0, -1) . ',%',
- )
+ [
+ 'class' => 'SMF\\Tasks\\ExportProfileData',
+ 'details' => substr(Utils::jsonEncode(['format' => $format, 'uid' => Utils::$context['id_member']]), 0, -1) . ',%',
+ ],
);
- foreach (glob($export_dir_slash . '*' . $idhash_ext . '*') as $fpath)
+ foreach (glob($export_dir_slash . '*' . $idhash_ext . '*') as $fpath) {
@unlink($fpath);
+ }
- if (empty($_POST['export_begin']))
+ if (empty($_POST['export_begin'])) {
Utils::redirectexit('action=profile;area=getprofiledata;u=' . Utils::$context['id_member']);
+ }
}
- $progress = file_exists($progressfile) ? Utils::jsonDecode(file_get_contents($progressfile), true) : array();
+ $progress = file_exists($progressfile) ? Utils::jsonDecode(file_get_contents($progressfile), true) : [];
- if (!empty($progress))
- {
+ if (!empty($progress)) {
$included = array_keys($progress);
- }
- else
- {
+ } else {
$included = array_intersect(array_keys($this->datatypes), array_keys($_POST));
}
// If we're starting a new export in this format, we're done here.
- if (!empty($_POST['export_begin']) && isset($_POST['format']) && $_POST['format'] === $format)
- {
+ if (!empty($_POST['export_begin']) && isset($_POST['format']) && $_POST['format'] === $format) {
break;
}
// The rest of this loop deals with current exports, if any.
- $included_desc = array();
+ $included_desc = [];
- foreach ($included as $datatype)
+ foreach ($included as $datatype) {
$included_desc[] = Lang::$txt[$datatype];
+ }
- $dlfilename = array_merge(array(Utils::$context['forum_name'], Utils::$context['member']['username']), $included_desc);
+ $dlfilename = array_merge([Utils::$context['forum_name'], Utils::$context['member']['username']], $included_desc);
$dlfilename = preg_replace('/[^\p{L}\p{M}\p{N}_]+/u', '-', str_replace('"', '', Utils::htmlspecialcharsDecode(strip_tags(implode('_', $dlfilename)))));
- if (file_exists($tempfile) && file_exists($progressfile))
- {
+ if (file_exists($tempfile) && file_exists($progressfile)) {
$done = false;
- }
- elseif (file_exists($realfile))
- {
+ } elseif (file_exists($realfile)) {
// It looks like we're done.
$done = true;
// But let's check whether it's outdated.
- foreach ($this->datatypes as $datatype => $datatype_settings)
- {
- if (!isset($progress[$datatype]))
+ foreach ($this->datatypes as $datatype => $datatype_settings) {
+ if (!isset($progress[$datatype])) {
continue;
+ }
- if (!isset($latest[$datatype]))
- {
+ if (!isset($latest[$datatype])) {
$latest[$datatype] = is_callable($datatype_settings['latest']) ? $datatype_settings['latest'](Utils::$context['id_member']) : $datatype_settings['latest'];
}
- if ($latest[$datatype] > $progress[$datatype])
+ if ($latest[$datatype] > $progress[$datatype]) {
Utils::$context['outdated_exports'][$idhash_ext][] = $datatype;
+ }
}
}
- if ($done === true)
- {
+ if ($done === true) {
$exportfilepaths = glob($export_dir_slash . '*_' . $idhash_ext);
- foreach ($exportfilepaths as $exportfilepath)
- {
+ foreach ($exportfilepaths as $exportfilepath) {
$exportbasename = basename($exportfilepath);
$part = substr($exportbasename, 0, strcspn($exportbasename, '_'));
$suffix = count($exportfilepaths) == 1 ? '' : '_' . $part;
$size = filesize($exportfilepath) / 1024;
- $units = array('KB', 'MB', 'GB', 'TB');
+ $units = ['KB', 'MB', 'GB', 'TB'];
$unitkey = 0;
- while ($size > 1024)
- {
+ while ($size > 1024) {
$size = $size / 1024;
$unitkey++;
}
$size = round($size, 2) . $units[$unitkey];
- Utils::$context['completed_exports'][$idhash_ext][$part] = array(
+ Utils::$context['completed_exports'][$idhash_ext][$part] = [
'realname' => $exportbasename,
'dlbasename' => $dlfilename . $suffix . '.' . $format_settings['extension'],
'dltoken' => $dltoken,
@@ -270,89 +261,92 @@ public function execute(): void
'format' => $format,
'mtime' => Time::create('@' . filemtime($exportfilepath))->format(),
'size' => $size,
- );
+ ];
}
ksort(Utils::$context['completed_exports'][$idhash_ext], SORT_NUMERIC);
$existing_export_formats[] = $format;
- }
- elseif ($done === false)
- {
- Utils::$context['active_exports'][$idhash_ext] = array(
+ } elseif ($done === false) {
+ Utils::$context['active_exports'][$idhash_ext] = [
'dltoken' => $dltoken,
'included' => $included,
'included_desc' => Lang::sentenceList($included_desc),
'format' => $format,
- );
+ ];
$existing_export_formats[] = $format;
}
}
- if (!empty($_POST['export_begin']))
- {
+ if (!empty($_POST['export_begin'])) {
User::$me->checkSession();
SecurityToken::validate(Utils::$context['token_check'], 'post');
$format = isset($_POST['format']) && isset(self::$formats[$_POST['format']]) ? $_POST['format'] : 'XML';
- $included = array();
- $included_desc = array();
+ $included = [];
+ $included_desc = [];
- foreach ($this->datatypes as $datatype => $datatype_settings)
- {
- if ($datatype == 'profile' || !empty($_POST[$datatype]))
- {
+ foreach ($this->datatypes as $datatype => $datatype_settings) {
+ if ($datatype == 'profile' || !empty($_POST[$datatype])) {
$included[$datatype] = $datatype_settings[$format];
$included_desc[] = Lang::$txt[$datatype];
$start[$datatype] = !empty($start[$datatype]) ? $start[$datatype] : 0;
- if (!isset($latest[$datatype]))
- {
+ if (!isset($latest[$datatype])) {
$latest[$datatype] = is_callable($datatype_settings['latest']) ? $datatype_settings['latest'](Utils::$context['id_member']) : $datatype_settings['latest'];
}
- if (!isset($total[$datatype]))
- {
+ if (!isset($total[$datatype])) {
$total[$datatype] = is_callable($datatype_settings['total']) ? $datatype_settings['total'](Utils::$context['id_member']) : $datatype_settings['total'];
}
}
}
- $dlfilename = array_merge(array(Utils::$context['forum_name'], Utils::$context['member']['username']), $included_desc);
+ $dlfilename = array_merge([Utils::$context['forum_name'], Utils::$context['member']['username']], $included_desc);
$dlfilename = preg_replace('/[^\p{L}\p{M}\p{N}_]+/u', '-', str_replace('"', '', Utils::htmlspecialcharsDecode(strip_tags(implode('_', $dlfilename)))));
$last_page = ceil(array_sum($total) / self::$formats[$format]['per_page']);
- $data = Utils::jsonEncode(array(
+ $data = Utils::jsonEncode([
'format' => $format,
'uid' => Utils::$context['id_member'],
'lang' => Utils::$context['member']['language'],
'included' => $included,
'start' => $start,
'latest' => $latest,
- 'datatype' => isset($current_datatype) ? $current_datatype : key($included),
+ 'datatype' => $current_datatype ?? key($included),
'format_settings' => self::$formats[$format],
'last_page' => $last_page,
'dlfilename' => $dlfilename,
- ));
-
- Db::$db->insert('insert', '{db_prefix}background_tasks',
- array('task_file' => 'string-255', 'task_class' => 'string-255', 'task_data' => 'string', 'claimed_time' => 'int'),
- array('$sourcedir/tasks/ExportProfileData.php', 'SMF\Tasks\ExportProfileData', $data, 0),
- array()
+ ]);
+
+ Db::$db->insert(
+ 'insert',
+ '{db_prefix}background_tasks',
+ [
+ 'task_class' => 'string-255',
+ 'task_data' => 'string',
+ 'claimed_time' => 'int',
+ ],
+ [
+ 'SMF\\Tasks\\ExportProfileData',
+ $data,
+ 0,
+ ],
+ [],
);
// So the user can see that we've started.
- if (!file_exists($tempfile))
+ if (!file_exists($tempfile)) {
touch($tempfile);
+ }
- if (!file_exists($progressfile))
- {
+ if (!file_exists($progressfile)) {
file_put_contents($progressfile, Utils::jsonEncode(array_fill_keys(array_keys($included), 0)));
}
@@ -363,12 +357,9 @@ public function execute(): void
Utils::$context['page_title'] = Lang::$txt['export_profile_data'];
- if (empty(Config::$modSettings['export_expiry']))
- {
+ if (empty(Config::$modSettings['export_expiry'])) {
unset(Lang::$txt['export_profile_data_desc_list']['expiry']);
- }
- else
- {
+ } else {
Lang::$txt['export_profile_data_desc_list']['expiry'] = sprintf(Lang::$txt['export_profile_data_desc_list']['expiry'], Config::$modSettings['export_expiry']);
}
@@ -388,8 +379,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;
}
@@ -414,42 +406,42 @@ public static function call(): void
public static function createDir($fallback = ''): string|bool
{
// No supplied fallback, so use the default location.
- if (empty($fallback))
+ if (empty($fallback)) {
$fallback = Config::$boarddir . DIRECTORY_SEPARATOR . 'exports';
+ }
// Automatically set it to the fallback if it is missing.
- if (empty(Config::$modSettings['export_dir']))
- Config::updateModSettings(array('export_dir' => $fallback));
+ if (empty(Config::$modSettings['export_dir'])) {
+ Config::updateModSettings(['export_dir' => $fallback]);
+ }
// Make sure the directory exists.
- if (!file_exists(Config::$modSettings['export_dir']))
+ if (!file_exists(Config::$modSettings['export_dir'])) {
@mkdir(Config::$modSettings['export_dir'], null, true);
+ }
// Make sure the directory has the correct permissions.
- if (!is_dir(Config::$modSettings['export_dir']) || !Utils::makeWritable(Config::$modSettings['export_dir']))
- {
+ if (!is_dir(Config::$modSettings['export_dir']) || !Utils::makeWritable(Config::$modSettings['export_dir'])) {
Lang::load('Errors');
// Try again at the fallback location.
- if (Config::$modSettings['export_dir'] != $fallback)
- {
+ if (Config::$modSettings['export_dir'] != $fallback) {
ErrorHandler::log(sprintf(Lang::$txt['export_dir_forced_change'], Config::$modSettings['export_dir'], $fallback));
- Config::updateModSettings(array('export_dir' => $fallback));
+ Config::updateModSettings(['export_dir' => $fallback]);
// Secondary fallback will be the default location, so no parameter this time.
self::createDir();
}
// Uh-oh. Even the default location failed.
- else
- {
+ else {
ErrorHandler::log(Lang::$txt['export_dir_not_writable']);
return false;
}
}
- return Security::secureDirectory(array(Config::$modSettings['export_dir']), true);
+ return Security::secureDirectory([Config::$modSettings['export_dir']], true);
}
/**
@@ -462,23 +454,23 @@ public static function getFormats()
static $finalized = false;
// Finalize various string values.
- if (!$finalized)
- {
+ if (!$finalized) {
array_walk_recursive(
self::$formats,
- function(&$value, $key)
- {
- if ($key === 'description')
+ function (&$value, $key) {
+ if ($key === 'description') {
$value = Lang::$txt[$value] ?? $value;
- }
+ }
+ },
);
$finalized = true;
}
// If these are missing, we can't transform the XML on the server.
- if (!class_exists('DOMDocument') || !class_exists('XSLTProcessor'))
+ if (!class_exists('DOMDocument') || !class_exists('XSLTProcessor')) {
unset(self::$formats['HTML']);
+ }
return self::$formats;
}
@@ -492,60 +484,63 @@ function(&$value, $key)
*/
protected function __construct()
{
- if (!isset(Utils::$context['token_check']))
+ if (!isset(Utils::$context['token_check'])) {
Utils::$context['token_check'] = 'profile-ex' . Utils::$context['id_member'];
+ }
self::getFormats();
- if (!isset($_POST['format']) || !isset(self::$formats[$_POST['format']]))
+ if (!isset($_POST['format']) || !isset(self::$formats[$_POST['format']])) {
unset($_POST['format'], $_POST['delete'], $_POST['export_begin']);
+ }
// This lists the types of data we can export and info for doing so.
- $this->datatypes = array(
- 'profile' => array(
+ $this->datatypes = [
+ 'profile' => [
'label' => null,
'total' => 0,
'latest' => 1,
// Instructions to pass to ExportProfileData background task:
- 'XML' => array(
+ 'XML' => [
'func' => 'getXmlProfile',
'langfile' => 'Profile',
- ),
- 'HTML' => array(
+ ],
+ 'HTML' => [
'func' => 'getXmlProfile',
'langfile' => 'Profile',
- ),
- 'XML_XSLT' => array(
+ ],
+ 'XML_XSLT' => [
'func' => 'getXmlProfile',
'langfile' => 'Profile',
- ),
+ ],
// 'CSV' => array(),
// 'JSON' => array(),
- ),
- 'posts' => array(
+ ],
+ 'posts' => [
'label' => Lang::$txt['export_include_posts'],
'total' => Utils::$context['member']['real_posts'],
- 'latest' => function($uid)
- {
+ 'latest' => function ($uid) {
static $latest_post;
- if (isset($latest_post))
+ if (isset($latest_post)) {
return $latest_post;
+ }
$query_this_board = !empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0 ? 'b.id_board != ' . Config::$modSettings['recycle_board'] : '1=1';
- $request = Db::$db->query('', '
- SELECT m.id_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg
FROM {db_prefix}messages as m
INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
WHERE id_member = {int:uid}
AND ' . $query_this_board . '
ORDER BY id_msg DESC
LIMIT {int:limit}',
- array(
+ [
'limit' => 1,
'uid' => $uid,
- )
+ ],
);
list($latest_post) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -553,66 +548,68 @@ protected function __construct()
return $latest_post;
},
// Instructions to pass to ExportProfileData background task:
- 'XML' => array(
+ 'XML' => [
'func' => 'getXmlPosts',
'langfile' => 'Post',
- ),
- 'HTML' => array(
+ ],
+ 'HTML' => [
'func' => 'getXmlPosts',
'langfile' => 'Post',
- ),
- 'XML_XSLT' => array(
+ ],
+ 'XML_XSLT' => [
'func' => 'getXmlPosts',
'langfile' => 'Post',
- ),
+ ],
// 'CSV' => array(),
// 'JSON' => array(),
- ),
- 'personal_messages' => array(
+ ],
+ 'personal_messages' => [
'label' => Lang::$txt['export_include_personal_messages'],
- 'total' => function($uid)
- {
+ 'total' => function ($uid) {
static $total_pms;
- if (isset($total_pms))
+ if (isset($total_pms)) {
return $total_pms;
+ }
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}personal_messages AS pm
INNER JOIN {db_prefix}pm_recipients AS pmr ON (pm.id_pm = pmr.id_pm)
WHERE (pm.id_member_from = {int:uid} AND pm.deleted_by_sender = {int:not_deleted})
OR (pmr.id_member = {int:uid} AND pmr.deleted = {int:not_deleted})',
- array(
+ [
'uid' => $uid,
'not_deleted' => 0,
- )
+ ],
);
list($total_pms) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
return $total_pms;
},
- 'latest' => function($uid)
- {
+ 'latest' => function ($uid) {
static $latest_pm;
- if (isset($latest_pm))
+ if (isset($latest_pm)) {
return $latest_pm;
+ }
- $request = Db::$db->query('', '
- SELECT pm.id_pm
+ $request = Db::$db->query(
+ '',
+ 'SELECT pm.id_pm
FROM {db_prefix}personal_messages AS pm
INNER JOIN {db_prefix}pm_recipients AS pmr ON (pm.id_pm = pmr.id_pm)
WHERE (pm.id_member_from = {int:uid} AND pm.deleted_by_sender = {int:not_deleted})
OR (pmr.id_member = {int:uid} AND pmr.deleted = {int:not_deleted})
ORDER BY pm.id_pm DESC
LIMIT {int:limit}',
- array(
+ [
'limit' => 1,
'uid' => $uid,
'not_deleted' => 0,
- )
+ ],
);
list($latest_pm) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -620,22 +617,22 @@ protected function __construct()
return $latest_pm;
},
// Instructions to pass to ExportProfileData background task:
- 'XML' => array(
+ 'XML' => [
'func' => 'getXmlPMs',
'langfile' => 'PersonalMessage',
- ),
- 'HTML' => array(
+ ],
+ 'HTML' => [
'func' => 'getXmlPMs',
'langfile' => 'PersonalMessage',
- ),
- 'XML_XSLT' => array(
+ ],
+ 'XML_XSLT' => [
'func' => 'getXmlPMs',
'langfile' => 'PersonalMessage',
- ),
+ ],
// 'CSV' => array(),
// 'JSON' => array(),
- ),
- );
+ ],
+ ];
Utils::$context['export_datatypes'] = $this->datatypes;
Utils::$context['export_formats'] = self::$formats;
@@ -643,7 +640,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Export::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Export::exportStatic')) {
Export::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/ExportAttachment.php b/Sources/Actions/Profile/ExportAttachment.php
index f15921e8a7..533aa3a0c5 100644
--- a/Sources/Actions/Profile/ExportAttachment.php
+++ b/Sources/Actions/Profile/ExportAttachment.php
@@ -13,14 +13,13 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\Actions\AttachmentDownload;
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\Profile;
use SMF\Utils;
-use SMF\Actions\AttachmentDownload;
-use SMF\Db\DatabaseApi as Db;
/**
* Downloads an attachment that was linked from a profile export.
@@ -34,12 +33,11 @@ class ExportAttachment implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'export_attachment',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -87,34 +85,36 @@ class ExportAttachment implements ActionInterface
*/
public function execute(): void
{
- if (!isset($_GET['t']) || $_GET['t'] !== $this->dltoken)
- {
+ if (!isset($_GET['t']) || $_GET['t'] !== $this->dltoken) {
Utils::sendHttpStatus(403);
+
exit;
}
- if (empty($this->attach))
- {
+ if (empty($this->attach)) {
Utils::sendHttpStatus(404);
+
die('404 File Not Found');
}
// Does this attachment belong to this member?
- $request = Db::$db->query('', '
- SELECT m.id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_topic
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}attachments AS a ON (m.id_msg = a.id_msg)
WHERE m.id_member = {int:uid}
AND a.id_attach = {int:attach}',
- array(
+ [
'uid' => Profile::$member->id,
'attach' => $this->attach,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
Db::$db->free_result($request);
Utils::sendHttpStatus(403);
+
exit;
}
Db::$db->free_result($request);
@@ -144,8 +144,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;
}
@@ -167,8 +168,9 @@ public static function call(): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
$this->idhash = hash_hmac('sha1', Profile::$member->id, Config::getAuthSecret());
$this->dltoken = hash_hmac('sha1', $this->idhash, Config::getAuthSecret());
@@ -178,7 +180,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ExportAttachment::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ExportAttachment::exportStatic')) {
ExportAttachment::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/ExportDownload.php b/Sources/Actions/Profile/ExportDownload.php
index 6b7b428e2a..a3cd3c9ac7 100644
--- a/Sources/Actions/Profile/ExportDownload.php
+++ b/Sources/Actions/Profile/ExportDownload.php
@@ -13,9 +13,8 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
use SMF\Lang;
use SMF\Utils;
@@ -32,12 +31,11 @@ class ExportDownload implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'download_export_file',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -116,66 +114,66 @@ public function execute(): void
$formats = Export::getFormats();
// No access in strict maintenance mode.
- if (!empty(Config::$maintenance) && Config::$maintenance == 2)
- {
+ if (!empty(Config::$maintenance) && Config::$maintenance == 2) {
Utils::sendHttpStatus(404);
+
exit;
}
// We can't give them anything without these.
- if (empty($_GET['t']) || empty($_GET['format']) || !isset($formats[$_GET['format']]))
- {
+ if (empty($_GET['t']) || empty($_GET['format']) || !isset($formats[$_GET['format']])) {
Utils::sendHttpStatus(400);
+
exit;
}
// Make sure they gave the correct authentication token.
// We use these tokens so the user can download without logging in, as required by the GDPR.
- if ($_GET['t'] !== $this->dltoken)
- {
+ if ($_GET['t'] !== $this->dltoken) {
Utils::sendHttpStatus(403);
+
exit;
}
// Obviously we can't give what we don't have.
- if (empty(Config::$modSettings['export_dir']) || !file_exists($this->path))
- {
+ if (empty(Config::$modSettings['export_dir']) || !file_exists($this->path)) {
Utils::sendHttpStatus(404);
+
exit;
}
- $file = array(
+ $file = [
'path' => $this->path,
'filename' => $this->buildFilename(),
'mtime' => filemtime($this->path),
'size' => filesize($this->path),
'mime_type' => $formats[$_GET['format']]['mime'],
- );
+ ];
- $file['etag'] = md5(implode(' ', array($file['filename'], $file['size'], $file['mtime'])));
+ $file['etag'] = md5(implode(' ', [$file['filename'], $file['size'], $file['mtime']]));
// If it hasn't been modified since the last time it was retrieved, there's no need to serve it again.
- if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
- {
+ if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
list($modified_since) = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
- if (strtotime($modified_since) >= $file['mtime'])
- {
+
+ if (strtotime($modified_since) >= $file['mtime']) {
ob_end_clean();
header_remove('content-encoding');
// Answer the question - no, it hasn't been modified ;).
Utils::sendHttpStatus(304);
+
exit;
}
}
// Check whether the ETag was sent back, and cache based on that...
- if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $file['etag']) !== false)
- {
+ if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $file['etag']) !== false) {
ob_end_clean();
header_remove('content-encoding');
Utils::sendHttpStatus(304);
+
exit;
}
@@ -194,8 +192,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;
}
@@ -237,17 +236,16 @@ protected function __construct()
*/
protected function buildFilename(): string
{
- $datatypes = file_exists($this->progressfile) ? array_keys(Utils::jsonDecode(file_get_contents($this->progressfile), true)) : array('profile');
+ $datatypes = file_exists($this->progressfile) ? array_keys(Utils::jsonDecode(file_get_contents($this->progressfile), true)) : ['profile'];
$included_desc = array_map(
- function ($datatype)
- {
+ function ($datatype) {
return Lang::$txt[$datatype];
},
- $datatypes
+ $datatypes,
);
- $dlfilename = array_merge(array(Utils::$context['forum_name'], Utils::$context['member']['username']), $included_desc);
+ $dlfilename = array_merge([Utils::$context['forum_name'], Utils::$context['member']['username']], $included_desc);
$dlfilename = preg_replace('/[^\p{L}\p{M}\p{N}_]+/u', '-', str_replace('"', '', Utils::htmlspecialcharsDecode(strip_tags(implode('_', $dlfilename)))));
$suffix = ($this->part > 1 || file_exists($this->export_dir_slash . '2_' . $this->idhash . '.' . $this->extension)) ? '_' . $this->part : '';
@@ -257,7 +255,8 @@ function ($datatype)
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ExportDownload::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ExportDownload::exportStatic')) {
ExportDownload::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/ForumProfile.php b/Sources/Actions/Profile/ForumProfile.php
index b3b94abbf4..de85e79d23 100644
--- a/Sources/Actions/Profile/ForumProfile.php
+++ b/Sources/Actions/Profile/ForumProfile.php
@@ -13,9 +13,8 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Lang;
use SMF\Profile;
use SMF\User;
@@ -33,12 +32,11 @@ class ForumProfile implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'forumProfile',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -63,8 +61,7 @@ public function execute(): void
{
Profile::$member->loadThemeOptions();
- if (User::$me->allowedTo(array('profile_forum_own', 'profile_forum_any')))
- {
+ if (User::$me->allowedTo(['profile_forum_own', 'profile_forum_any'])) {
Profile::$member->loadCustomFields('forumprofile');
}
@@ -73,18 +70,18 @@ public function execute(): void
Utils::$context['show_preview_button'] = true;
Profile::$member->setupContext(
- array(
- 'avatar_choice',
- 'hr',
- 'personal_text',
- 'hr',
- 'bday1',
- 'usertitle',
- 'signature',
- 'hr',
- 'website_title',
+ [
+ 'avatar_choice',
+ 'hr',
+ 'personal_text',
+ 'hr',
+ 'bday1',
+ 'usertitle',
+ 'signature',
+ 'hr',
+ 'website_title',
'website_url',
- ),
+ ],
);
}
@@ -99,8 +96,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;
}
@@ -122,13 +120,15 @@ public static function call(): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ForumProfile::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ForumProfile::exportStatic')) {
ForumProfile::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/GroupMembership.php b/Sources/Actions/Profile/GroupMembership.php
index b87607b2ea..32e0b63d5f 100644
--- a/Sources/Actions/Profile/GroupMembership.php
+++ b/Sources/Actions/Profile/GroupMembership.php
@@ -13,17 +13,16 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Group;
use SMF\Lang;
use SMF\Profile;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Allows a user to choose, or at least request, group memberships.
@@ -37,12 +36,12 @@ class GroupMembership implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'groupMembership',
- ),
- );
+ 'groupMembership2' => 'groupMembership2',
+ ],
+ ];
/*******************
* Public properties
@@ -76,12 +75,9 @@ class GroupMembership implements ActionInterface
*/
public function execute(): void
{
- if (!empty(Utils::$context['completed_save']))
- {
+ if (!empty(Utils::$context['completed_save'])) {
$this->save();
- }
- else
- {
+ } else {
$this->show();
}
}
@@ -91,8 +87,9 @@ public function execute(): void
*/
public function show(): void
{
- if (!User::$me->allowedTo('manage_membergroups') && !User::$me->is_owner)
+ if (!User::$me->allowedTo('manage_membergroups') && !User::$me->is_owner) {
ErrorHandler::fatalLang('cannot_manage_membergroups', false);
+ }
Utils::$context['primary_group'] = Profile::$member->group_id;
Utils::$context['update_message'] = Lang::$txt['group_membership_msg_' . ($_GET['msg'] ?? '')] ?? '';
@@ -101,41 +98,43 @@ public function show(): void
Utils::$context['can_edit_primary'] = $this->canEditPrimary();
// This beast will be our group holder.
- Utils::$context['groups'] = array(
- 'member' => array(),
- 'available' => array()
- );
+ Utils::$context['groups'] = [
+ 'member' => [],
+ 'available' => [],
+ ];
// Get all the membergroups they can join.
$this->loadCurrentAndAssignableGroups();
// Get any pending join requests.
- $request = Db::$db->query('', '
- SELECT id_group
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_group
FROM {db_prefix}log_group_requests
WHERE id_member = {int:selected_member}
AND status = {int:status_open}',
- array(
+ [
'selected_member' => Profile::$member->id,
'status_open' => 0,
- )
+ ],
);
$open_requests = Db::$db->fetch_all($request);
Db::$db->free_result($request);
// Show the assignable groups in the templates.
- foreach (Profile::$member->current_and_assignable_groups as $id => $group)
- {
+ foreach (Profile::$member->current_and_assignable_groups as $id => $group) {
// Skip "Regular Members" for now.
- if ($id == 0)
+ if ($id == 0) {
continue;
+ }
// Are they in this group?
$member_or_available = in_array($id, Profile::$member->groups) ? 'member' : 'available';
// Can't join private or protected groups.
- if ($group->type < Group::TYPE_REQUESTABLE && $member_or_available == 'available')
+ if ($group->type < Group::TYPE_REQUESTABLE && $member_or_available == 'available') {
continue;
+ }
Utils::$context['groups'][$member_or_available][$id] = $group;
@@ -144,23 +143,22 @@ public function show(): void
}
// If needed, add "Regular Members" on the end.
- if (Utils::$context['can_edit_primary'] || Profile::$member->group_id == Group::REGULAR)
- {
+ if (Utils::$context['can_edit_primary'] || Profile::$member->group_id == Group::REGULAR) {
Utils::$context['groups']['member'][Group::REGULAR] = Profile::$member->assignable_groups[Group::REGULAR];
Utils::$context['groups']['member'][Group::REGULAR]->name = Lang::$txt['regular_members'];
}
// No changing primary group unless you have enough groups!
- if (count(Utils::$context['groups']['member']) < 2)
+ if (count(Utils::$context['groups']['member']) < 2) {
Utils::$context['can_edit_primary'] = false;
+ }
// In the special case that someone is requesting membership of a group, setup some special context vars.
if (
- isset($_REQUEST['request'])
- && isset(Utils::$context['groups']['available'][(int) $_REQUEST['request']])
+ isset($_REQUEST['request'], Utils::$context['groups']['available'][(int) $_REQUEST['request']])
+
&& Utils::$context['groups']['available'][(int) $_REQUEST['request']]->type == Group::TYPE_REQUESTABLE
- )
- {
+ ) {
Utils::$context['group_request'] = Utils::$context['groups']['available'][(int) $_REQUEST['request']];
}
}
@@ -170,12 +168,14 @@ public function show(): void
*/
public function save(): void
{
- if (!isset($_REQUEST['gid']) && !isset($_POST['primary']))
+ if (!isset($_REQUEST['gid']) && !isset($_POST['primary'])) {
return;
+ }
// Let's be extra cautious...
- if (!User::$me->is_owner || empty(Config::$modSettings['show_group_membership']))
+ if (!User::$me->is_owner || empty(Config::$modSettings['show_group_membership'])) {
User::$me->isAllowedTo('manage_membergroups');
+ }
User::$me->checkSession(isset($_GET['gid']) ? 'get' : 'post');
@@ -192,81 +192,80 @@ public function save(): void
// Which groups can they be assigned to?
$this->loadCurrentAndAssignableGroups();
- if (!isset(Profile::$member->current_and_assignable_groups[$new_group_id]))
+ if (!isset(Profile::$member->current_and_assignable_groups[$new_group_id])) {
ErrorHandler::fatalLang('cannot_manage_membergroups', false);
+ }
// Just for improved legibility...
$new_group_info = Profile::$member->current_and_assignable_groups[$new_group_id];
// Can't request a non-requestable group.
- if ($this->change_type == 'request' && $new_group_info['type'] != 2)
+ if ($this->change_type == 'request' && $new_group_info['type'] != 2) {
ErrorHandler::fatalLang('no_access', false);
+ }
- if ($this->change_type == 'free')
- {
+ if ($this->change_type == 'free') {
// Can't freely join or leave private or protected groups.
- if ($new_group_info['type'] <= 1)
+ if ($new_group_info['type'] <= 1) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Can't leave a requestable group that you're not part of.
- if ($new_group_info['type'] == 2 && !in_array($new_group_id, Profile::$member->groups))
+ if ($new_group_info['type'] == 2 && !in_array($new_group_id, Profile::$member->groups)) {
ErrorHandler::fatalLang('no_access', false);
+ }
}
// Whatever we are doing, we need to determine if changing primary is possible.
$can_edit_primary = $this->canEditPrimary($new_group_id);
- switch ($this->change_type)
- {
+ switch ($this->change_type) {
// If they're requesting, add the note then return.
case 'request':
$this->sendJoinRequest($new_group_id);
+
return;
// Leaving/joining a group.
case 'free':
// Are they leaving?
- if (Profile::$member->group_id == $new_group_id)
- {
+ if (Profile::$member->group_id == $new_group_id) {
$new_primary = $can_edit_primary ? 0 : Profile::$member->group_id;
- }
- elseif (in_array($new_group_id, Profile::$member->additional_groups))
- {
- $new_additional_groups = array_diff($new_additional_groups, array($new_group_id));
+ } elseif (in_array($new_group_id, Profile::$member->additional_groups)) {
+ $new_additional_groups = array_diff($new_additional_groups, [$new_group_id]);
}
// ... if not, must be joining.
- else
- {
+ else {
// If they're just a regular member and this can be a primary group,
// then make it the primary.
- if (Profile::$member->group_id == 0 && $can_edit_primary && !empty($new_group_info['can_be_primary']))
- {
+ if (Profile::$member->group_id == 0 && $can_edit_primary && !empty($new_group_info['can_be_primary'])) {
$new_primary = $new_group_id;
}
// Otherwise, make it an addtional group.
- else
- {
+ else {
$new_additional_groups[] = $new_group_id;
}
}
+
break;
// Finally, we must be setting the primary.
default:
- if (Profile::$member->group_id != 0)
+ if (Profile::$member->group_id != 0) {
$new_additional_groups[] = Profile::$member->group_id;
+ }
- if (in_array($new_group_id, $new_additional_groups))
- {
- $new_additional_groups = array_diff($new_additional_groups, array($new_group_id));
+ if (in_array($new_group_id, $new_additional_groups)) {
+ $new_additional_groups = array_diff($new_additional_groups, [$new_group_id]);
}
$new_primary = $new_group_id;
+
break;
}
// Run the changes through the validation method for group membership.
- Profile::$member->validateGroups($new_primary, $new_additional_groups ?? array());
+ Profile::$member->validateGroups($new_primary, $new_additional_groups ?? []);
Profile::$member->new_data['id_group'] = $new_primary;
}
@@ -281,8 +280,9 @@ public function save(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -327,8 +327,9 @@ public static function groupMembership2(int $memID): string
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
/**
@@ -336,23 +337,24 @@ protected function __construct()
*/
protected function loadCurrentAndAssignableGroups(): void
{
- if (isset(Profile::$member->current_and_assignable_groups))
+ if (isset(Profile::$member->current_and_assignable_groups)) {
return;
+ }
- if (empty(Profile::$member->assignable_groups))
+ if (empty(Profile::$member->assignable_groups)) {
Profile::$member->loadAssignableGroups();
+ }
$current_and_assignable_groups = Profile::$member->assignable_groups;
// If they are already in an unassignable group, show that too.
$current_unassignable_groups = array_intersect(Profile::$member->groups, Group::getUnassignable());
- if ($current_unassignable_groups !== array())
- {
- foreach (Group::load($current_unassignable_groups) as $group)
- {
- if ($group->min_posts > -1)
+ if ($current_unassignable_groups !== []) {
+ foreach (Group::load($current_unassignable_groups) as $group) {
+ if ($group->min_posts > -1) {
continue;
+ }
$group->is_primary = $group->id == Profile::$member->group_id;
$group->is_additional = in_array($group->id, Profile::$member->additional_groups);
@@ -363,13 +365,13 @@ protected function loadCurrentAndAssignableGroups(): void
uasort(
$current_and_assignable_groups,
- function($a, $b)
- {
- if ($a['id'] >= 4 && $b['id'] >= 4)
+ function ($a, $b) {
+ if ($a['id'] >= 4 && $b['id'] >= 4) {
return $a['name'] <=> $b['name'];
+ }
return $a['id'] <=> $b['id'];
- }
+ },
);
Profile::$member->current_and_assignable_groups = $current_and_assignable_groups;
@@ -379,18 +381,15 @@ function($a, $b)
* Figures out whether the current user can change the primary membergroup
* of the member whose profile is being viewed.
*/
- protected function canEditPrimary(int $new_group_id = null): bool
+ protected function canEditPrimary(?int $new_group_id = null): bool
{
$this->loadCurrentAndAssignableGroups();
// Hidden groups cannot be primary groups.
- if (isset($new_group_id))
- {
+ if (isset($new_group_id)) {
$can_edit_primary = Profile::$member->current_and_assignable_groups[$new_group_id]->can_be_primary;
- }
- else
- {
- $possible_primary_groups = array_filter(Profile::$member->current_and_assignable_groups, fn($group) => !empty($group->can_be_primary));
+ } else {
+ $possible_primary_groups = array_filter(Profile::$member->current_and_assignable_groups, fn ($group) => !empty($group->can_be_primary));
$can_edit_primary = !empty($possible_primary_groups);
}
@@ -407,28 +406,31 @@ protected function canEditPrimary(int $new_group_id = null): bool
*/
protected function sendJoinRequest(int $new_group_id): void
{
- $request = Db::$db->query('', '
- SELECT id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}log_group_requests
WHERE id_member = {int:selected_member}
AND id_group = {int:selected_group}
AND status = {int:status_open}',
- array(
+ [
'selected_member' => Profile::$member->id,
'selected_group' => $new_group_id,
'status_open' => 0,
- )
+ ],
);
$already_requested = Db::$db->num_rows($request) != 0;
Db::$db->free_result($request);
- if ($already_requested)
+ if ($already_requested) {
ErrorHandler::fatalLang('profile_error_already_requested_group');
+ }
// Log the request.
- Db::$db->insert('',
+ Db::$db->insert(
+ '',
'{db_prefix}log_group_requests',
- array(
+ [
'id_member' => 'int',
'id_group' => 'int',
'time_applied' => 'int',
@@ -438,8 +440,8 @@ protected function sendJoinRequest(int $new_group_id): void
'member_name_acted' => 'string',
'time_acted' => 'int',
'act_reason' => 'string',
- ),
- array(
+ ],
+ [
Profile::$member->id,
$new_group_id,
time(),
@@ -449,43 +451,42 @@ protected function sendJoinRequest(int $new_group_id): void
'',
0,
'',
- ),
- array('id_request')
+ ],
+ ['id_request'],
);
// Set up some data for our background task...
- $data = Utils::jsonEncode(array(
+ $data = Utils::jsonEncode([
'id_member' => Profile::$member->id,
'member_name' => User::$me->name,
'id_group' => $new_group_id,
'group_name' => Profile::$member->assignable_groups[$new_group_id]['name'],
'reason' => $_POST['reason'],
'time' => time(),
- ));
+ ]);
// Add a background task to handle notifying people of this request
Db::$db->insert(
'insert',
'{db_prefix}background_tasks',
- array(
- 'task_file' => 'string-255',
+ [
'task_class' => 'string-255',
'task_data' => 'string',
'claimed_time' => 'int',
- ),
- array(
- '$sourcedir/tasks/GroupReq_Notify.php',
- 'SMF\Tasks\GroupReq_Notify',
+ ],
+ [
+ 'SMF\\Tasks\\GroupReq_Notify',
$data,
0,
- ),
- array()
+ ],
+ [],
);
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\GroupMembership::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\GroupMembership::exportStatic')) {
GroupMembership::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/IgnoreBoards.php b/Sources/Actions/Profile/IgnoreBoards.php
index 57db9c08cf..f5e6de2ed8 100644
--- a/Sources/Actions/Profile/IgnoreBoards.php
+++ b/Sources/Actions/Profile/IgnoreBoards.php
@@ -13,16 +13,15 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Category;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Profile;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Handles the "ignored boards" section of the profile (if enabled)
@@ -36,12 +35,11 @@ class IgnoreBoards implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ignoreboards',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -65,62 +63,63 @@ class IgnoreBoards implements ActionInterface
public function execute(): void
{
// Have the admins enabled this option?
- if (empty(Config::$modSettings['allow_ignore_boards']))
+ if (empty(Config::$modSettings['allow_ignore_boards'])) {
ErrorHandler::fatalLang('ignoreboards_disallowed', 'user');
+ }
// Find all the boards this user is allowed to see.
Utils::$context['num_boards'] = 0;
- Utils::$context['categories'] = array();
+ Utils::$context['categories'] = [];
- $request = Db::$db->query('order_by_board_order', '
- SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level,
+ $request = Db::$db->query(
+ 'order_by_board_order',
+ 'SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level,
' . (!empty(Profile::$member->data['ignore_boards']) ? 'b.id_board IN ({array_int:ignore_boards})' : '0') . ' AS is_ignored
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:empty_string}',
- array(
- 'ignore_boards' => !empty(Profile::$member->data['ignore_boards']) ? explode(',', Profile::$member->data['ignore_boards']) : array(),
+ [
+ 'ignore_boards' => !empty(Profile::$member->data['ignore_boards']) ? explode(',', Profile::$member->data['ignore_boards']) : [],
'empty_string' => '',
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Utils::$context['num_boards']++;
// This category hasn't been set up yet..
- if (!isset(Utils::$context['categories'][$row['id_cat']]))
- {
- Utils::$context['categories'][$row['id_cat']] = array(
+ if (!isset(Utils::$context['categories'][$row['id_cat']])) {
+ Utils::$context['categories'][$row['id_cat']] = [
'id' => $row['id_cat'],
'name' => $row['cat_name'],
- 'boards' => array()
- );
+ 'boards' => [],
+ ];
}
// Set this board up, and let the template know when it's a child. (indent them..)
- 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'],
'selected' => $row['is_ignored'],
- );
+ ];
}
Db::$db->free_result($request);
Category::sort(Utils::$context['categories']);
// Now, let's sort the list of categories into the boards for templates that like that.
- $temp_boards = array();
- foreach (Utils::$context['categories'] as $category)
- {
+ $temp_boards = [];
+
+ foreach (Utils::$context['categories'] as $category) {
// Include a list of boards per category for easy toggling.
Utils::$context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
- $temp_boards[] = array(
+ $temp_boards[] = [
'name' => $category['name'],
- 'child_ids' => array_keys($category['boards'])
- );
+ 'child_ids' => array_keys($category['boards']),
+ ];
$temp_boards = array_merge($temp_boards, array_values($category['boards']));
}
@@ -128,18 +127,15 @@ public function execute(): void
$max_boards = max(2, ceil(count($temp_boards) / 2));
// Now, alternate them so they can be shown left and right ;).
- Utils::$context['board_columns'] = array();
- for ($i = 0; $i < $max_boards; $i++)
- {
+ Utils::$context['board_columns'] = [];
+
+ for ($i = 0; $i < $max_boards; $i++) {
Utils::$context['board_columns'][] = $temp_boards[$i];
- if (isset($temp_boards[$i + $max_boards]))
- {
+ if (isset($temp_boards[$i + $max_boards])) {
Utils::$context['board_columns'][] = $temp_boards[$i + $max_boards];
- }
- else
- {
- Utils::$context['board_columns'][] = array();
+ } else {
+ Utils::$context['board_columns'][] = [];
}
}
@@ -157,8 +153,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;
}
@@ -180,13 +177,15 @@ public static function call(): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\IgnoreBoards::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\IgnoreBoards::exportStatic')) {
IgnoreBoards::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/IssueWarning.php b/Sources/Actions/Profile/IssueWarning.php
index d1d427276d..95ef59ad53 100644
--- a/Sources/Actions/Profile/IssueWarning.php
+++ b/Sources/Actions/Profile/IssueWarning.php
@@ -13,21 +13,20 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\ItemList;
use SMF\Lang;
use SMF\Msg;
+use SMF\PersonalMessage\PM;
use SMF\Profile;
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
-use SMF\PersonalMessage\PM;
/**
* Rename here and in the exportStatic call at the end of the file.
@@ -41,12 +40,13 @@ class IssueWarning implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'list_getUserWarnings' => 'list_getUserWarnings',
+ 'list_getUserWarningCount' => 'list_getUserWarningCount',
+ 'issueWarning' => 'issueWarning',
+ ],
+ ];
/*******************
* Public properties
@@ -57,7 +57,7 @@ class IssueWarning implements ActionInterface
*
* This stores any legitimate errors.
*/
- public array $issueErrors = array();
+ public array $issueErrors = [];
/****************************
* Internal static properties
@@ -81,8 +81,7 @@ class IssueWarning implements ActionInterface
public function execute(): void
{
// Doesn't hurt to be overly cautious.
- if (empty(Config::$modSettings['warning_enable']) || (User::$me->is_owner && !Profile::$member->warning) || !User::$me->allowedTo('issue_warning'))
- {
+ if (empty(Config::$modSettings['warning_enable']) || (User::$me->is_owner && !Profile::$member->warning) || !User::$me->allowedTo('issue_warning')) {
ErrorHandler::fatalLang('no_access', false);
}
@@ -96,22 +95,22 @@ public function execute(): void
Utils::$context['min_allowed'] = 0;
Utils::$context['max_allowed'] = 100;
- if (Utils::$context['warning_limit'] > 0)
- {
+ if (Utils::$context['warning_limit'] > 0) {
// Make sure we cannot go outside of our limit for the day.
- $request = Db::$db->query('', '
- SELECT SUM(counter)
+ $request = Db::$db->query(
+ '',
+ 'SELECT SUM(counter)
FROM {db_prefix}log_comments
WHERE id_recipient = {int:selected_member}
AND id_member = {int:current_member}
AND comment_type = {string:warning}
AND log_time > {int:day_time_period}',
- array(
+ [
'current_member' => User::$me->id,
'selected_member' => Profile::$member->id,
'day_time_period' => time() - 86400,
'warning' => 'warning',
- )
+ ],
);
list($current_applied) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -122,148 +121,149 @@ public function execute(): void
}
// Defaults.
- Utils::$context['warning_data'] = array(
+ Utils::$context['warning_data'] = [
'reason' => '',
'notify' => '',
'notify_subject' => '',
'notify_body' => '',
- );
+ ];
// Are we saving?
- if (isset($_POST['save']))
+ if (isset($_POST['save'])) {
$this->save();
+ }
- if (isset($_POST['preview']))
+ if (isset($_POST['preview'])) {
$this->preview();
+ }
- if (!empty($this->issueErrors))
- {
+ if (!empty($this->issueErrors)) {
// Fill in the suite of errors.
- Utils::$context['post_errors'] = array();
+ Utils::$context['post_errors'] = [];
- foreach ($this->issueErrors as $error)
+ foreach ($this->issueErrors as $error) {
Utils::$context['post_errors'][] = Lang::$txt[$error];
+ }
}
Utils::$context['page_title'] = Lang::$txt['profile_issue_warning'];
// Work our the various levels.
- Utils::$context['level_effects'] = array(
+ Utils::$context['level_effects'] = [
0 => Lang::$txt['profile_warning_effect_none'],
Config::$modSettings['warning_watch'] => Lang::$txt['profile_warning_effect_watch'],
Config::$modSettings['warning_moderate'] => Lang::$txt['profile_warning_effect_moderation'],
Config::$modSettings['warning_mute'] => Lang::$txt['profile_warning_effect_mute'],
- );
+ ];
Utils::$context['current_level'] = 0;
- foreach (Utils::$context['level_effects'] as $limit => $dummy)
- {
- if (Utils::$context['member']['warning'] >= $limit)
+ foreach (Utils::$context['level_effects'] as $limit => $dummy) {
+ if (Utils::$context['member']['warning'] >= $limit) {
Utils::$context['current_level'] = $limit;
+ }
}
- $list_options = array(
+ $list_options = [
'id' => 'view_warnings',
'title' => Lang::$txt['profile_viewwarning_previous_warnings'],
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['profile_viewwarning_no_warnings'],
'base_href' => Config::$scripturl . '?action=profile;area=issuewarning;sa=user;u=' . Profile::$member->id,
'default_sort_col' => 'log_time',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getUserWarnings',
- 'params' => array(),
- ),
- 'get_count' => array(
+ 'params' => [],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getUserWarningCount',
- 'params' => array(),
- ),
- 'columns' => array(
- 'issued_by' => array(
- 'header' => array(
+ 'params' => [],
+ ],
+ 'columns' => [
+ 'issued_by' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_issued'],
'style' => 'width: 20%;',
- ),
- 'data' => array(
- 'function' => function($warning)
- {
+ ],
+ 'data' => [
+ 'function' => function ($warning) {
return $warning['issuer']['link'];
},
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lc.member_name DESC',
'reverse' => 'lc.member_name',
- ),
- ),
- 'log_time' => array(
- 'header' => array(
+ ],
+ ],
+ 'log_time' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_time'],
'style' => 'width: 30%;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lc.log_time DESC',
'reverse' => 'lc.log_time',
- ),
- ),
- 'reason' => array(
- 'header' => array(
+ ],
+ ],
+ 'reason' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_reason'],
- ),
- 'data' => array(
- 'function' => function($warning)
- {
+ ],
+ 'data' => [
+ 'function' => function ($warning) {
$ret = '
' . $warning['reason'] . '
';
- if (!empty($warning['id_notice']))
+ if (!empty($warning['id_notice'])) {
$ret .= '
';
+ }
return $ret;
},
- ),
- ),
- 'level' => array(
- 'header' => array(
+ ],
+ ],
+ 'level' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_level'],
'style' => 'width: 6%;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'counter',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lc.counter DESC',
'reverse' => 'lc.counter',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
// Create the list for viewing.
new ItemList($list_options);
// Are they warning because of a message?
- if (isset($_REQUEST['msg']) && 0 < (int) $_REQUEST['msg'])
- {
- $request = Db::$db->query('', '
- SELECT m.subject
+ if (isset($_REQUEST['msg']) && 0 < (int) $_REQUEST['msg']) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.subject
FROM {db_prefix}messages AS m
WHERE m.id_msg = {int:message}
AND {query_see_message_board}
LIMIT 1',
- array(
+ [
'message' => (int) $_REQUEST['msg'],
- )
+ ],
);
- if (Db::$db->num_rows($request) != 0)
- {
+
+ if (Db::$db->num_rows($request) != 0) {
Utils::$context['warning_for_message'] = (int) $_REQUEST['msg'];
list(Utils::$context['warned_message_subject']) = Db::$db->fetch_row($request);
}
@@ -271,59 +271,56 @@ public function execute(): void
}
// Didn't find the message?
- if (empty(Utils::$context['warning_for_message']))
- {
+ if (empty(Utils::$context['warning_for_message'])) {
Utils::$context['warning_for_message'] = 0;
Utils::$context['warned_message_subject'] = '';
}
// Any custom templates?
- Utils::$context['notification_templates'] = array();
+ Utils::$context['notification_templates'] = [];
- $request = Db::$db->query('', '
- SELECT recipient_name AS template_title, body
+ $request = Db::$db->query(
+ '',
+ 'SELECT recipient_name AS template_title, body
FROM {db_prefix}log_comments
WHERE comment_type = {literal:warntpl}
AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})',
- array(
+ [
'generic' => 0,
'current_member' => User::$me->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// If we're not warning for a message skip any that are.
- if (!Utils::$context['warning_for_message'] && strpos($row['body'], '{MESSAGE}') !== false)
- {
+ if (!Utils::$context['warning_for_message'] && strpos($row['body'], '{MESSAGE}') !== false) {
continue;
}
- Utils::$context['notification_templates'][] = array(
+ Utils::$context['notification_templates'][] = [
'title' => $row['template_title'],
'body' => $row['body'],
- );
+ ];
}
Db::$db->free_result($request);
// Setup the "default" templates.
- foreach (array('spamming', 'offence', 'insulting') as $type)
- {
- Utils::$context['notification_templates'][] = array(
+ foreach (['spamming', 'offence', 'insulting'] as $type) {
+ Utils::$context['notification_templates'][] = [
'title' => Lang::$txt['profile_warning_notify_title_' . $type],
'body' => sprintf(Lang::$txt['profile_warning_notify_template_outline' . (!empty(Utils::$context['warning_for_message']) ? '_post' : '')], Lang::$txt['profile_warning_notify_for_' . $type]),
- );
+ ];
}
// Replace all the common variables in the templates.
- foreach (Utils::$context['notification_templates'] as $k => $name)
- {
- Utils::$context['notification_templates'][$k]['body'] = strtr($name['body'], array(
+ foreach (Utils::$context['notification_templates'] as $k => $name) {
+ Utils::$context['notification_templates'][$k]['body'] = strtr($name['body'], [
'{MEMBER}' => Utils::htmlspecialcharsDecode(Utils::$context['member']['name']),
'{MESSAGE}' => '[url=' . Config::$scripturl . '?msg=' . Utils::$context['warning_for_message'] . ']' . Utils::htmlspecialcharsDecode(Utils::$context['warned_message_subject']) . '[/url]',
'{SCRIPTURL}' => Config::$scripturl,
'{FORUMNAME}' => Config::$mbname,
- '{REGARDS}' => sprintf(Lang::$txt['regards_team'], Utils::$context['forum_name'])
- ));
+ '{REGARDS}' => sprintf(Lang::$txt['regards_team'], Utils::$context['forum_name']),
+ ]);
}
}
@@ -338,8 +335,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;
}
@@ -362,10 +360,11 @@ public static function call(): void
*/
public static function list_getUserWarnings(int $start, int $items_per_page, string $sort): array
{
- $previous_warnings = array();
+ $previous_warnings = [];
- $request = Db::$db->query('', '
- SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name,
+ $request = Db::$db->query(
+ '',
+ 'SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name,
lc.log_time, lc.body, lc.counter, lc.id_notice
FROM {db_prefix}log_comments AS lc
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
@@ -373,25 +372,25 @@ public static function list_getUserWarnings(int $start, int $items_per_page, str
AND lc.comment_type = {literal:warning}
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array(
+ [
'selected_member' => Profile::$member->id,
'sort' => $sort,
'start' => $start,
'max' => $items_per_page,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $previous_warnings[] = array(
- 'issuer' => array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $previous_warnings[] = [
+ 'issuer' => [
'id' => $row['id_member'],
'link' => $row['id_member'] ? (' ' . $row['member_name'] . '') : $row['member_name'],
- ),
+ ],
'time' => Time::create('@' . $row['log_time'])->format(),
'reason' => $row['body'],
'counter' => $row['counter'] > 0 ? '+' . $row['counter'] : $row['counter'],
'id_notice' => $row['id_notice'],
- );
+ ];
}
Db::$db->free_result($request);
@@ -405,14 +404,15 @@ public static function list_getUserWarnings(int $start, int $items_per_page, str
*/
public static function list_getUserWarningCount(): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_comments
WHERE id_recipient = {int:selected_member}
AND comment_type = {literal:warning}',
- array(
+ [
'selected_member' => Profile::$member->id,
- )
+ ],
);
list($total_warnings) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -446,8 +446,9 @@ public static function issueWarning(int $memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
// Get all the actual settings.
list(Config::$modSettings['warning_enable'], Config::$modSettings['user_limit']) = explode(',', Config::$modSettings['warning_settings']);
@@ -467,8 +468,9 @@ protected function save(): void
// This cannot be empty!
$_POST['warn_reason'] = isset($_POST['warn_reason']) ? trim($_POST['warn_reason']) : '';
- if ($_POST['warn_reason'] == '' && !User::$me->is_owner)
+ if ($_POST['warn_reason'] == '' && !User::$me->is_owner) {
$this->issueErrors[] = 'warning_no_reason';
+ }
$_POST['warn_reason'] = Utils::htmlspecialchars($_POST['warn_reason']);
@@ -478,46 +480,45 @@ protected function save(): void
// Do we actually have to issue them with a PM?
$id_notice = 0;
- if (!empty($_POST['warn_notify']) && empty($this->issueErrors))
- {
+
+ if (!empty($_POST['warn_notify']) && empty($this->issueErrors)) {
$_POST['warn_sub'] = trim($_POST['warn_sub']);
$_POST['warn_body'] = trim($_POST['warn_body']);
- if (empty($_POST['warn_sub']) || empty($_POST['warn_body']))
- {
+ if (empty($_POST['warn_sub']) || empty($_POST['warn_body'])) {
$this->issueErrors[] = 'warning_notify_blank';
}
// Send the PM?
- else
- {
+ else {
PM::send(
- array(
- 'to' => array(Profile::$member->id),
- 'bcc' => array(),
- ),
+ [
+ 'to' => [Profile::$member->id],
+ 'bcc' => [],
+ ],
$_POST['warn_sub'],
$_POST['warn_body'],
false,
- array(
+ [
'id' => 0,
'name' => Utils::$context['forum_name_html_safe'],
'username' => Utils::$context['forum_name_html_safe'],
- )
+ ],
);
// Log the notice!
- $id_notice = Db::$db->insert('',
+ $id_notice = Db::$db->insert(
+ '',
'{db_prefix}log_member_notices',
- array(
+ [
'subject' => 'string-255',
'body' => 'string-65534',
- ),
- array(
+ ],
+ [
Utils::htmlspecialchars($_POST['warn_sub']),
Utils::htmlspecialchars($_POST['warn_body']),
- ),
- array('id_notice'),
- 1
+ ],
+ ['id_notice'],
+ 1,
);
}
}
@@ -526,14 +527,13 @@ protected function save(): void
$level_change = $_POST['warning_level'] - Profile::$member->warning;
// No errors? Proceed! Only log if you're not the owner.
- if (empty($this->issueErrors))
- {
+ if (empty($this->issueErrors)) {
// Log what we've done!
- if (!User::$me->is_owner)
- {
- Db::$db->insert('',
+ if (!User::$me->is_owner) {
+ Db::$db->insert(
+ '',
'{db_prefix}log_comments',
- array(
+ [
'id_member' => 'int',
'member_name' => 'string',
'comment_type' => 'string',
@@ -543,8 +543,8 @@ protected function save(): void
'id_notice' => 'int',
'counter' => 'int',
'body' => 'string-65534',
- ),
- array(
+ ],
+ [
User::$me->id,
User::$me->name,
'warning',
@@ -554,26 +554,24 @@ protected function save(): void
(int) $id_notice,
$level_change,
$_POST['warn_reason'],
- ),
- array('id_comment')
+ ],
+ ['id_comment'],
);
}
// Make the change.
- User::updateMemberData(Profile::$member->id, array('warning' => $_POST['warning_level']));
+ User::updateMemberData(Profile::$member->id, ['warning' => $_POST['warning_level']]);
// Leave a lovely message.
Utils::$context['profile_updated'] = User::$me->is_owner ? Lang::$txt['profile_updated_own'] : Lang::$txt['profile_warning_success'];
- }
- else
- {
+ } else {
// Try to remember some bits.
- Utils::$context['warning_data'] = array(
+ Utils::$context['warning_data'] = [
'reason' => $_POST['warn_reason'],
'notify' => !empty($_POST['warn_notify']),
- 'notify_subject' => isset($_POST['warn_sub']) ? $_POST['warn_sub'] : '',
- 'notify_body' => isset($_POST['warn_body']) ? $_POST['warn_body'] : '',
- );
+ 'notify_subject' => $_POST['warn_sub'] ?? '',
+ 'notify_body' => $_POST['warn_body'] ?? '',
+ ];
}
// Show the new improved warning level.
@@ -589,28 +587,29 @@ protected function preview(): void
Utils::$context['preview_subject'] = !empty($_POST['warn_sub']) ? trim(Utils::htmlspecialchars($_POST['warn_sub'])) : '';
- if (empty($_POST['warn_sub']) || empty($_POST['warn_body']))
+ if (empty($_POST['warn_sub']) || empty($_POST['warn_body'])) {
$this->issueErrors[] = 'warning_notify_blank';
+ }
- if (!empty($_POST['warn_body']))
- {
+ if (!empty($_POST['warn_body'])) {
Msg::preparsecode($warning_body);
$warning_body = BBCodeParser::load()->parse($warning_body);
}
// Try to remember some bits.
- Utils::$context['warning_data'] = array(
+ Utils::$context['warning_data'] = [
'reason' => $_POST['warn_reason'],
'notify' => !empty($_POST['warn_notify']),
- 'notify_subject' => isset($_POST['warn_sub']) ? $_POST['warn_sub'] : '',
- 'notify_body' => isset($_POST['warn_body']) ? $_POST['warn_body'] : '',
+ 'notify_subject' => $_POST['warn_sub'] ?? '',
+ 'notify_body' => $_POST['warn_body'] ?? '',
'body_preview' => $warning_body,
- );
+ ];
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\IssueWarning::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\IssueWarning::exportStatic')) {
IssueWarning::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/Main.php b/Sources/Actions/Profile/Main.php
index 21dc6b2b8b..144677749a 100644
--- a/Sources/Actions/Profile/Main.php
+++ b/Sources/Actions/Profile/Main.php
@@ -13,10 +13,10 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -27,7 +27,6 @@
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This class has the primary job of showing and editing people's profiles.
@@ -43,12 +42,11 @@ class Main implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'modifyProfile' => 'ModifyProfile',
+ ],
+ ];
/*******************
* Public properties
@@ -57,7 +55,6 @@ class Main implements ActionInterface
/**
* @var array
*
- *
* Defines the menu structure for the profile area.
* See {@link Menu.php Menu.php} for details!
*
@@ -119,159 +116,159 @@ class Main implements ActionInterface
* array $permission: Array of permissions to determine who can access
* this area. Should contain arrays $own and $any.
*/
- public array $profile_areas = array(
- 'info' => array(
+ public array $profile_areas = [
+ 'info' => [
'title' => 'profileInfo',
- 'areas' => array(
- 'summary' => array(
+ 'areas' => [
+ 'summary' => [
'label' => 'summary',
'function' => __NAMESPACE__ . '\\Summary::call',
'sub_template' => 'summary',
'icon' => 'administration',
- 'permission' => array(
+ 'permission' => [
'own' => 'is_not_guest',
'any' => 'profile_view',
- ),
- ),
- 'popup' => array(
+ ],
+ ],
+ 'popup' => [
'function' => __NAMESPACE__ . '\\Popup::call',
'sub_template' => 'profile_popup',
- 'permission' => array(
+ 'permission' => [
'own' => 'is_not_guest',
- 'any' => array(),
- ),
+ 'any' => [],
+ ],
'select' => 'summary',
- ),
- 'alerts_popup' => array(
+ ],
+ 'alerts_popup' => [
'function' => __NAMESPACE__ . '\\AlertsPopup::call',
'sub_template' => 'alerts_popup',
- 'permission' => array(
+ 'permission' => [
'own' => 'is_not_guest',
- 'any' => array(),
- ),
+ 'any' => [],
+ ],
'select' => 'summary',
- ),
- 'statistics' => array(
+ ],
+ 'statistics' => [
'label' => 'statPanel',
'function' => __NAMESPACE__ . '\\StatPanel::call',
'sub_template' => 'statPanel',
'icon' => 'stats',
- 'permission' => array(
+ 'permission' => [
'own' => 'is_not_guest',
'any' => 'profile_view',
- ),
- ),
- 'showposts' => array(
+ ],
+ ],
+ 'showposts' => [
'label' => 'showPosts',
'function' => __NAMESPACE__ . '\\ShowPosts::call',
'sub_template' => 'showPosts',
'icon' => 'posts',
- 'subsections' => array(
- 'messages' => array(
+ 'subsections' => [
+ 'messages' => [
'label' => 'showMessages',
- 'permission' => array('is_not_guest', 'profile_view'),
- ),
- 'topics' => array(
+ 'permission' => ['is_not_guest', 'profile_view'],
+ ],
+ 'topics' => [
'label' => 'showTopics',
- 'permission' => array('is_not_guest', 'profile_view'),
- ),
- 'unwatchedtopics' => array(
+ 'permission' => ['is_not_guest', 'profile_view'],
+ ],
+ 'unwatchedtopics' => [
'label' => 'showUnwatched',
- 'permission' => array('is_not_guest', 'profile_view'),
+ 'permission' => ['is_not_guest', 'profile_view'],
'enabled' => true,
- ),
- 'attach' => array(
+ ],
+ 'attach' => [
'label' => 'showAttachments',
- 'permission' => array('is_not_guest', 'profile_view'),
- ),
- ),
- 'permission' => array(
+ 'permission' => ['is_not_guest', 'profile_view'],
+ ],
+ ],
+ 'permission' => [
'own' => 'is_not_guest',
'any' => 'profile_view',
- ),
- ),
- 'showdrafts' => array(
+ ],
+ ],
+ 'showdrafts' => [
'label' => 'drafts_show',
'function' => 'SMF\\Draft::showInProfile',
'icon' => 'drafts',
'enabled' => true,
- 'permission' => array(
+ 'permission' => [
'own' => 'is_not_guest',
- 'any' => array(),
- ),
- ),
- 'showalerts' => array(
+ 'any' => [],
+ ],
+ ],
+ 'showalerts' => [
'label' => 'alerts_show',
'function' => __NAMESPACE__ . '\\ShowAlerts::call',
'sub_template' => 'showAlerts',
'icon' => 'alerts',
- 'permission' => array(
+ 'permission' => [
'own' => 'is_not_guest',
- 'any' => array(),
- ),
- ),
- 'permissions' => array(
+ 'any' => [],
+ ],
+ ],
+ 'permissions' => [
'label' => 'showPermissions',
'function' => __NAMESPACE__ . '\\ShowPermissions::call',
'sub_template' => 'showPermissions',
'icon' => 'permissions',
- 'permission' => array(
+ 'permission' => [
'own' => 'manage_permissions',
'any' => 'manage_permissions',
- ),
- ),
- 'tracking' => array(
+ ],
+ ],
+ 'tracking' => [
'label' => 'trackUser',
'function' => __NAMESPACE__ . '\\Tracking::call',
'sub_template' => 'tracking',
'icon' => 'logs',
- 'subsections' => array(
- 'activity' => array(
+ 'subsections' => [
+ 'activity' => [
'label' => 'trackActivity',
'permission' => 'moderate_forum',
- ),
- 'ip' => array(
+ ],
+ 'ip' => [
'label' => 'trackIP',
'permission' => 'moderate_forum',
- ),
- 'edits' => array(
+ ],
+ 'edits' => [
'label' => 'trackEdits',
'permission' => 'moderate_forum',
'enabled' => true,
- ),
- 'groupreq' => array(
+ ],
+ 'groupreq' => [
'label' => 'trackGroupRequests',
'permission' => 'approve_group_requests',
'enabled' => true,
- ),
- 'logins' => array(
+ ],
+ 'logins' => [
'label' => 'trackLogins',
'permission' => 'moderate_forum',
'enabled' => true,
- ),
- ),
- 'permission' => array(
- 'own' => array('moderate_forum', 'approve_group_requests'),
- 'any' => array('moderate_forum', 'approve_group_requests'),
- ),
- ),
- 'viewwarning' => array(
+ ],
+ ],
+ 'permission' => [
+ 'own' => ['moderate_forum', 'approve_group_requests'],
+ 'any' => ['moderate_forum', 'approve_group_requests'],
+ ],
+ ],
+ 'viewwarning' => [
'label' => 'profile_view_warnings',
'function' => __NAMESPACE__ . '\\ViewWarning::call',
'sub_template' => 'viewWarning',
'icon' => 'warning',
'enabled' => true,
- 'permission' => array(
- 'own' => array('view_warning_own', 'view_warning_any', 'issue_warning', 'moderate_forum'),
- 'any' => array('view_warning_any', 'issue_warning', 'moderate_forum'),
- ),
- ),
- ),
- ),
- 'edit_profile' => array(
+ 'permission' => [
+ 'own' => ['view_warning_own', 'view_warning_any', 'issue_warning', 'moderate_forum'],
+ 'any' => ['view_warning_any', 'issue_warning', 'moderate_forum'],
+ ],
+ ],
+ ],
+ ],
+ 'edit_profile' => [
'title' => 'forumprofile',
- 'areas' => array(
- 'account' => array(
+ 'areas' => [
+ 'account' => [
'label' => 'account',
'function' => __NAMESPACE__ . '\\Account::call',
'sub_template' => 'edit_options',
@@ -280,12 +277,12 @@ class Main implements ActionInterface
'sc' => 'post',
'token' => 'profile-ac%u',
'password' => true,
- 'permission' => array(
- 'own' => array('profile_identity_any', 'profile_identity_own', 'profile_password_any', 'profile_password_own', 'manage_membergroups'),
- 'any' => array('profile_identity_any', 'profile_password_any', 'manage_membergroups'),
- ),
- ),
- 'tfasetup' => array(
+ 'permission' => [
+ 'own' => ['profile_identity_any', 'profile_identity_own', 'profile_password_any', 'profile_password_own', 'manage_membergroups'],
+ 'any' => ['profile_identity_any', 'profile_password_any', 'manage_membergroups'],
+ ],
+ ],
+ 'tfasetup' => [
'label' => 'account',
'function' => __NAMESPACE__ . '\\TFASetup::call',
'sub_template' => 'tfasetup',
@@ -293,12 +290,12 @@ class Main implements ActionInterface
'enabled' => true,
'hidden' => true,
'select' => 'account',
- 'permission' => array(
- 'own' => array('profile_password_own'),
- 'any' => array('profile_password_any'),
- ),
- ),
- 'tfadisable' => array(
+ 'permission' => [
+ 'own' => ['profile_password_own'],
+ 'any' => ['profile_password_any'],
+ ],
+ ],
+ 'tfadisable' => [
'label' => 'account',
'function' => __NAMESPACE__ . '\\TFADisable::call',
'sub_template' => 'tfadisable',
@@ -308,62 +305,62 @@ class Main implements ActionInterface
'enabled' => true,
'hidden' => true,
'select' => 'account',
- 'permission' => array(
- 'own' => array('profile_password_own'),
- 'any' => array('profile_password_any'),
- ),
- ),
- 'forumprofile' => array(
+ 'permission' => [
+ 'own' => ['profile_password_own'],
+ 'any' => ['profile_password_any'],
+ ],
+ ],
+ 'forumprofile' => [
'label' => 'forumprofile',
'function' => __NAMESPACE__ . '\\ForumProfile::call',
'sub_template' => 'edit_options',
'icon' => 'members',
'sc' => 'post',
'token' => 'profile-fp%u',
- 'permission' => array(
- 'own' => array('profile_forum_any', 'profile_forum_own'),
- 'any' => array('profile_forum_any'),
- ),
- ),
- 'theme' => array(
+ 'permission' => [
+ 'own' => ['profile_forum_any', 'profile_forum_own'],
+ 'any' => ['profile_forum_any'],
+ ],
+ ],
+ 'theme' => [
'label' => 'theme',
'function' => __NAMESPACE__ . '\\ThemeOptions::call',
'sub_template' => 'edit_options',
'icon' => 'features',
'sc' => 'post',
'token' => 'profile-th%u',
- 'permission' => array(
- 'own' => array('profile_extra_any', 'profile_extra_own'),
- 'any' => array('profile_extra_any'),
- ),
- ),
- 'notification' => array(
+ 'permission' => [
+ 'own' => ['profile_extra_any', 'profile_extra_own'],
+ 'any' => ['profile_extra_any'],
+ ],
+ ],
+ 'notification' => [
'label' => 'notification',
'function' => __NAMESPACE__ . '\\Notification::call',
'sub_template' => 'notification',
'icon' => 'alerts',
'sc' => 'post',
- //'token' => 'profile-nt%u', This is not checked here. We do it in the function itself - but if it was checked, this is what it'd be.
- 'subsections' => array(
- 'alerts' => array(
+ // 'token' => 'profile-nt%u', This is not checked here. We do it in the function itself - but if it was checked, this is what it'd be.
+ 'subsections' => [
+ 'alerts' => [
'label' => 'alert_prefs',
- 'permission' => array('is_not_guest', 'profile_extra_any'),
- ),
- 'topics' => array(
+ 'permission' => ['is_not_guest', 'profile_extra_any'],
+ ],
+ 'topics' => [
'label' => 'watched_topics',
- 'permission' => array('is_not_guest', 'profile_extra_any'),
- ),
- 'boards' => array(
+ 'permission' => ['is_not_guest', 'profile_extra_any'],
+ ],
+ 'boards' => [
'label' => 'watched_boards',
- 'permission' => array('is_not_guest', 'profile_extra_any'),
- ),
- ),
- 'permission' => array(
- 'own' => array('is_not_guest'),
- 'any' => array('profile_extra_any'), // If you change this, update it in the functions themselves; we delegate all saving checks there.
- ),
- ),
- 'ignoreboards' => array(
+ 'permission' => ['is_not_guest', 'profile_extra_any'],
+ ],
+ ],
+ 'permission' => [
+ 'own' => ['is_not_guest'],
+ 'any' => ['profile_extra_any'], // If you change this, update it in the functions themselves; we delegate all saving checks there.
+ ],
+ ],
+ 'ignoreboards' => [
'label' => 'ignoreboards',
'function' => __NAMESPACE__ . '\\IgnoreBoards::call',
'sub_template' => 'ignoreboards',
@@ -371,32 +368,32 @@ class Main implements ActionInterface
'enabled' => true,
'sc' => 'post',
'token' => 'profile-ib%u',
- 'permission' => array(
- 'own' => array('profile_extra_any', 'profile_extra_own'),
- 'any' => array('profile_extra_any'),
- ),
- ),
- 'lists' => array(
+ 'permission' => [
+ 'own' => ['profile_extra_any', 'profile_extra_own'],
+ 'any' => ['profile_extra_any'],
+ ],
+ ],
+ 'lists' => [
'label' => 'editBuddyIgnoreLists',
'function' => __NAMESPACE__ . '\\BuddyIgnoreLists::call',
'sub_template' => 'editBuddyIgnoreLists',
'icon' => 'frenemy',
'enabled' => true,
'sc' => 'post',
- 'subsections' => array(
- 'buddies' => array(
+ 'subsections' => [
+ 'buddies' => [
'label' => 'editBuddies',
- ),
- 'ignore' => array(
+ ],
+ 'ignore' => [
'label' => 'editIgnoreList',
- ),
- ),
- 'permission' => array(
- 'own' => array('profile_extra_any', 'profile_extra_own'),
- 'any' => array(),
- ),
- ),
- 'groupmembership' => array(
+ ],
+ ],
+ 'permission' => [
+ 'own' => ['profile_extra_any', 'profile_extra_own'],
+ 'any' => [],
+ ],
+ ],
+ 'groupmembership' => [
'label' => 'groupmembership',
'function' => __NAMESPACE__ . '\\GroupMembership::call',
'sub_template' => 'groupMembership',
@@ -405,104 +402,104 @@ class Main implements ActionInterface
'sc' => 'request',
'token' => 'profile-gm%u',
'token_type' => 'request',
- 'permission' => array(
- 'own' => array('is_not_guest'),
- 'any' => array('manage_membergroups'),
- ),
- ),
- ),
- ),
- 'profile_action' => array(
+ 'permission' => [
+ 'own' => ['is_not_guest'],
+ 'any' => ['manage_membergroups'],
+ ],
+ ],
+ ],
+ ],
+ 'profile_action' => [
'title' => 'profileAction',
- 'areas' => array(
- 'sendpm' => array(
+ 'areas' => [
+ 'sendpm' => [
'label' => 'profileSendIm',
'custom_url' => '{scripturl}?action=pm;sa=send',
'icon' => 'personal_message',
'enabled' => true,
- 'permission' => array(
- 'own' => array(),
- 'any' => array('pm_send'),
- ),
- ),
- 'report' => array(
+ 'permission' => [
+ 'own' => [],
+ 'any' => ['pm_send'],
+ ],
+ ],
+ 'report' => [
'label' => 'report_profile',
'custom_url' => '{scripturl}?action=reporttm;{session_var}={session_id}',
'icon' => 'warning',
'enabled' => true,
- 'permission' => array(
- 'own' => array(),
- 'any' => array('report_user'),
- ),
- ),
- 'issuewarning' => array(
+ 'permission' => [
+ 'own' => [],
+ 'any' => ['report_user'],
+ ],
+ ],
+ 'issuewarning' => [
'label' => 'profile_issue_warning',
'function' => __NAMESPACE__ . '\\IssueWarning::call',
'sub_template' => 'issueWarning',
'icon' => 'warning',
'token' => 'profile-iw%u',
'enabled' => true,
- 'permission' => array(
- 'own' => array(),
- 'any' => array('issue_warning'),
- ),
- ),
- 'banuser' => array(
+ 'permission' => [
+ 'own' => [],
+ 'any' => ['issue_warning'],
+ ],
+ ],
+ 'banuser' => [
'label' => 'profileBanUser',
'custom_url' => '{scripturl}?action=admin;area=ban;sa=add',
'icon' => 'ban',
'enabled' => true,
- 'permission' => array(
- 'own' => array(),
- 'any' => array('manage_bans'),
- ),
- ),
- 'subscriptions' => array(
+ 'permission' => [
+ 'own' => [],
+ 'any' => ['manage_bans'],
+ ],
+ ],
+ 'subscriptions' => [
'label' => 'subscriptions',
'function' => __NAMESPACE__ . '\\PaidSubs::call',
'icon' => 'paid',
'enabled' => true,
- 'permission' => array(
- 'own' => array('is_not_guest'),
- 'any' => array('moderate_forum'),
- ),
- ),
- 'getprofiledata' => array(
+ 'permission' => [
+ 'own' => ['is_not_guest'],
+ 'any' => ['moderate_forum'],
+ ],
+ ],
+ 'getprofiledata' => [
'label' => 'export_profile_data',
'function' => __NAMESPACE__ . '\\Export::call',
'sub_template' => 'export_profile_data',
'icon' => 'packages',
// 'token' => 'profile-ex%u', // This is not checked here. We do it in the function itself - but if it was checked, this is what it'd be.
- 'permission' => array(
- 'own' => array('profile_view_own'),
- 'any' => array('moderate_forum'),
- ),
- ),
- 'download' => array(
+ 'permission' => [
+ 'own' => ['profile_view_own'],
+ 'any' => ['moderate_forum'],
+ ],
+ ],
+ 'download' => [
'label' => 'export_profile_data',
'function' => __NAMESPACE__ . '\\ExportDownload::call',
'sub_template' => 'download_export_file',
'icon' => 'packages',
'hidden' => true,
'select' => 'getprofiledata',
- 'permission' => array(
- 'own' => array('profile_view_own'),
- 'any' => array('moderate_forum'),
- ),
- ),
- 'dlattach' => array(
+ 'permission' => [
+ 'own' => ['profile_view_own'],
+ 'any' => ['moderate_forum'],
+ ],
+ ],
+ 'dlattach' => [
'label' => 'export_profile_data',
'function' => __NAMESPACE__ . '\\ExportAttachment::call',
'sub_template' => 'export_attachment',
'icon' => 'packages',
'hidden' => true,
'select' => 'getprofiledata',
- 'permission' => array(
- 'own' => array('profile_view_own'),
- 'any' => array(),
- ),
- ),
- 'deleteaccount' => array(
+ 'permission' => [
+ 'own' => ['profile_view_own'],
+ 'any' => [],
+ ],
+ ],
+ 'deleteaccount' => [
'label' => 'deleteAccount',
'function' => __NAMESPACE__ . '\\Delete::call',
'sub_template' => 'deleteAccount',
@@ -510,37 +507,37 @@ class Main implements ActionInterface
'sc' => 'post',
'token' => 'profile-da%u',
'password' => true,
- 'permission' => array(
- 'own' => array('profile_remove_any', 'profile_remove_own'),
- 'any' => array('profile_remove_any'),
- ),
- ),
- 'activateaccount' => array(
+ 'permission' => [
+ 'own' => ['profile_remove_any', 'profile_remove_own'],
+ 'any' => ['profile_remove_any'],
+ ],
+ ],
+ 'activateaccount' => [
'file' => 'Profile-Actions.php',
'function' => 'activateAccount',
'icon' => 'regcenter',
'sc' => 'get',
'token' => 'profile-aa%u',
'token_type' => 'get',
- 'permission' => array(
- 'own' => array(),
- 'any' => array('moderate_forum'),
- ),
- ),
+ 'permission' => [
+ 'own' => [],
+ 'any' => ['moderate_forum'],
+ ],
+ ],
// A logout link just for the popup menu.
- 'logout' => array(
+ 'logout' => [
'label' => 'logout',
'custom_url' => '{scripturl}?action=logout;{session_var}={session_id}',
'icon' => 'logout',
'enabled' => true,
- 'permission' => array(
- 'own' => array('is_not_guest'),
- 'any' => array(),
- ),
- ),
- ),
- ),
- );
+ 'permission' => [
+ 'own' => ['is_not_guest'],
+ 'any' => [],
+ ],
+ ],
+ ],
+ ],
+ ];
/**
* @var bool
@@ -572,37 +569,37 @@ class Main implements ActionInterface
public function execute(): void
{
// Is there an updated message to show?
- if (isset($_GET['updated']))
+ if (isset($_GET['updated'])) {
Utils::$context['profile_updated'] = Lang::$txt['profile_updated_own'];
+ }
$menu = $this->createMenu();
$this->securityChecks();
// File to include?
- if (!empty($menu->include_data['file']))
- require_once(Config::$sourcedir . '/' . $menu->include_data['file']);
+ if (!empty($menu->include_data['file'])) {
+ require_once Config::$sourcedir . '/' . $menu->include_data['file'];
+ }
// Build the link tree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=profile' . (Profile::$member->id != User::$me->id ? ';u=' . Profile::$member->id : ''),
'name' => sprintf(Lang::$txt['profile_of_username'], Profile::$member->formatted['name']),
- );
+ ];
- if (!empty($menu->include_data['label']))
- {
- Utils::$context['linktree'][] = array(
+ if (!empty($menu->include_data['label'])) {
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=profile' . (Profile::$member->id != User::$me->id ? ';u=' . Profile::$member->id : '') . ';area=' . $menu->current_area,
'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=profile' . (Profile::$member->id != User::$me->id ? ';u=' . Profile::$member->id : '') . ';area=' . $menu->current_area . ';sa=' . $menu->current_subsection,
'name' => $menu->include_data['subsections'][$menu->current_subsection]['label'],
- );
+ ];
}
// Set the template for this area and add the profile layer.
@@ -610,102 +607,91 @@ public function execute(): void
Utils::$context['template_layers'][] = 'profile';
- Theme::loadJavaScriptFile('profile.js', array('defer' => false, 'minimize' => true), 'smf_profile');
+ Theme::loadJavaScriptFile('profile.js', ['defer' => false, 'minimize' => true], 'smf_profile');
// Right - are we saving - if so let's save the old data first.
- if (Utils::$context['completed_save'])
- {
+ if (Utils::$context['completed_save']) {
// Clean up the POST variables.
$_POST = Utils::htmlTrimRecursive($_POST);
$_POST = Utils::htmlspecialcharsRecursive($_POST);
Profile::$member->post_sanitized = true;
- if ($this->check_password)
- {
+ if ($this->check_password) {
// Check to ensure we're forcing SSL for authentication
- if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn())
- {
+ if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn()) {
ErrorHandler::fatalLang('login_ssl_required', false);
}
- $password = isset($_POST['oldpasswrd']) ? $_POST['oldpasswrd'] : '';
+ $password = $_POST['oldpasswrd'] ?? '';
// You didn't even enter a password!
- if (trim($password) == '')
+ if (trim($password) == '') {
Profile::$member->save_errors[] = 'no_password';
+ }
// Since the password got modified due to all the $_POST cleaning, lets undo it so we can get the correct password
$password = Utils::htmlspecialcharsDecode($password);
// Does the integration want to check passwords?
- $good_password = in_array(true, IntegrationHook::call('integrate_verify_password', array(Profile::$member->username, $password, false)), true);
+ $good_password = in_array(true, IntegrationHook::call('integrate_verify_password', [Profile::$member->username, $password, false]), true);
// Bad password!!!
- if (!$good_password && !Security::hashVerifyPassword(Profile::$member->username, $password, Profile::$member->passwd))
- {
+ if (!$good_password && !Security::hashVerifyPassword(Profile::$member->username, $password, Profile::$member->passwd)) {
Profile::$member->save_errors[] = 'bad_password';
}
// Warn other elements not to jump the gun and do custom changes!
- if (in_array('bad_password', Profile::$member->save_errors))
+ if (in_array('bad_password', Profile::$member->save_errors)) {
Utils::$context['password_auth_failed'] = true;
+ }
}
// Change the IP address in the database.
- if (User::$me->is_owner && ($_REQUEST['area'] ?? null) != 'tfasetup')
+ if (User::$me->is_owner && ($_REQUEST['area'] ?? null) != 'tfasetup') {
Profile::$member->new_data['member_ip'] = User::$me->ip;
+ }
// Now call the sub-action function...
- if ($menu->current_area == 'activateaccount')
- {
- if (empty(Profile::$member->save_errors))
- {
+ if ($menu->current_area == 'activateaccount') {
+ if (empty(Profile::$member->save_errors)) {
Activate::call();
Utils::redirectexit('action=profile;u=' . Profile::$member->id . ';area=summary');
}
- }
- elseif ($menu->current_area == 'deleteaccount')
- {
- if (empty(Profile::$member->save_errors))
- {
+ } elseif ($menu->current_area == 'deleteaccount') {
+ if (empty(Profile::$member->save_errors)) {
Delete::call();
Utils::redirectexit();
}
- }
- elseif (empty(Profile::$member->save_errors))
- {
- if (($_REQUEST['area'] ?? null) == 'tfadisable')
- {
+ } elseif (empty(Profile::$member->save_errors)) {
+ if (($_REQUEST['area'] ?? null) == 'tfadisable') {
// Already checked the password, token, permissions, and session.
- Profile::$member->new_data += array(
+ Profile::$member->new_data += [
'tfa_secret' => '',
'tfa_backup' => '',
- );
+ ];
}
- if ($menu->current_area == 'groupmembership')
- {
+ if ($menu->current_area == 'groupmembership') {
$gm_action = GroupMembership::load();
$gm_action->execute();
$msg = $gm_action->change_type;
}
- $force_redirect = !in_array($menu->current_area, array('account', 'forumprofile', 'theme'));
+ $force_redirect = !in_array($menu->current_area, ['account', 'forumprofile', 'theme']);
Profile::$member->save();
}
}
// Have some errors for some reason?
- if (!empty(Profile::$member->save_errors))
- {
+ if (!empty(Profile::$member->save_errors)) {
// Set all the errors so the template knows what went wrong.
- foreach (Profile::$member->save_errors as $error_type)
+ foreach (Profile::$member->save_errors as $error_type) {
Utils::$context['modify_error'][$error_type] = true;
+ }
}
// If it's you or it's forced then we should redirect upon save.
- elseif ((!empty(Profile::$member->new_data) && User::$me->is_owner && !Utils::$context['do_preview']) || !empty($force_redirect))
- {
+ elseif ((!empty(Profile::$member->new_data) && User::$me->is_owner && !Utils::$context['do_preview']) || !empty($force_redirect)) {
Utils::redirectexit('action=profile' . (User::$me->is_owner ? '' : ';u=' . Profile::$member->id) . ';area=' . $menu->current_area . (!empty($msg) ? ';msg=' . $msg : ';updated'));
}
@@ -713,12 +699,12 @@ public function execute(): void
$call = Utils::getCallable($menu->include_data['function']);
// Is it valid?
- if (!empty($call))
+ if (!empty($call)) {
call_user_func($call, Profile::$member->id);
+ }
// Set the page title if it's not already set...
- if (!isset(Utils::$context['page_title']))
- {
+ if (!isset(Utils::$context['page_title'])) {
Utils::$context['page_title'] = Lang::$txt['profile'] . (isset(Lang::$txt[$menu->current_area]) ? ' - ' . Lang::$txt[$menu->current_area] : '');
}
}
@@ -734,8 +720,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;
}
@@ -751,7 +738,7 @@ public static function call(): void
/**
* Backward compatibility wrapper.
*/
- public static function modifyProfile($post_errors = array()): void
+ public static function modifyProfile($post_errors = []): void
{
self::load();
Profile::$member->save_errors = $post_errors;
@@ -768,8 +755,9 @@ public static function modifyProfile($post_errors = array()): void
protected function __construct()
{
// Don't reload this as we may have processed error strings.
- if (empty(Profile::$member->save_errors))
+ if (empty(Profile::$member->save_errors)) {
Lang::load('Profile+Drafts');
+ }
Theme::loadTemplate('Profile');
@@ -778,20 +766,22 @@ protected function __construct()
// Group management isn't actually a permission. But we need it to be for this, so we need a phantom permission.
// And we care about what the current user can do, not what the user whose profile it is.
- if (User::$me->mod_cache['gq'] != '0=1')
+ if (User::$me->mod_cache['gq'] != '0=1') {
User::$me->permissions[] = 'approve_group_requests';
+ }
// If paid subscriptions are enabled, make sure we actually have at least one subscription available...
Utils::$context['subs_available'] = false;
- if (!empty(Config::$modSettings['paid_enabled']))
- {
- $get_active_subs = Db::$db->query('', '
- SELECT COUNT(*)
+ if (!empty(Config::$modSettings['paid_enabled'])) {
+ $get_active_subs = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}subscriptions
- WHERE active = {int:active}', array(
+ WHERE active = {int:active}',
+ [
'active' => 1,
- )
+ ],
);
list($num_subs) = Db::$db->fetch_row($get_active_subs);
Db::$db->free_result($get_active_subs);
@@ -810,18 +800,18 @@ protected function setProfileAreas(): void
// Finalize various string values.
array_walk_recursive(
$this->profile_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,
'{session_var}' => Utils::$context['session_var'],
'{session_id}' => Utils::$context['session_id'],
- ));
- }
+ ]);
+ },
);
$this->profile_areas['info']['areas']['showposts']['subsections']['unwatchedtopics']['enabled'] = User::$me->is_owner;
@@ -836,7 +826,6 @@ function(&$value, $key)
$this->profile_areas['info']['areas']['viewwarning']['enabled'] = Config::$modSettings['warning_settings'][0] == 1 && Profile::$member->warning;
-
$this->profile_areas['edit_profile']['areas']['account']['enabled'] = User::$me->is_admin || (Profile::$member->group_id != 1 && !in_array(1, Profile::$member->additional_groups));
$this->profile_areas['edit_profile']['areas']['tfasetup']['enabled'] = !empty(Config::$modSettings['tfa_mode']);
@@ -849,7 +838,6 @@ function(&$value, $key)
$this->profile_areas['edit_profile']['areas']['groupmembership']['enabled'] = !empty(Config::$modSettings['show_group_membership']) && User::$me->is_owner;
-
$this->profile_areas['profile_action']['areas']['sendpm']['enabled'] = User::$me->allowedTo('profile_view');
$this->profile_areas['profile_action']['areas']['report']['enabled'] = User::$me->allowedTo('profile_view');
@@ -863,30 +851,27 @@ function(&$value, $key)
$this->profile_areas['profile_action']['areas']['logout']['enabled'] = !empty($_REQUEST['area']) && $_REQUEST['area'] === 'popup';
// Give mods access to the menu.
- IntegrationHook::call('integrate_profile_areas', array(&$this->profile_areas));
+ IntegrationHook::call('integrate_profile_areas', [&$this->profile_areas]);
// Do some cleaning ready for the menu function.
- Utils::$context['password_areas'] = array();
+ Utils::$context['password_areas'] = [];
- foreach ($this->profile_areas as $section_id => $section)
- {
+ foreach ($this->profile_areas as $section_id => $section) {
// Do a bit of spring cleaning so to speak.
- foreach ($section['areas'] as $area_id => $area)
- {
+ foreach ($section['areas'] as $area_id => $area) {
// If it said no permissions that meant it wasn't valid!
- if (empty($area['permission'][User::$me->is_owner ? 'own' : 'any']))
- {
+ if (empty($area['permission'][User::$me->is_owner ? 'own' : 'any'])) {
$this->profile_areas[$section_id]['areas'][$area_id]['enabled'] = false;
}
// Otherwise pick the right set.
- else
- {
+ else {
$this->profile_areas[$section_id]['areas'][$area_id]['permission'] = $area['permission'][User::$me->is_owner ? 'own' : 'any'];
}
// Password required in most cases
- if (!empty($area['password']))
+ if (!empty($area['password'])) {
Utils::$context['password_areas'][] = $area_id;
+ }
}
}
}
@@ -902,21 +887,22 @@ function(&$value, $key)
protected function createMenu(): object
{
// Set a few options for the menu.
- $menuOptions = array(
+ $menuOptions = [
'disable_hook_call' => true,
'disable_url_session_check' => true,
- 'current_area' => isset($_REQUEST['area']) ? $_REQUEST['area'] : '',
- 'extra_url_parameters' => array(
+ 'current_area' => $_REQUEST['area'] ?? '',
+ 'extra_url_parameters' => [
'u' => Profile::$member->id,
- ),
- );
+ ],
+ ];
// Actually create the menu!
$menu = new Menu($this->profile_areas, $menuOptions);
// No menu means no access.
- if (empty($menu->include_data) && (!User::$me->is_guest || User::$me->validateSession()))
+ if (empty($menu->include_data) && (!User::$me->is_guest || User::$me->validateSession())) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Backward compatibility.
Utils::$context['profile_menu_id'] = $menu->id;
@@ -935,49 +921,41 @@ protected function securityChecks(): void
Utils::$context['completed_save'] = false;
Utils::$context['do_preview'] = isset($_REQUEST['preview_signature']);
- $security_checks = array();
+ $security_checks = [];
$found_area = false;
- foreach ($this->profile_areas as $section_id => $section)
- {
+ foreach ($this->profile_areas as $section_id => $section) {
// Do a bit of spring cleaning so to speak.
- foreach ($section['areas'] as $area_id => $area)
- {
+ foreach ($section['areas'] as $area_id => $area) {
// Is this our area?
- if (Menu::$loaded['profile']->current_area == $area_id)
- {
+ if (Menu::$loaded['profile']->current_area == $area_id) {
// This can't happen - but is a security check.
- if ((isset($section['enabled']) && $section['enabled'] == false) || (isset($area['enabled']) && $area['enabled'] == false))
- {
+ if ((isset($section['enabled']) && $section['enabled'] == false) || (isset($area['enabled']) && $area['enabled'] == false)) {
ErrorHandler::fatalLang('no_access', false);
}
// Are we saving data in a valid area?
- if (isset($area['sc']) && (isset($_REQUEST['save']) || Utils::$context['do_preview']))
- {
+ if (isset($area['sc']) && (isset($_REQUEST['save']) || Utils::$context['do_preview'])) {
$security_checks['session'] = $area['sc'];
Utils::$context['completed_save'] = true;
}
// Do we need to perform a token check?
- if (!empty($area['token']))
- {
+ if (!empty($area['token'])) {
$security_checks[isset($_REQUEST['save']) ? 'validateToken' : 'needsToken'] = $area['token'];
$token_name = $area['token'] !== true ? str_replace('%u', Profile::$member->id, $area['token']) : 'profile-u' . Profile::$member->id;
- $token_type = isset($area['token_type']) && in_array($area['token_type'], array('request', 'post', 'get')) ? $area['token_type'] : 'post';
+ $token_type = isset($area['token_type']) && in_array($area['token_type'], ['request', 'post', 'get']) ? $area['token_type'] : 'post';
}
// Does this require session validating?
- if (!empty($area['validate']) || (isset($_REQUEST['save']) && !User::$me->is_owner && ($area_id != 'issuewarning' || empty(Config::$modSettings['securityDisable_moderate']))))
- {
+ if (!empty($area['validate']) || (isset($_REQUEST['save']) && !User::$me->is_owner && ($area_id != 'issuewarning' || empty(Config::$modSettings['securityDisable_moderate'])))) {
$security_checks['validate'] = true;
}
// Permissions for good measure.
- if (!empty(Menu::$loaded['profile']->include_data['permission']))
- {
+ if (!empty(Menu::$loaded['profile']->include_data['permission'])) {
$security_checks['permission'] = Menu::$loaded['profile']->include_data['permission'];
}
@@ -988,25 +966,29 @@ protected function securityChecks(): void
}
// Oh dear, some serious security lapse is going on here... we'll put a stop to that!
- if (!$found_area)
+ if (!$found_area) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Now the context is setup have we got any security checks to carry out additional to that above?
- if (isset($security_checks['session']))
+ if (isset($security_checks['session'])) {
User::$me->checkSession($security_checks['session']);
+ }
- if (isset($security_checks['validate']))
+ if (isset($security_checks['validate'])) {
User::$me->validateSession();
+ }
- if (isset($security_checks['validateToken']))
+ if (isset($security_checks['validateToken'])) {
SecurityToken::validate($token_name, $token_type);
+ }
- if (isset($security_checks['permission']))
+ if (isset($security_checks['permission'])) {
User::$me->isAllowedTo($security_checks['permission']);
+ }
// Create a token if needed.
- if (isset($security_checks['needsToken']) || isset($security_checks['validateToken']))
- {
+ if (isset($security_checks['needsToken']) || isset($security_checks['validateToken'])) {
SecurityToken::create($token_name, $token_type);
Utils::$context['token_check'] = $token_name;
}
@@ -1019,7 +1001,8 @@ protected function securityChecks(): void
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Main::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Main::exportStatic')) {
Main::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/Notification.php b/Sources/Actions/Profile/Notification.php
index db9226d676..c3f69364ca 100644
--- a/Sources/Actions/Profile/Notification.php
+++ b/Sources/Actions/Profile/Notification.php
@@ -13,11 +13,12 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\Actions\Notify;
use SMF\Alert;
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\ItemList;
@@ -29,8 +30,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Actions\Notify;
-use SMF\Db\DatabaseApi as Db;
/**
* Handles preferences related to notifications.
@@ -44,12 +43,19 @@ class Notification implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'notification',
- ),
- );
+ 'list_getTopicNotificationCount' => 'list_getTopicNotificationCount',
+ 'list_getTopicNotifications' => 'list_getTopicNotifications',
+ 'list_getBoardNotifications' => 'list_getBoardNotifications',
+ 'alert_configuration' => 'alert_configuration',
+ 'alert_markread' => 'alert_markread',
+ 'alert_notifications_topics' => 'alert_notifications_topics',
+ 'alert_notifications_boards' => 'alert_notifications_boards',
+ 'makeNotificationChanges' => 'makeNotificationChanges',
+ ],
+ ];
/*******************
* Public properties
@@ -67,220 +73,220 @@ class Notification implements ActionInterface
* @var array
*
* Defines all the types of alerts and their default values.
- *
+ *
* The 'alert' and 'email' keys are required for each alert type.
* The 'help' and 'permission' keys are optional.
- *
+ *
* Valid values for 'alert' and 'email' keys are: 'always', 'yes', 'never'.
* If using 'always' or 'never' you should add a help string.
*/
- public array $alert_types = array(
- 'board' => array(
- 'topic_notify' => array(
- 'alert' => 'yes',
+ public array $alert_types = [
+ 'board' => [
+ 'topic_notify' => [
+ 'alert' => 'yes',
'email' => 'yes',
- ),
- 'board_notify' => array(
- 'alert' => 'yes',
+ ],
+ 'board_notify' => [
+ 'alert' => 'yes',
'email' => 'yes',
- ),
- ),
- 'msg' => array(
- 'msg_mention' => array(
- 'alert' => 'yes',
+ ],
+ ],
+ 'msg' => [
+ 'msg_mention' => [
+ 'alert' => 'yes',
'email' => 'yes',
- ),
- 'msg_quote' => array(
- 'alert' => 'yes',
+ ],
+ 'msg_quote' => [
+ 'alert' => 'yes',
'email' => 'yes',
- ),
- 'msg_like' => array(
- 'alert' => 'yes',
+ ],
+ 'msg_like' => [
+ 'alert' => 'yes',
'email' => 'never',
- ),
- 'unapproved_reply' => array(
- 'alert' => 'yes',
+ ],
+ 'unapproved_reply' => [
+ 'alert' => 'yes',
'email' => 'yes',
- ),
- ),
- 'pm' => array(
- 'pm_new' => array(
- 'alert' => 'never',
- 'email' => 'yes',
- 'help' => 'alert_pm_new',
- 'permission' => array(
- 'name' => 'pm_read',
+ ],
+ ],
+ 'pm' => [
+ 'pm_new' => [
+ 'alert' => 'never',
+ 'email' => 'yes',
+ 'help' => 'alert_pm_new',
+ 'permission' => [
+ 'name' => 'pm_read',
'is_board' => false,
- ),
- ),
- 'pm_reply' => array(
+ ],
+ ],
+ 'pm_reply' => [
'alert' => 'never',
'email' => 'yes',
'help' => 'alert_pm_new',
- 'permission' => array(
+ 'permission' => [
'name' => 'pm_send',
'is_board' => false,
- ),
- ),
- ),
- 'groupr' => array(
- 'groupr_approved' => array(
- 'alert' => 'yes',
+ ],
+ ],
+ ],
+ 'groupr' => [
+ 'groupr_approved' => [
+ 'alert' => 'yes',
'email' => 'yes',
- ),
- 'groupr_rejected' => array(
- 'alert' => 'yes',
+ ],
+ 'groupr_rejected' => [
+ 'alert' => 'yes',
'email' => 'yes',
- ),
- ),
- 'moderation' => array(
- 'unapproved_attachment' => array(
+ ],
+ ],
+ 'moderation' => [
+ 'unapproved_attachment' => [
'alert' => 'yes',
'email' => 'yes',
- 'permission' => array(
+ 'permission' => [
'name' => 'approve_posts',
'is_board' => true,
- ),
- ),
- 'unapproved_post' => array(
+ ],
+ ],
+ 'unapproved_post' => [
'alert' => 'yes',
'email' => 'yes',
- 'permission' => array(
+ 'permission' => [
'name' => 'approve_posts',
'is_board' => true,
- ),
- ),
- 'msg_report' => array(
+ ],
+ ],
+ 'msg_report' => [
'alert' => 'yes',
'email' => 'yes',
- 'permission' => array(
+ 'permission' => [
'name' => 'moderate_board',
'is_board' => true,
- ),
- ),
- 'msg_report_reply' => array(
+ ],
+ ],
+ 'msg_report_reply' => [
'alert' => 'yes',
'email' => 'yes',
- 'permission' => array(
+ 'permission' => [
'name' => 'moderate_board',
'is_board' => true,
- ),
- ),
- 'member_report' => array(
+ ],
+ ],
+ 'member_report' => [
'alert' => 'yes',
'email' => 'yes',
- 'permission' => array(
+ 'permission' => [
'name' => 'moderate_forum',
'is_board' => false,
- ),
- ),
- 'member_report_reply' => array(
+ ],
+ ],
+ 'member_report_reply' => [
'alert' => 'yes',
'email' => 'yes',
- 'permission' => array(
+ 'permission' => [
'name' => 'moderate_forum',
'is_board' => false,
- ),
- ),
- ),
- 'members' => array(
- 'member_register' => array(
+ ],
+ ],
+ ],
+ 'members' => [
+ 'member_register' => [
'alert' => 'yes',
'email' => 'yes',
- 'permission' => array(
+ 'permission' => [
'name' => 'moderate_forum',
'is_board' => false,
- ),
- ),
- 'request_group' => array(
+ ],
+ ],
+ 'request_group' => [
'alert' => 'yes',
'email' => 'yes',
- ),
- 'warn_any' => array(
+ ],
+ 'warn_any' => [
'alert' => 'yes',
'email' => 'yes',
- 'permission' => array(
+ 'permission' => [
'name' => 'issue_warning',
'is_board' => false,
- ),
- ),
- 'buddy_request' => array(
+ ],
+ ],
+ 'buddy_request' => [
'alert' => 'yes',
'email' => 'never',
- ),
- 'birthday' => array(
+ ],
+ 'birthday' => [
'alert' => 'yes',
'email' => 'yes',
- ),
- ),
- 'calendar' => array(
- 'event_new' => array(
+ ],
+ ],
+ 'calendar' => [
+ 'event_new' => [
'alert' => 'yes',
'email' => 'yes',
'help' => 'alert_event_new',
- ),
- ),
- 'paidsubs' => array(
- 'paidsubs_expiring' => array(
- 'alert' => 'yes',
+ ],
+ ],
+ 'paidsubs' => [
+ 'paidsubs_expiring' => [
+ 'alert' => 'yes',
'email' => 'yes',
- ),
- ),
- );
+ ],
+ ],
+ ];
/**
* @var array
*
* The group level options.
*/
- public array $group_options = array(
- 'board' => array(
- 'msg_auto_notify' => array(
- 'check',
- 'msg_auto_notify',
+ public array $group_options = [
+ 'board' => [
+ 'msg_auto_notify' => [
+ 'check',
+ 'msg_auto_notify',
'label' => 'after',
- ),
- 'msg_receive_body' => array(
- 'check',
- 'msg_receive_body',
+ ],
+ 'msg_receive_body' => [
+ 'check',
+ 'msg_receive_body',
'label' => 'after',
- ),
- 'msg_notify_pref' => array(
- 'select',
- 'msg_notify_pref',
- 'label' => 'before',
- 'opts' => array(
+ ],
+ 'msg_notify_pref' => [
+ 'select',
+ 'msg_notify_pref',
+ 'label' => 'before',
+ 'opts' => [
0 => 'alert_opt_msg_notify_pref_never',
1 => 'alert_opt_msg_notify_pref_instant',
2 => 'alert_opt_msg_notify_pref_first',
3 => 'alert_opt_msg_notify_pref_daily',
4 => 'alert_opt_msg_notify_pref_weekly',
- ),
- ),
- 'msg_notify_type' => array(
- 'select',
- 'msg_notify_type',
- 'label' => 'before',
- 'opts' => array(
+ ],
+ ],
+ 'msg_notify_type' => [
+ 'select',
+ 'msg_notify_type',
+ 'label' => 'before',
+ 'opts' => [
1 => 'notify_send_type_everything',
2 => 'notify_send_type_everything_own',
3 => 'notify_send_type_only_replies',
4 => 'notify_send_type_nothing',
- ),
- ),
- ),
- 'pm' => array(
- 'pm_notify' => array(
- 'select',
- 'pm_notify',
- 'label' => 'before',
- 'opts' => array(
+ ],
+ ],
+ ],
+ 'pm' => [
+ 'pm_notify' => [
+ 'select',
+ 'pm_notify',
+ 'label' => 'before',
+ 'opts' => [
1 => 'email_notify_all',
2 => 'email_notify_buddies',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
/**************************
* Public static properties
@@ -291,24 +297,24 @@ class Notification implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'alerts' => 'configuration',
'markread' => 'markRead',
'topics' => 'topics',
'boards' => 'boards',
- );
+ ];
/**
* @var array
*
* Available sub-actions.
*/
- public static array $subtemplates = array(
+ public static array $subtemplates = [
'alerts' => 'alert_configuration',
'markread' => 'alert_markread',
'topics' => 'alert_notifications_topics',
'boards' => 'alert_notifications_boards',
- );
+ ];
/****************************
* Internal static properties
@@ -332,23 +338,23 @@ class Notification implements ActionInterface
public function execute(): void
{
// Going to want this for consistency.
- Theme::loadCSSFile('admin.css', array(), 'smf_admin');
+ Theme::loadCSSFile('admin.css', [], 'smf_admin');
Utils::$context['sub_template'] = self::$subtemplates[$this->subaction];
- if (isset(Menu::$loaded['profile']))
- {
- Menu::$loaded['profile']->tab_data = array(
+ if (isset(Menu::$loaded['profile'])) {
+ Menu::$loaded['profile']->tab_data = [
'title' => Lang::$txt['notification'],
'help' => '',
'description' => Lang::$txt['notification_info'],
- );
+ ];
}
- $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);
+ }
}
/**
@@ -356,100 +362,101 @@ public function execute(): void
*
* @param bool $defaultSettings If true, we are loading default options.
*/
- function configuration($defaultSettings = false)
+ public function configuration($defaultSettings = false)
{
- if (!isset(Utils::$context['token_check']))
+ if (!isset(Utils::$context['token_check'])) {
Utils::$context['token_check'] = 'profile-nt' . Profile::$member->id;
+ }
User::$me->kickIfGuest();
- if (!User::$me->is_owner)
+ if (!User::$me->is_owner) {
User::$me->isAllowedTo('profile_extra_any');
+ }
// Set the post action if we're coming from the profile...
- if (!isset(Utils::$context['action']))
- {
+ if (!isset(Utils::$context['action'])) {
Utils::$context['action'] = 'action=profile;area=notification;sa=alerts;u=' . Profile::$member->id;
}
// What options are set?
Profile::$member->loadThemeOptions($defaultSettings);
- Theme::loadJavaScriptFile('alertSettings.js', array('minimize' => true), 'smf_alertSettings');
+ Theme::loadJavaScriptFile('alertSettings.js', ['minimize' => true], 'smf_alertSettings');
// Now load all the values for this user.
$prefs = Notify::getNotifyPrefs(Profile::$member->id, '', Profile::$member->id != 0);
- Utils::$context['alert_prefs'] = !empty($prefs[Profile::$member->id]) ? $prefs[Profile::$member->id] : array();
+ Utils::$context['alert_prefs'] = !empty($prefs[Profile::$member->id]) ? $prefs[Profile::$member->id] : [];
- Utils::$context['member'] += array(
- 'alert_timeout' => isset(Utils::$context['alert_prefs']['alert_timeout']) ? Utils::$context['alert_prefs']['alert_timeout'] : 10,
- 'notify_announcements' => isset(Utils::$context['alert_prefs']['announcements']) ? Utils::$context['alert_prefs']['announcements'] : 0,
- );
+ Utils::$context['member'] += [
+ 'alert_timeout' => Utils::$context['alert_prefs']['alert_timeout'] ?? 10,
+ 'notify_announcements' => Utils::$context['alert_prefs']['announcements'] ?? 0,
+ ];
// There are certain things that are disabled at the group level.
- if (empty(Config::$modSettings['cal_enabled']))
+ if (empty(Config::$modSettings['cal_enabled'])) {
unset($this->alert_types['calendar']);
+ }
// Disable paid subscriptions at group level if they're disabled.
- if (empty(Config::$modSettings['paid_enabled']))
+ if (empty(Config::$modSettings['paid_enabled'])) {
unset($this->alert_types['paidsubs']);
+ }
// Disable membergroup requests at group level if they're disabled.
- if (empty(Config::$modSettings['show_group_membership']))
+ if (empty(Config::$modSettings['show_group_membership'])) {
unset($this->alert_types['groupr'], $this->alert_types['members']['request_group']);
+ }
// Disable mentions if they're disabled.
- if (empty(Config::$modSettings['enable_mentions']))
+ if (empty(Config::$modSettings['enable_mentions'])) {
unset($this->alert_types['msg']['msg_mention']);
+ }
// Disable likes if they're disabled.
- if (empty(Config::$modSettings['enable_likes']))
+ if (empty(Config::$modSettings['enable_likes'])) {
unset($this->alert_types['msg']['msg_like']);
+ }
// Disable buddy requests if they're disabled.
- if (empty(Config::$modSettings['enable_buddylist']))
+ if (empty(Config::$modSettings['enable_buddylist'])) {
unset($this->alert_types['members']['buddy_request']);
+ }
// Disable sending the body if it's disabled.
- if (!empty(Config::$modSettings['disallow_sendBody']))
+ if (!empty(Config::$modSettings['disallow_sendBody'])) {
$this->group_options['board']['msg_receive_body'][0] = 'hide';
+ }
// Finalize the string values of the options.
- foreach ($this->group_options as &$options)
- {
- foreach ($options as &$option)
- {
- if (!isset($option['opts']))
+ foreach ($this->group_options as &$options) {
+ foreach ($options as &$option) {
+ if (!isset($option['opts'])) {
continue;
+ }
- foreach ($option['opts'] as &$value)
+ foreach ($option['opts'] as &$value) {
$value = Lang::$txt[$value] ?? $value;
+ }
}
}
// Now, now, we could pass this through global but we should really get into the habit of
// passing content to hooks, not expecting hooks to splatter everything everywhere.
- IntegrationHook::call('integrate_alert_types', array(&$this->alert_types, &$this->group_options));
+ IntegrationHook::call('integrate_alert_types', [&$this->alert_types, &$this->group_options]);
// Now we have to do some permissions testing - but only if we're not loading this from the admin center
- if (!empty(Profile::$member->id))
- {
- $group_permissions = array('manage_membergroups');
- $board_permissions = array();
-
- foreach ($this->alert_types as $group => $items)
- {
- foreach ($items as $alert_key => $alert_value)
- {
- if (isset($alert_value['permission']))
- {
- if (empty($alert_value['permission']['is_board']))
- {
+ if (!empty(Profile::$member->id)) {
+ $group_permissions = ['manage_membergroups'];
+ $board_permissions = [];
+
+ foreach ($this->alert_types as $group => $items) {
+ foreach ($items as $alert_key => $alert_value) {
+ if (isset($alert_value['permission'])) {
+ if (empty($alert_value['permission']['is_board'])) {
$group_permissions[] = $alert_value['permission']['name'];
- }
- else
- {
+ } else {
$board_permissions[] = $alert_value['permission']['name'];
}
}
@@ -458,38 +465,38 @@ function configuration($defaultSettings = false)
$member_groups = User::getGroupsWithPermissions($group_permissions, $board_permissions);
- if (empty($member_groups['manage_membergroups']['allowed']))
- {
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ if (empty($member_groups['manage_membergroups']['allowed'])) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}group_moderators
WHERE id_member = {int:memID}',
- array(
+ [
'memID' => Profile::$member->id,
- )
+ ],
);
list($is_group_moderator) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- if (empty($is_group_moderator))
+ if (empty($is_group_moderator)) {
unset($this->alert_types['members']['request_group']);
+ }
}
- foreach ($this->alert_types as $group => $items)
- {
- foreach ($items as $alert_key => $alert_value)
- {
- if (isset($alert_value['permission']))
- {
+ foreach ($this->alert_types as $group => $items) {
+ foreach ($items as $alert_key => $alert_value) {
+ if (isset($alert_value['permission'])) {
$allowed = count(array_intersect(Profile::$member->groups, $member_groups[$alert_value['permission']['name']]['allowed'])) != 0;
- if (!$allowed)
+ if (!$allowed) {
unset($this->alert_types[$group][$alert_key]);
+ }
}
}
- if (empty($this->alert_types[$group]))
+ if (empty($this->alert_types[$group])) {
unset($this->alert_types[$group]);
+ }
}
}
@@ -497,37 +504,30 @@ function configuration($defaultSettings = false)
Utils::$context['alert_types'] = $this->alert_types;
Utils::$context['alert_group_options'] = $this->group_options;
- Utils::$context['alert_bits'] = array(
+ Utils::$context['alert_bits'] = [
'alert' => 0b01,
'email' => 0b10,
- );
+ ];
- if (isset($_POST['notify_submit']))
- {
+ if (isset($_POST['notify_submit'])) {
User::$me->checkSession();
SecurityToken::validate(Utils::$context['token_check'], 'post');
// We need to step through the list of valid settings and figure out what the user has set.
- $update_prefs = array();
+ $update_prefs = [];
// Now the group level options
- foreach ($this->group_options as $opt_group => $group)
- {
- foreach ($group as $this_option)
- {
- switch ($this_option[0])
- {
+ foreach ($this->group_options as $opt_group => $group) {
+ foreach ($group as $this_option) {
+ switch ($this_option[0]) {
case 'check':
$update_prefs[$this_option[1]] = !empty($_POST['opt_' . $this_option[1]]) ? 1 : 0;
break;
case 'select':
- if (isset($_POST['opt_' . $this_option[1]], $this_option['opts'][$_POST['opt_' . $this_option[1]]]))
- {
+ if (isset($_POST['opt_' . $this_option[1]], $this_option['opts'][$_POST['opt_' . $this_option[1]]])) {
$update_prefs[$this_option[1]] = $_POST['opt_' . $this_option[1]];
- }
- else
- {
+ } else {
// We didn't have a sane value. Let's grab the first item from the possibles.
$keys = array_keys($this_option['opts']);
$first = array_shift($keys);
@@ -539,16 +539,12 @@ function configuration($defaultSettings = false)
}
// Now the individual options
- foreach (Utils::$context['alert_types'] as $alert_group => $items)
- {
- foreach ($items as $item_key => $this_options)
- {
+ foreach (Utils::$context['alert_types'] as $alert_group => $items) {
+ foreach ($items as $item_key => $this_options) {
$this_value = 0;
- foreach (Utils::$context['alert_bits'] as $type => $bitvalue)
- {
- if ($this_options[$type] == 'yes' && !empty($_POST[$type . '_' . $item_key]) || $this_options[$type] == 'always')
- {
+ foreach (Utils::$context['alert_bits'] as $type => $bitvalue) {
+ if ($this_options[$type] == 'yes' && !empty($_POST[$type . '_' . $item_key]) || $this_options[$type] == 'always') {
$this_value |= $bitvalue;
}
}
@@ -557,21 +553,15 @@ function configuration($defaultSettings = false)
}
}
- if (isset($_POST['opt_alert_timeout']))
- {
+ if (isset($_POST['opt_alert_timeout'])) {
$update_prefs['alert_timeout'] = Utils::$context['member']['alert_timeout'] = (int) $_POST['opt_alert_timeout'];
- }
- else
- {
+ } else {
$update_prefs['alert_timeout'] = Utils::$context['alert_prefs']['alert_timeout'];
}
- if (isset($_POST['notify_announcements']))
- {
+ if (isset($_POST['notify_announcements'])) {
$update_prefs['announcements'] = Utils::$context['member']['notify_announcements'] = (int) $_POST['notify_announcements'];
- }
- else
- {
+ } else {
$update_prefs['announcements'] = Utils::$context['alert_prefs']['announcements'];
}
@@ -579,8 +569,9 @@ function configuration($defaultSettings = false)
Notify::setNotifyPrefs((int) Profile::$member->id, $update_prefs);
- foreach ($update_prefs as $pref => $value)
+ foreach ($update_prefs as $pref => $value) {
Utils::$context['alert_prefs'][$pref] = $value;
+ }
$this->changeNotifications();
@@ -599,7 +590,7 @@ public function markRead()
Config::$db_show_debug = false;
// We only want to output our little layer here.
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
Utils::$context['sub_template'] = 'alerts_all_read';
Lang::load('Alerts');
@@ -607,8 +598,9 @@ public function markRead()
// Now we're all set up.
User::$me->kickIfGuest();
- if (!User::$me->is_owner)
+ if (!User::$me->is_owner) {
ErrorHandler::fatal('no_access');
+ }
User::$me->checkSession('get');
@@ -621,8 +613,7 @@ public function markRead()
public function topics()
{
// Because of the way this stuff works, we want to do this ourselves.
- if (isset($_POST['edit_notify_topics']) || isset($_POST['remove_notify_topics']))
- {
+ if (isset($_POST['edit_notify_topics']) || isset($_POST['remove_notify_topics'])) {
User::$me->checkSession();
SecurityToken::validate(str_replace('%u', Profile::$member->id, 'profile-nt%u'), 'post');
@@ -635,7 +626,7 @@ public function topics()
SecurityToken::create(Utils::$context['token_check'], 'post');
// Do the topic notifications.
- $list_options = array(
+ $list_options = [
'id' => 'topic_notification_list',
'width' => '100%',
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
@@ -643,27 +634,25 @@ public function topics()
'no_items_align' => 'left',
'base_href' => Config::$scripturl . '?action=profile;u=' . Profile::$member->id . ';area=notification;sa=topics',
'default_sort_col' => 'last_post',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getTopicNotifications',
- 'params' => array(),
- ),
- 'get_count' => array(
+ 'params' => [],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getTopicNotificationCount',
- 'params' => array(),
- ),
- 'columns' => array(
- 'subject' => array(
- 'header' => array(
+ 'params' => [],
+ ],
+ 'columns' => [
+ 'subject' => [
+ 'header' => [
'value' => Lang::$txt['notifications_topics'],
'class' => 'lefttext',
- ),
- 'data' => array(
- 'function' => function($topic)
- {
+ ],
+ 'data' => [
+ 'function' => function ($topic) {
$link = $topic['link'];
- if ($topic['new'])
- {
+ if ($topic['new']) {
$link .= ' ' . Lang::$txt['new'] . '';
}
@@ -671,95 +660,95 @@ public function topics()
return $link;
},
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'ms.subject',
'reverse' => 'ms.subject DESC',
- ),
- ),
- 'started_by' => array(
- 'header' => array(
+ ],
+ ],
+ 'started_by' => [
+ 'header' => [
'value' => Lang::$txt['started_by'],
'class' => 'lefttext',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'poster_link',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'real_name_col',
'reverse' => 'real_name_col DESC',
- ),
- ),
- 'last_post' => array(
- 'header' => array(
+ ],
+ ],
+ 'last_post' => [
+ 'header' => [
'value' => Lang::$txt['last_post'],
'class' => 'lefttext',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' %1$s ' . Lang::$txt['by'] . ' %2$s',
- 'params' => array(
+ 'params' => [
'updated' => false,
'poster_updated_link' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'ml.id_msg DESC',
'reverse' => 'ml.id_msg',
- ),
- ),
- 'alert_pref' => array(
- 'header' => array(
+ ],
+ ],
+ 'alert_pref' => [
+ 'header' => [
'value' => Lang::$txt['notify_what_how'],
'class' => 'lefttext',
- ),
- 'data' => array(
- 'function' => function($topic)
- {
+ ],
+ 'data' => [
+ 'function' => function ($topic) {
$pref = $topic['notify_pref'];
$mode = !empty($topic['unwatched']) ? 0 : ($pref & 0x02 ? 3 : ($pref & 0x01 ? 2 : 1));
+
return Lang::$txt['notify_topic_' . $mode];
},
- ),
- ),
- 'delete' => array(
- 'header' => array(
+ ],
+ ],
+ 'delete' => [
+ 'header' => [
'value' => ' ',
'style' => 'width: 4%;',
'class' => 'centercol',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' ',
- 'params' => array(
+ 'params' => [
'id' => false,
- ),
- ),
+ ],
+ ],
'class' => 'centercol',
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . '?action=profile;area=notification;sa=topics',
'include_sort' => true,
'include_start' => true,
- 'hidden_fields' => array(
+ 'hidden_fields' => [
'u' => Profile::$member->id,
'sa' => Utils::$context['menu_item_selected'],
Utils::$context['session_var'] => Utils::$context['session_id'],
- ),
+ ],
'token' => Utils::$context['token_check'],
- ),
- 'additional_rows' => array(
- array(
+ ],
+ 'additional_rows' => [
+ [
'position' => 'bottom_of_list',
'value' => '
',
'class' => 'floatright',
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the notification list.
new ItemList($list_options);
@@ -771,8 +760,7 @@ public function topics()
public function boards()
{
// Because of the way this stuff works, we want to do this ourselves.
- if (isset($_POST['edit_notify_boards']) || isset($_POSt['remove_notify_boards']))
- {
+ if (isset($_POST['edit_notify_boards']) || isset($_POSt['remove_notify_boards'])) {
User::$me->checkSession();
SecurityToken::validate(str_replace('%u', Profile::$member->id, 'profile-nt%u'), 'post');
@@ -785,92 +773,90 @@ public function boards()
SecurityToken::create(Utils::$context['token_check'], 'post');
// Fine, start with the board list.
- $list_options = array(
+ $list_options = [
'id' => 'board_notification_list',
'width' => '100%',
'no_items_label' => Lang::$txt['notifications_boards_none'] . ' ' . Lang::$txt['notifications_boards_howto'],
'no_items_align' => 'left',
'base_href' => Config::$scripturl . '?action=profile;u=' . Profile::$member->id . ';area=notification;sa=boards',
'default_sort_col' => 'board_name',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getBoardNotifications',
- 'params' => array(),
- ),
- 'columns' => array(
- 'board_name' => array(
- 'header' => array(
+ 'params' => [],
+ ],
+ 'columns' => [
+ 'board_name' => [
+ 'header' => [
'value' => Lang::$txt['notifications_boards'],
'class' => 'lefttext',
- ),
- 'data' => array(
- 'function' => function($board)
- {
+ ],
+ 'data' => [
+ 'function' => function ($board) {
$link = $board['link'];
- if ($board['new'])
- {
+ if ($board['new']) {
$link .= ' ' . Lang::$txt['new'] . '';
}
return $link;
},
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'name',
'reverse' => 'name DESC',
- ),
- ),
- 'alert_pref' => array(
- 'header' => array(
+ ],
+ ],
+ 'alert_pref' => [
+ 'header' => [
'value' => Lang::$txt['notify_what_how'],
'class' => 'lefttext',
- ),
- 'data' => array(
- 'function' => function($board)
- {
+ ],
+ 'data' => [
+ 'function' => function ($board) {
$pref = $board['notify_pref'];
$mode = $pref & 0x02 ? 3 : ($pref & 0x01 ? 2 : 1);
+
return Lang::$txt['notify_board_' . $mode];
},
- ),
- ),
- 'delete' => array(
- 'header' => array(
+ ],
+ ],
+ 'delete' => [
+ 'header' => [
'value' => ' ',
'style' => 'width: 4%;',
'class' => 'centercol',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' ',
- 'params' => array(
+ 'params' => [
'id' => false,
- ),
- ),
+ ],
+ ],
'class' => 'centercol',
- ),
- ),
- ),
- 'form' => array(
+ ],
+ ],
+ ],
+ 'form' => [
'href' => Config::$scripturl . '?action=profile;area=notification;sa=boards',
'include_sort' => true,
'include_start' => true,
- 'hidden_fields' => array(
+ 'hidden_fields' => [
'u' => Profile::$member->id,
'sa' => Utils::$context['menu_item_selected'],
Utils::$context['session_var'] => Utils::$context['session_id'],
- ),
+ ],
'token' => Utils::$context['token_check'],
- ),
- 'additional_rows' => array(
- array(
+ ],
+ 'additional_rows' => [
+ [
'position' => 'bottom_of_list',
'value' => '
',
'class' => 'floatright',
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the board notification list.
new ItemList($list_options);
@@ -887,8 +873,9 @@ public function boards()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -908,17 +895,18 @@ public static function call(): void
*/
public static function list_getTopicNotificationCount()
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_notify AS ln' . (!Config::$modSettings['postmod_active'] && User::$me->query_see_board === '1=1' ? '' : '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)') . '
WHERE ln.id_member = {int:selected_member}' . (User::$me->query_see_topic_board === '1=1' ? '' : '
AND {query_see_topic_board}') . (Config::$modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved}' : ''),
- array(
+ [
'selected_member' => Profile::$member->id,
'is_approved' => 1,
- )
+ ],
);
list($totalNotifications) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -937,13 +925,14 @@ public static function list_getTopicNotificationCount()
public static function list_getTopicNotifications($start, $items_per_page, $sort)
{
$prefs = Notify::getNotifyPrefs(Profile::$member->id);
- $prefs = isset($prefs[Profile::$member->id]) ? $prefs[Profile::$member->id] : array();
+ $prefs = $prefs[Profile::$member->id] ?? [];
// All the topics with notification on...
- $notification_topics = array();
+ $notification_topics = [];
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
COALESCE(lt.id_msg, lmr.id_msg, -1) + 1 AS new_from, b.id_board, b.name,
t.id_topic, ms.subject, ms.id_member, COALESCE(mem.real_name, ms.poster_name) AS real_name_col,
ml.id_msg_modified, ml.poster_time, ml.id_member AS id_member_updated,
@@ -961,20 +950,20 @@ public static function list_getTopicNotifications($start, $items_per_page, $sort
WHERE ln.id_member = {int:selected_member}
ORDER BY {raw:sort}
LIMIT {int:offset}, {int:items_per_page}',
- array(
+ [
'current_member' => User::$me->id,
'is_approved' => 1,
'selected_member' => Profile::$member->id,
'sort' => $sort,
'offset' => $start,
'items_per_page' => $items_per_page,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Lang::censorText($row['subject']);
- $notification_topics[] = array(
+ $notification_topics[] = [
'id' => $row['id_topic'],
'poster_link' => empty($row['id_member']) ? $row['real_name_col'] : ' ' . $row['real_name_col'] . '',
'poster_updated_link' => empty($row['id_member_updated']) ? $row['last_real_name'] : ' ' . $row['last_real_name'] . '',
@@ -987,9 +976,9 @@ public static function list_getTopicNotifications($start, $items_per_page, $sort
'new_href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new',
'new_link' => ' ' . $row['subject'] . '',
'board_link' => ' ' . $row['name'] . '',
- 'notify_pref' => isset($prefs['topic_notify_' . $row['id_topic']]) ? $prefs['topic_notify_' . $row['id_topic']] : (!empty($prefs['topic_notify']) ? $prefs['topic_notify'] : 0),
+ 'notify_pref' => $prefs['topic_notify_' . $row['id_topic']] ?? (!empty($prefs['topic_notify']) ? $prefs['topic_notify'] : 0),
'unwatched' => $row['unwatched'],
- );
+ ];
}
Db::$db->free_result($request);
@@ -1007,34 +996,35 @@ public static function list_getTopicNotifications($start, $items_per_page, $sort
public static function list_getBoardNotifications($start, $items_per_page, $sort)
{
$prefs = Notify::getNotifyPrefs(Profile::$member->id);
- $prefs = isset($prefs[Profile::$member->id]) ? $prefs[Profile::$member->id] : array();
+ $prefs = $prefs[Profile::$member->id] ?? [];
- $notification_boards = array();
+ $notification_boards = [];
- $request = Db::$db->query('', '
- SELECT b.id_board, b.name, COALESCE(lb.id_msg, 0) AS board_read, b.id_msg_updated
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board, b.name, COALESCE(lb.id_msg, 0) AS board_read, b.id_msg_updated
FROM {db_prefix}log_notify AS ln
INNER JOIN {db_prefix}boards AS b ON (b.id_board = ln.id_board)
LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
WHERE ln.id_member = {int:selected_member}
AND {query_see_board}
ORDER BY {raw:sort}',
- array(
+ [
'current_member' => User::$me->id,
'selected_member' => Profile::$member->id,
'sort' => $sort,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $notification_boards[] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $notification_boards[] = [
'id' => $row['id_board'],
'name' => $row['name'],
'href' => Config::$scripturl . '?board=' . $row['id_board'] . '.0',
'link' => ' ' . $row['name'] . '',
'new' => $row['board_read'] < $row['id_msg_updated'],
- 'notify_pref' => isset($prefs['board_notify_' . $row['id_board']]) ? $prefs['board_notify_' . $row['id_board']] : (!empty($prefs['board_notify']) ? $prefs['board_notify'] : 0),
- );
+ 'notify_pref' => $prefs['board_notify_' . $row['id_board']] ?? (!empty($prefs['board_notify']) ? $prefs['board_notify'] : 0),
+ ];
}
Db::$db->free_result($request);
@@ -1115,11 +1105,13 @@ public static function makeNotificationChanges($memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
+ }
}
/**
@@ -1128,77 +1120,79 @@ protected function __construct()
protected function changeNotifications()
{
// Update the boards they are being notified about.
- if (isset($_POST['edit_notify_boards']) && !empty($_POST['notify_boards']))
- {
+ if (isset($_POST['edit_notify_boards']) && !empty($_POST['notify_boards'])) {
// Make sure only integers are deleted.
- foreach ($_POST['notify_boards'] as $index => $id)
+ foreach ($_POST['notify_boards'] as $index => $id) {
$_POST['notify_boards'][$index] = (int) $id;
+ }
// id_board = 0 is reserved for topic notifications.
- $_POST['notify_boards'] = array_diff($_POST['notify_boards'], array(0));
+ $_POST['notify_boards'] = array_diff($_POST['notify_boards'], [0]);
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_notify
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_notify
WHERE id_board IN ({array_int:board_list})
AND id_member = {int:selected_member}',
- array(
+ [
'board_list' => $_POST['notify_boards'],
'selected_member' => Profile::$member->id,
- )
+ ],
);
}
// Update the topics they are being notified about.
- if (isset($_POST['edit_notify_topics']) && !empty($_POST['notify_topics']))
- {
- foreach ($_POST['notify_topics'] as $index => $id)
+ if (isset($_POST['edit_notify_topics']) && !empty($_POST['notify_topics'])) {
+ foreach ($_POST['notify_topics'] as $index => $id) {
$_POST['notify_topics'][$index] = (int) $id;
+ }
// Make sure there are no zeros left.
$_POST['notify_topics'] = array_filter($_POST['notify_topics']);
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_notify
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_notify
WHERE id_topic IN ({array_int:topic_list})
AND id_member = {int:selected_member}',
- array(
+ [
'topic_list' => $_POST['notify_topics'],
'selected_member' => Profile::$member->id,
- )
+ ],
);
- foreach ($_POST['notify_topics'] as $topic)
- {
- Notify::setNotifyPrefs(Profile::$member->id, array('topic_notify_' . $topic => 0));
+ foreach ($_POST['notify_topics'] as $topic) {
+ Notify::setNotifyPrefs(Profile::$member->id, ['topic_notify_' . $topic => 0]);
}
}
// Are we removing topic preferences?
- if (isset($_POST['remove_notify_topics']) && !empty($_POST['notify_topics']))
- {
- $prefs = array();
+ if (isset($_POST['remove_notify_topics']) && !empty($_POST['notify_topics'])) {
+ $prefs = [];
- foreach ($_POST['notify_topics'] as $topic)
+ foreach ($_POST['notify_topics'] as $topic) {
$prefs[] = 'topic_notify_' . $topic;
+ }
Notify::deleteNotifyPrefs(Profile::$member->id, $prefs);
}
// Are we removing board preferences?
- if (isset($_POST['remove_notify_board']) && !empty($_POST['notify_boards']))
- {
- $prefs = array();
+ if (isset($_POST['remove_notify_board']) && !empty($_POST['notify_boards'])) {
+ $prefs = [];
- foreach ($_POST['notify_boards'] as $board)
+ foreach ($_POST['notify_boards'] as $board) {
$prefs[] = 'board_notify_' . $board;
-
+ }
+
Notify::deleteNotifyPrefs(Profile::$member->id, $prefs);
}
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Notification::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Notification::exportStatic')) {
Notification::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/PaidSubs.php b/Sources/Actions/Profile/PaidSubs.php
index ef561e7607..ccc47d5ebb 100644
--- a/Sources/Actions/Profile/PaidSubs.php
+++ b/Sources/Actions/Profile/PaidSubs.php
@@ -13,18 +13,17 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\Actions\Admin\Subscriptions;
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Profile;
use SMF\Theme;
use SMF\Time;
use SMF\Utils;
-use SMF\Actions\Admin\Subscriptions;
-use SMF\Db\DatabaseApi as Db;
/**
* Class for doing all the paid subscription stuff - kinda.
@@ -38,12 +37,11 @@ class PaidSubs implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'subscriptions',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -74,31 +72,25 @@ public function execute(): void
Subscriptions::getSubs();
// Remove any invalid ones.
- foreach (Subscriptions::$all as $id => $sub)
- {
+ foreach (Subscriptions::$all as $id => $sub) {
// Work out the costs.
$costs = Utils::jsonDecode($sub['real_cost'], true);
- $cost_array = array();
- if ($sub['real_length'] == 'F')
- {
- foreach ($costs as $duration => $cost)
- {
- if ($cost != 0)
+ $cost_array = [];
+
+ if ($sub['real_length'] == 'F') {
+ foreach ($costs as $duration => $cost) {
+ if ($cost != 0) {
$cost_array[$duration] = $cost;
+ }
}
- }
- else
- {
+ } else {
$cost_array['fixed'] = $costs['fixed'];
}
- if (empty($cost_array))
- {
+ if (empty($cost_array)) {
unset(Subscriptions::$all[$id]);
- }
- else
- {
+ } else {
Subscriptions::$all[$id]['member'] = 0;
Subscriptions::$all[$id]['subscribed'] = false;
Subscriptions::$all[$id]['costs'] = $cost_array;
@@ -107,36 +99,40 @@ public function execute(): void
// Work out what gateways are enabled.
$gateways = Subscriptions::loadPaymentGateways();
- foreach ($gateways as $id => $gateway)
- {
+
+ foreach ($gateways as $id => $gateway) {
$gateways[$id] = new $gateway['display_class']();
- if (!$gateways[$id]->gatewayEnabled())
+ if (!$gateways[$id]->gatewayEnabled()) {
unset($gateways[$id]);
+ }
}
// No gateways yet?
- if (empty($gateways))
+ if (empty($gateways)) {
ErrorHandler::fatal(Lang::$txt['paid_admin_not_setup_gateway']);
+ }
// Get the current subscriptions.
- Utils::$context['current'] = array();
+ Utils::$context['current'] = [];
- $request = Db::$db->query('', '
- SELECT id_sublog, id_subscribe, start_time, end_time, status, payments_pending, pending_details
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_sublog, id_subscribe, start_time, end_time, status, payments_pending, pending_details
FROM {db_prefix}log_subscribed
WHERE id_member = {int:selected_member}',
- array(
+ [
'selected_member' => Profile::$member->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// The subscription must exist!
- if (!isset(Subscriptions::$all[$row['id_subscribe']]))
+ if (!isset(Subscriptions::$all[$row['id_subscribe']])) {
continue;
+ }
- Utils::$context['current'][$row['id_subscribe']] = array(
+ Utils::$context['current'][$row['id_subscribe']] = [
'id' => $row['id_sublog'],
'sub_id' => $row['id_subscribe'],
'hide' => $row['status'] == 0 && $row['end_time'] == 0 && $row['payments_pending'] == 0,
@@ -146,33 +142,29 @@ public function execute(): void
'pending_details' => $row['pending_details'],
'status' => $row['status'],
'status_text' => $row['status'] == 0 ? ($row['payments_pending'] ? Lang::$txt['paid_pending'] : Lang::$txt['paid_finished']) : Lang::$txt['paid_active'],
- );
+ ];
- if ($row['status'] == 1)
+ if ($row['status'] == 1) {
Subscriptions::$all[$row['id_subscribe']]['subscribed'] = true;
+ }
}
Db::$db->free_result($request);
// Simple "done"?
- if (isset($_GET['done']))
- {
+ if (isset($_GET['done'])) {
$_GET['sub_id'] = (int) $_GET['sub_id'];
// Must exist but let's be sure...
- if (isset(Utils::$context['current'][$_GET['sub_id']]))
- {
+ if (isset(Utils::$context['current'][$_GET['sub_id']])) {
// What are the details like?
$current_pending = Utils::jsonDecode(Utils::$context['current'][$_GET['sub_id']]['pending_details'], true);
- if (!empty($current_pending))
- {
+ if (!empty($current_pending)) {
$current_pending = array_reverse($current_pending);
- foreach ($current_pending as $id => $sub)
- {
+ foreach ($current_pending as $id => $sub) {
// Just find one and change it.
- if ($sub[0] == $_GET['sub_id'] && $sub[3] == 'prepay')
- {
+ if ($sub[0] == $_GET['sub_id'] && $sub[3] == 'prepay') {
$current_pending[$id][3] = 'payback';
break;
}
@@ -181,16 +173,17 @@ public function execute(): void
// Save the details back.
$pending_details = Utils::jsonEncode($current_pending);
- Db::$db->query('', '
- UPDATE {db_prefix}log_subscribed
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_subscribed
SET payments_pending = payments_pending + 1, pending_details = {string:pending_details}
WHERE id_sublog = {int:current_subscription_id}
AND id_member = {int:selected_member}',
- array(
+ [
'current_subscription_id' => Utils::$context['current'][$_GET['sub_id']]['id'],
'selected_member' => Profile::$member->id,
'pending_details' => $pending_details,
- )
+ ],
);
}
}
@@ -201,43 +194,42 @@ public function execute(): void
}
// If this is confirmation then it's simpler...
- if (isset($_GET['confirm']) && isset($_POST['sub_id']) && is_array($_POST['sub_id']))
- {
+ if (isset($_GET['confirm'], $_POST['sub_id']) && is_array($_POST['sub_id'])) {
// Hopefully just one.
- foreach ($_POST['sub_id'] as $k => $v)
+ foreach ($_POST['sub_id'] as $k => $v) {
$id_sub = (int) $k;
+ }
- if (!isset(Subscriptions::$all[$id_sub]) || Subscriptions::$all[$id_sub]['active'] == 0)
+ if (!isset(Subscriptions::$all[$id_sub]) || Subscriptions::$all[$id_sub]['active'] == 0) {
ErrorHandler::fatalLang('paid_sub_not_active');
+ }
// Simplify...
Utils::$context['sub'] = Subscriptions::$all[$id_sub];
$period = 'xx';
- if (Utils::$context['sub']['flexible'])
- {
+
+ if (Utils::$context['sub']['flexible']) {
$period = isset($_POST['cur'][$id_sub]) && isset(Utils::$context['sub']['costs'][$_POST['cur'][$id_sub]]) ? $_POST['cur'][$id_sub] : 'xx';
}
// Check we have a valid cost.
- if (Utils::$context['sub']['flexible'] && $period == 'xx')
+ if (Utils::$context['sub']['flexible'] && $period == 'xx') {
ErrorHandler::fatalLang('paid_sub_not_active');
+ }
// Sort out the cost/currency.
Utils::$context['currency'] = Config::$modSettings['paid_currency_code'];
Utils::$context['recur'] = Utils::$context['sub']['repeatable'];
- if (Utils::$context['sub']['flexible'])
- {
+ if (Utils::$context['sub']['flexible']) {
// Real cost...
Utils::$context['value'] = Utils::$context['sub']['costs'][$_POST['cur'][$id_sub]];
Utils::$context['cost'] = sprintf(Config::$modSettings['paid_currency_symbol'], Utils::$context['value']) . '/' . Lang::$txt[$_POST['cur'][$id_sub]];
// The period value for paypal.
Utils::$context['paypal_period'] = strtoupper(substr($_POST['cur'][$id_sub], 0, 1));
- }
- else
- {
+ } else {
// Real cost...
Utils::$context['value'] = Utils::$context['sub']['costs']['fixed'];
Utils::$context['cost'] = sprintf(Config::$modSettings['paid_currency_symbol'], Utils::$context['value']);
@@ -249,75 +241,76 @@ public function execute(): void
}
// Setup the gateway context.
- Utils::$context['gateways'] = array();
+ Utils::$context['gateways'] = [];
- foreach ($gateways as $id => $gateway)
- {
+ foreach ($gateways as $id => $gateway) {
$fields = $gateways[$id]->fetchGatewayFields(
Utils::$context['sub']['id'] . '+' . Profile::$member->id,
Utils::$context['sub'],
Utils::$context['value'],
$period,
- Config::$scripturl . '?action=profile&u=' . Profile::$member->id . '&area=subscriptions&sub_id=' . Utils::$context['sub']['id'] . '&done'
+ Config::$scripturl . '?action=profile&u=' . Profile::$member->id . '&area=subscriptions&sub_id=' . Utils::$context['sub']['id'] . '&done',
);
- if (!empty($fields['form']))
+ if (!empty($fields['form'])) {
Utils::$context['gateways'][] = $fields;
+ }
}
// Bugger?!
- if (empty(Utils::$context['gateways']))
+ if (empty(Utils::$context['gateways'])) {
ErrorHandler::fatal(Lang::$txt['paid_admin_not_setup_gateway']);
+ }
// Now we are going to assume they want to take this out ;)
- $new_data = array(Utils::$context['sub']['id'], Utils::$context['value'], $period, 'prepay');
+ $new_data = [Utils::$context['sub']['id'], Utils::$context['value'], $period, 'prepay'];
- if (isset(Utils::$context['current'][Utils::$context['sub']['id']]))
- {
+ if (isset(Utils::$context['current'][Utils::$context['sub']['id']])) {
// What are the details like?
- $current_pending = array();
+ $current_pending = [];
- if (Utils::$context['current'][Utils::$context['sub']['id']]['pending_details'] != '')
- {
+ if (Utils::$context['current'][Utils::$context['sub']['id']]['pending_details'] != '') {
$current_pending = Utils::jsonDecode(Utils::$context['current'][Utils::$context['sub']['id']]['pending_details'], true);
}
// Don't get silly.
- if (count($current_pending) > 9)
- $current_pending = array();
+ if (count($current_pending) > 9) {
+ $current_pending = [];
+ }
// Only record real pending payments as will otherwise confuse the admin!
$pending_count = 0;
- foreach ($current_pending as $pending)
- {
- if ($pending[3] == 'payback')
+
+ foreach ($current_pending as $pending) {
+ if ($pending[3] == 'payback') {
$pending_count++;
+ }
}
- if (!in_array($new_data, $current_pending))
- {
+ if (!in_array($new_data, $current_pending)) {
$current_pending[] = $new_data;
- Db::$db->query('', '
- UPDATE {db_prefix}log_subscribed
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_subscribed
SET payments_pending = {int:pending_count}, pending_details = {string:pending_details}
WHERE id_sublog = {int:current_subscription_item}
AND id_member = {int:selected_member}',
- array(
+ [
'pending_count' => $pending_count,
'current_subscription_item' => Utils::$context['current'][Utils::$context['sub']['id']]['id'],
'selected_member' => Profile::$member->id,
'pending_details' => Utils::jsonEncode($current_pending),
- )
+ ],
);
}
}
// Never had this before, lovely.
- else
- {
- Db::$db->insert('',
+ else {
+ Db::$db->insert(
+ '',
'{db_prefix}log_subscribed',
- array(
+ [
'id_subscribe' => 'int',
'id_member' => 'int',
'status' => 'int',
@@ -325,17 +318,17 @@ public function execute(): void
'pending_details' => 'string-65534',
'start_time' => 'int',
'vendor_ref' => 'string-255',
- ),
- array(
+ ],
+ [
Utils::$context['sub']['id'],
Profile::$member->id,
0,
0,
- Utils::jsonEncode(array($new_data)),
+ Utils::jsonEncode([$new_data]),
time(),
'',
- ),
- array('id_sublog')
+ ],
+ ['id_sublog'],
);
}
@@ -345,10 +338,8 @@ public function execute(): void
// Quit.
return;
}
- else
- {
- Utils::$context['sub_template'] = 'user_subscription';
- }
+
+ Utils::$context['sub_template'] = 'user_subscription';
}
/***********************
@@ -362,8 +353,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;
}
@@ -385,13 +377,15 @@ public static function call(): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\PaidSubs::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\PaidSubs::exportStatic')) {
PaidSubs::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/Popup.php b/Sources/Actions/Profile/Popup.php
index 3a9636ebd9..94383bd792 100644
--- a/Sources/Actions/Profile/Popup.php
+++ b/Sources/Actions/Profile/Popup.php
@@ -13,9 +13,8 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -34,12 +33,11 @@ class Popup implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'profile_popup',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -49,68 +47,67 @@ class Popup implements ActionInterface
* @var array
*
* A list of menu items to pull from the main profile menu.
- *
- * The values of all 'title' elements are Lang::$txt keys, and will be
+ *
+ * The values of all 'title' elements are Lang::$txt keys, and will be
* replaced at runtime with the values of those Lang::$txt strings.
- *
- * Occurrences of '{scripturl}' in value strings will be replaced at runtime
+ *
+ * Occurrences of '{scripturl}' in value strings will be replaced at runtime
* with the value of Config::$scripturl.
*/
- public array $profile_items = array(
- array(
+ public array $profile_items = [
+ [
'menu' => 'edit_profile',
'area' => 'account',
- ),
- array(
+ ],
+ [
'menu' => 'edit_profile',
'area' => 'forumprofile',
'title' => 'popup_forumprofile',
- ),
- array(
+ ],
+ [
'menu' => 'edit_profile',
'area' => 'theme',
'title' => 'theme',
- ),
- array(
+ ],
+ [
'menu' => 'edit_profile',
'area' => 'notification',
- ),
- array(
+ ],
+ [
'menu' => 'edit_profile',
'area' => 'ignoreboards',
- ),
- array(
+ ],
+ [
'menu' => 'edit_profile',
'area' => 'lists',
'url' => '{scripturl}?action=profile;area=lists;sa=ignore',
'title' => 'popup_ignore',
- ),
- array(
+ ],
+ [
'menu' => 'info',
'area' => 'showposts',
'title' => 'popup_showposts',
- ),
- array(
+ ],
+ [
'menu' => 'info',
'area' => 'showdrafts',
'title' => 'popup_showdrafts',
- ),
- array(
+ ],
+ [
'menu' => 'edit_profile',
'area' => 'groupmembership',
'title' => 'popup_groupmembership',
- ),
- array(
+ ],
+ [
'menu' => 'profile_action',
'area' => 'subscriptions',
'title' => 'popup_subscriptions',
- ),
- array(
+ ],
+ [
'menu' => 'profile_action',
'area' => 'logout',
- ),
- );
-
+ ],
+ ];
/****************************
* Internal static properties
@@ -137,20 +134,18 @@ public function execute(): void
Config::$db_show_debug = false;
// We only want to output our little layer here.
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
- IntegrationHook::call('integrate_profile_popup', array(&$this->profile_items));
+ IntegrationHook::call('integrate_profile_popup', [&$this->profile_items]);
// Now check if these items are available
- Utils::$context['profile_items'] = array();
-
- foreach ($this->profile_items as $item)
- {
- if (isset(Menu::$loaded['profile']['sections'][$item['menu']]['areas'][$item['area']]))
- {
+ Utils::$context['profile_items'] = [];
+
+ foreach ($this->profile_items as $item) {
+ if (isset(Menu::$loaded['profile']['sections'][$item['menu']]['areas'][$item['area']])) {
Utils::$context['profile_items'][] = $item;
}
- }
+ }
}
/***********************
@@ -164,8 +159,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;
}
@@ -190,19 +186,20 @@ protected function __construct()
// Finalize various string values.
array_walk_recursive(
$this->profile_items,
- function(&$value, $key)
- {
- if ($key === 'title')
+ function (&$value, $key) {
+ if ($key === 'title') {
$value = Lang::$txt[$value] ?? $value;
+ }
- $value = strtr($value, array('{scripturl}' => Config::$scripturl));
- }
+ $value = strtr($value, ['{scripturl}' => Config::$scripturl]);
+ },
);
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Popup::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Popup::exportStatic')) {
Popup::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/ShowAlerts.php b/Sources/Actions/Profile/ShowAlerts.php
index ea57778f48..7c09830d27 100644
--- a/Sources/Actions/Profile/ShowAlerts.php
+++ b/Sources/Actions/Profile/ShowAlerts.php
@@ -13,10 +13,9 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
use SMF\Alert;
+use SMF\BackwardCompatibility;
use SMF\Config;
use SMF\Lang;
use SMF\PageIndex;
@@ -37,12 +36,11 @@ class ShowAlerts implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'showAlerts' => 'showAlerts',
+ ],
+ ];
/****************************
* Internal static properties
@@ -65,11 +63,8 @@ class ShowAlerts implements ActionInterface
*/
public function execute(): void
{
- require_once(Config::$sourcedir . '/Actions/Profile/Modify.php');
-
// Are we opening a specific alert? (i.e.: ?action=profile;area=showalerts;alert=12345)
- if (!empty($_REQUEST['alert']))
- {
+ if (!empty($_REQUEST['alert'])) {
$alert_id = (int) $_REQUEST['alert'];
$alerts = Alert::fetch(User::$me->id, $alert_id);
$alert = array_pop($alerts);
@@ -82,8 +77,9 @@ public function execute(): void
*/
// In case it failed to determine this alert's link
- if (empty($alert->target_href))
+ if (empty($alert->target_href)) {
Utils::redirectexit('action=profile;area=showalerts');
+ }
// Mark the alert as read while we're at it.
Alert::mark(User::$me->id, $alert_id, 1);
@@ -97,12 +93,9 @@ public function execute(): void
Utils::$context['start'] = (int) isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
// Fix invalid 'start' offsets.
- if (Utils::$context['start'] > User::$me->alerts)
- {
+ if (Utils::$context['start'] > User::$me->alerts) {
Utils::$context['start'] = User::$me->alerts - (User::$me->alerts % $maxIndex);
- }
- else
- {
+ } else {
Utils::$context['start'] = Utils::$context['start'] - (Utils::$context['start'] % $maxIndex);
}
@@ -118,8 +111,7 @@ public function execute(): void
Utils::$context['pagination'] = new PageIndex(Config::$scripturl . '?action=profile;area=showalerts;u=' . User::$me->id, Utils::$context['start'], User::$me->alerts, $maxIndex, false);
// Set some JavaScript for checking all alerts at once.
- if (Utils::$context['showCheckboxes'])
- {
+ if (Utils::$context['showCheckboxes']) {
Theme::addInlineJavaScript('
$(function(){
$(\'#select_all\').on(\'change\', function() {
@@ -135,46 +127,43 @@ public function execute(): void
}
// The quickbuttons
- foreach (Utils::$context['alerts'] as $id => $alert)
- {
- Utils::$context['alerts'][$id]['quickbuttons'] = array(
- 'delete' => array(
+ foreach (Utils::$context['alerts'] as $id => $alert) {
+ Utils::$context['alerts'][$id]['quickbuttons'] = [
+ 'delete' => [
'label' => Lang::$txt['delete'],
'href' => Config::$scripturl . '?action=profile;u=' . Utils::$context['id_member'] . ';area=showalerts;do=remove;aid=' . $id . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'] . (!empty(Utils::$context['start']) ? ';start=' . Utils::$context['start'] : ''),
'class' => 'you_sure',
- 'icon' => 'remove_button'
- ),
- 'mark' => array(
+ 'icon' => 'remove_button',
+ ],
+ 'mark' => [
'label' => $alert['is_read'] != 0 ? Lang::$txt['mark_unread'] : Lang::$txt['mark_read_short'],
'href' => Config::$scripturl . '?action=profile;u=' . Utils::$context['id_member'] . ';area=showalerts;do=' . ($alert['is_read'] != 0 ? 'unread' : 'read') . ';aid=' . $id . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'] . (!empty(Utils::$context['start']) ? ';start=' . Utils::$context['start'] : ''),
'icon' => $alert['is_read'] != 0 ? 'unread_button' : 'read_button',
- ),
- 'view' => array(
+ ],
+ 'view' => [
'label' => Lang::$txt['view'],
'href' => Config::$scripturl . '?action=profile;area=showalerts;alert=' . $id . ';',
'icon' => 'move',
- ),
- 'quickmod' => array(
- 'class' => 'inline_mod_check',
+ ],
+ 'quickmod' => [
+ 'class' => 'inline_mod_check',
'content' => ' ',
- 'show' => Utils::$context['showCheckboxes']
- )
- );
+ 'show' => Utils::$context['showCheckboxes'],
+ ],
+ ];
}
// The Delete all unread link.
Utils::$context['alert_purge_link'] = Config::$scripturl . '?action=profile;u=' . Utils::$context['id_member'] . ';area=showalerts;do=purge;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'] . (!empty(Utils::$context['start']) ? ';start=' . Utils::$context['start'] : '');
// Set a nice message.
- if (!empty($_SESSION['update_message']))
- {
+ if (!empty($_SESSION['update_message'])) {
Utils::$context['update_message'] = Lang::$txt['profile_updated_own'];
unset($_SESSION['update_message']);
}
// Saving multiple changes?
- if (isset($_GET['save']) && !empty($_POST['mark']))
- {
+ if (isset($_GET['save']) && !empty($_POST['mark'])) {
// Get the values.
$toMark = array_map('intval', (array) $_POST['mark']);
@@ -183,25 +172,21 @@ public function execute(): void
}
// A single change.
- if (!empty($_GET['do']) && !empty($_GET['aid']))
- {
+ if (!empty($_GET['do']) && !empty($_GET['aid'])) {
$toMark = (int) $_GET['aid'];
$action = Utils::htmlspecialchars(Utils::htmlTrim($_GET['do']));
}
// Delete all read alerts.
- elseif (!empty($_GET['do']) && $_GET['do'] === 'purge')
- {
+ elseif (!empty($_GET['do']) && $_GET['do'] === 'purge') {
$action = 'purge';
}
// Save the changes.
- if (!empty($action) && (!empty($toMark) || $action === 'purge'))
- {
+ if (!empty($action) && (!empty($toMark) || $action === 'purge')) {
User::$me->checkSession('request');
// Call it!
- switch ($action)
- {
+ switch ($action) {
case 'remove':
Alert::delete($toMark, User::$me->id);
break;
@@ -234,8 +219,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;
}
@@ -272,17 +258,20 @@ public static function showAlerts(int $memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
// Users may only view their own alerts.
- if (!User::$me->is_owner)
+ if (!User::$me->is_owner) {
Utils::redirectexit('action=profile;u=' . Profile::$member->id);
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ShowAlerts::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ShowAlerts::exportStatic')) {
ShowAlerts::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/ShowPermissions.php b/Sources/Actions/Profile/ShowPermissions.php
index adaa63676d..8f9c50611a 100644
--- a/Sources/Actions/Profile/ShowPermissions.php
+++ b/Sources/Actions/Profile/ShowPermissions.php
@@ -13,17 +13,16 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\Actions\Admin\Permissions;
+use SMF\BackwardCompatibility;
use SMF\Board;
+use SMF\Db\DatabaseApi as Db;
use SMF\Lang;
use SMF\Profile;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Actions\Admin\Permissions;
-use SMF\Db\DatabaseApi as Db;
/**
* Rename here and in the exportStatic call at the end of the file.
@@ -37,12 +36,11 @@ class ShowPermissions implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'showPermissions' => 'showPermissions',
+ ],
+ ];
/****************************
* Internal static properties
@@ -73,8 +71,9 @@ public function execute(): void
// If they're an admin we know they can do everything, so we might as well leave.
Profile::$member->formatted['has_all_permissions'] = Profile::$member->is_admin;
- if (Profile::$member->formatted['has_all_permissions'])
+ if (Profile::$member->formatted['has_all_permissions']) {
return;
+ }
// Load all the permission profiles.
Permissions::loadPermissionProfiles();
@@ -83,89 +82,86 @@ public function execute(): void
Utils::$context['board'] = Board::$info->id;
// Load a list of boards for the jump box - except the defaults.
- Utils::$context['boards'] = array();
- Utils::$context['no_access_boards'] = array();
+ Utils::$context['boards'] = [];
+ Utils::$context['no_access_boards'] = [];
- $request = Db::$db->query('order_by_board_order', '
- SELECT b.id_board, b.name, b.id_profile, b.member_groups, COALESCE(mods.id_member, modgs.id_group, 0) AS is_mod
+ $request = Db::$db->query(
+ 'order_by_board_order',
+ 'SELECT b.id_board, b.name, b.id_profile, b.member_groups, COALESCE(mods.id_member, modgs.id_group, 0) AS is_mod
FROM {db_prefix}boards AS b
LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = b.id_board AND modgs.id_group IN ({array_int:current_groups}))
WHERE {query_see_board}',
- array(
+ [
'current_member' => Profile::$member->id,
'current_groups' => Profile::$member->groups,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (!$row['is_mod'] && !Profile::$member->can_manage_boards && count(array_intersect(Profile::$member->groups, explode(',', $row['member_groups']))) === 0)
- {
- Utils::$context['no_access_boards'][] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (!$row['is_mod'] && !Profile::$member->can_manage_boards && count(array_intersect(Profile::$member->groups, explode(',', $row['member_groups']))) === 0) {
+ Utils::$context['no_access_boards'][] = [
'id' => $row['id_board'],
'name' => $row['name'],
'is_last' => false,
- );
- }
- elseif ($row['id_profile'] != 1 || $row['is_mod'])
- {
- Utils::$context['boards'][$row['id_board']] = array(
+ ];
+ } elseif ($row['id_profile'] != 1 || $row['is_mod']) {
+ Utils::$context['boards'][$row['id_board']] = [
'id' => $row['id_board'],
'name' => $row['name'],
'selected' => Board::$info->id == $row['id_board'],
'profile' => $row['id_profile'],
'profile_name' => Utils::$context['profiles'][$row['id_profile']]['name'],
- );
+ ];
}
}
Db::$db->free_result($request);
Board::sort(Utils::$context['boards']);
- if (!empty(Utils::$context['no_access_boards']))
- {
+ if (!empty(Utils::$context['no_access_boards'])) {
Utils::$context['no_access_boards'][count(Utils::$context['no_access_boards']) - 1]['is_last'] = true;
}
- Profile::$member->formatted['permissions'] = array(
- 'general' => array(),
- 'board' => array(),
- );
+ Profile::$member->formatted['permissions'] = [
+ 'general' => [],
+ 'board' => [],
+ ];
// For legibility below.
$general_perms = &Profile::$member->formatted['permissions']['general'];
$board_perms = &Profile::$member->formatted['permissions']['board'];
- $denied = array();
+ $denied = [];
// Get all general permissions.
- $result = Db::$db->query('', '
- SELECT p.permission, p.add_deny, mg.group_name, p.id_group
+ $result = Db::$db->query(
+ '',
+ 'SELECT p.permission, p.add_deny, mg.group_name, p.id_group
FROM {db_prefix}permissions AS p
LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = p.id_group)
WHERE p.id_group IN ({array_int:group_list})
ORDER BY p.add_deny DESC, p.permission, mg.min_posts, CASE WHEN mg.id_group < {int:newbie_group} THEN mg.id_group ELSE 4 END, mg.group_name',
- array(
+ [
'group_list' => Profile::$member->groups,
'newbie_group' => 4,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
// We don't know about this permission, it doesn't exist :P.
- if (!isset(Lang::$txt['permissionname_' . $row['permission']]))
+ if (!isset(Lang::$txt['permissionname_' . $row['permission']])) {
continue;
+ }
- if (empty($row['add_deny']))
+ if (empty($row['add_deny'])) {
$denied[] = $row['permission'];
+ }
// Permissions that end with _own or _any consist of two parts.
- if (in_array(substr($row['permission'], -4), array('_own', '_any')) && isset(Lang::$txt['permissionname_' . substr($row['permission'], 0, -4)]))
- {
+ if (in_array(substr($row['permission'], -4), ['_own', '_any']) && isset(Lang::$txt['permissionname_' . substr($row['permission'], 0, -4)])) {
$name = Lang::$txt['permissionname_' . substr($row['permission'], 0, -4)] . ' - ' . Lang::$txt['permissionname_' . $row['permission']];
- }
- else
- {
+ } else {
$name = Lang::$txt['permissionname_' . $row['permission']];
}
@@ -176,18 +172,17 @@ public function execute(): void
$group_name = $row['id_group'] == 0 ? Lang::$txt['membergroups_members'] : $row['group_name'];
// Add this permission if it doesn't exist yet.
- if (!isset($general_perms[$row['permission']]))
- {
- $general_perms[$row['permission']] = array(
+ if (!isset($general_perms[$row['permission']])) {
+ $general_perms[$row['permission']] = [
'id' => $row['permission'],
- 'groups' => array(
- 'allowed' => array(),
- 'denied' => array(),
- ),
+ 'groups' => [
+ 'allowed' => [],
+ 'denied' => [],
+ ],
'name' => $name,
'is_denied' => false,
'is_global' => true,
- );
+ ];
}
// Add the membergroup to either the denied or the allowed groups.
@@ -198,8 +193,9 @@ public function execute(): void
}
Db::$db->free_result($result);
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
bp.add_deny, bp.permission, bp.id_group, mg.group_name' . (empty(Board::$info->id) ? '' : ',
b.id_profile, CASE WHEN (mods.id_member IS NULL AND modgs.id_group IS NULL) THEN 0 ELSE 1 END AS is_moderator') . '
FROM {db_prefix}board_permissions AS bp' . (empty(Board::$info->id) ? '' : '
@@ -210,30 +206,28 @@ public function execute(): void
WHERE bp.id_profile = {raw:current_profile}
AND bp.id_group IN ({array_int:group_list}' . (empty(Board::$info->id) ? ')' : ', {int:moderator_group})
AND (mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR bp.id_group != {int:moderator_group})'),
- array(
+ [
'current_board' => Board::$info->id,
'group_list' => Profile::$member->groups,
'current_member' => Profile::$member->id,
'current_profile' => empty(Board::$info->id) ? '1' : 'b.id_profile',
'moderator_group' => 3,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// We don't know about this permission, it doesn't exist :P.
- if (!isset(Lang::$txt['permissionname_' . $row['permission']]))
+ if (!isset(Lang::$txt['permissionname_' . $row['permission']])) {
continue;
+ }
// The name of the permission using the format 'permission name' - 'own/any topic/event/etc.'.
if (
- in_array(substr($row['permission'], -4), array('_own', '_any'))
+ in_array(substr($row['permission'], -4), ['_own', '_any'])
&& isset(Lang::$txt['permissionname_' . substr($row['permission'], 0, -4)])
- )
- {
+ ) {
$name = Lang::$txt['permissionname_' . substr($row['permission'], 0, -4)] . ' - ' . Lang::$txt['permissionname_' . $row['permission']];
- }
- else
- {
+ } else {
$name = Lang::$txt['permissionname_' . $row['permission']];
}
@@ -244,18 +238,17 @@ public function execute(): void
$group_name = $row['id_group'] == 0 ? Lang::$txt['membergroups_members'] : $row['group_name'];
// Create the structure for this permission.
- if (!isset($board_perms[$row['permission']]))
- {
- $board_perms[$row['permission']] = array(
+ if (!isset($board_perms[$row['permission']])) {
+ $board_perms[$row['permission']] = [
'id' => $row['permission'],
- 'groups' => array(
- 'allowed' => array(),
- 'denied' => array()
- ),
+ 'groups' => [
+ 'allowed' => [],
+ 'denied' => [],
+ ],
'name' => $name,
'is_denied' => false,
'is_global' => empty(Board::$info->id),
- );
+ ];
}
$board_perms[$row['permission']]['groups'][$denied_allowed][$row['id_group']] = $group_name;
@@ -276,8 +269,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;
}
@@ -318,13 +312,15 @@ protected function __construct()
Lang::load('Admin');
Theme::loadTemplate('ManageMembers');
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ShowPermissions::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ShowPermissions::exportStatic')) {
ShowPermissions::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/ShowPosts.php b/Sources/Actions/Profile/ShowPosts.php
index 15996d7018..08cdc164ff 100644
--- a/Sources/Actions/Profile/ShowPosts.php
+++ b/Sources/Actions/Profile/ShowPosts.php
@@ -13,12 +13,12 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\ItemList;
@@ -32,7 +32,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Rename here and in the exportStatic call at the end of the file.
@@ -46,12 +45,17 @@ class ShowPosts implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'list_getUnwatched' => 'list_getUnwatched',
+ 'list_getNumUnwatched' => 'list_getNumUnwatched',
+ 'list_getAttachments' => 'list_getAttachments',
+ 'list_getNumAttachments' => 'list_getNumAttachments',
+ 'showPosts' => 'showPosts',
+ 'showUnwatched' => 'showUnwatched',
+ 'showAttachments' => 'showAttachments',
+ ],
+ ];
/*******************
* Public properties
@@ -74,12 +78,12 @@ class ShowPosts implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'messages' => 'messages',
'topics' => 'topics',
'unwatchedtopics' => 'unwatched',
'attach' => 'attachments',
- );
+ ];
/****************************
* Internal static properties
@@ -107,21 +111,21 @@ public function execute(): void
Utils::$context['current_member'] = Profile::$member->id;
// Create the tabs for the template.
- Menu::$loaded['profile']->tab_data = array(
+ Menu::$loaded['profile']->tab_data = [
'title' => Lang::$txt['showPosts'],
'description' => Lang::$txt['showPosts_help'],
'icon_class' => 'main_icons profile_hd',
- 'tabs' => array(
- 'messages' => array(
- ),
- 'topics' => array(
- ),
- 'unwatchedtopics' => array(
- ),
- 'attach' => array(
- ),
- ),
- );
+ 'tabs' => [
+ 'messages' => [
+ ],
+ 'topics' => [
+ ],
+ 'unwatchedtopics' => [
+ ],
+ 'attach' => [
+ ],
+ ],
+ ];
$this->setPageTitle();
@@ -130,15 +134,15 @@ public function execute(): void
!empty(Utils::$context['load_average'])
&& !empty(Config::$modSettings['loadavg_show_posts'])
&& Utils::$context['load_average'] >= Config::$modSettings['loadavg_show_posts']
- )
- {
+ ) {
ErrorHandler::fatalLang('loadavg_show_posts_disabled', false);
}
- $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);
+ }
}
/**
@@ -149,8 +153,9 @@ public function messages(): void
Utils::$context['is_topics'] = false;
// If just deleting a message, do it and then redirect back.
- if (isset($_GET['delete']))
+ if (isset($_GET['delete'])) {
$this->deletePost();
+ }
$this->loadPosts();
}
@@ -171,104 +176,105 @@ public function topics(): void
public function unwatched(): void
{
// Only the owner can see the list (if the function is enabled of course)
- if (!User::$me->is_owner)
- Utils::redirectexit('action=profile;u=' . Profile::$member->id . ';area=showposts');;
+ if (!User::$me->is_owner) {
+ Utils::redirectexit('action=profile;u=' . Profile::$member->id . ';area=showposts');
+ }
// And here they are: the topics you don't like
- $list_options = array(
+ $list_options = [
'id' => 'unwatched_topics',
'width' => '100%',
'items_per_page' => (empty(Config::$modSettings['disableCustomPerPage']) && !empty(Theme::$current->options['topics_per_page'])) ? Theme::$current->options['topics_per_page'] : Config::$modSettings['defaultMaxTopics'],
'no_items_label' => Lang::$txt['unwatched_topics_none'],
'base_href' => Config::$scripturl . '?action=profile;area=showposts;sa=unwatchedtopics;u=' . Profile::$member->id,
'default_sort_col' => 'started_on',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getUnwatched',
- 'params' => array(),
- ),
- 'get_count' => array(
+ 'params' => [],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getNumUnwatched',
- 'params' => array(),
- ),
- 'columns' => array(
- 'subject' => array(
- 'header' => array(
+ 'params' => [],
+ ],
+ 'columns' => [
+ 'subject' => [
+ 'header' => [
'value' => Lang::$txt['subject'],
'class' => 'lefttext',
'style' => 'width: 30%;',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' %2$s',
- 'params' => array(
+ 'params' => [
'id_topic' => false,
'subject' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'm.subject',
'reverse' => 'm.subject DESC',
- ),
- ),
- 'started_by' => array(
- 'header' => array(
+ ],
+ ],
+ 'started_by' => [
+ 'header' => [
'value' => Lang::$txt['started_by'],
'style' => 'width: 15%;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'started_by',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'mem.real_name',
'reverse' => 'mem.real_name DESC',
- ),
- ),
- 'started_on' => array(
- 'header' => array(
+ ],
+ ],
+ 'started_on' => [
+ 'header' => [
'value' => Lang::$txt['on'],
'class' => 'lefttext',
'style' => 'width: 20%;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'started_on',
'timeformat' => true,
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'm.poster_time',
'reverse' => 'm.poster_time DESC',
- ),
- ),
- 'last_post_by' => array(
- 'header' => array(
+ ],
+ ],
+ 'last_post_by' => [
+ 'header' => [
'value' => Lang::$txt['last_post'],
'style' => 'width: 15%;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'last_post_by',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'mem.real_name',
'reverse' => 'mem.real_name DESC',
- ),
- ),
- 'last_post_on' => array(
- 'header' => array(
+ ],
+ ],
+ 'last_post_on' => [
+ 'header' => [
'value' => Lang::$txt['on'],
'class' => 'lefttext',
'style' => 'width: 20%;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'last_post_on',
'timeformat' => true,
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'm.poster_time',
'reverse' => 'm.poster_time DESC',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
// Create the request list.
new ItemList($list_options);
@@ -286,108 +292,108 @@ public function attachments(): void
$boards_allowed = User::$me->boardsAllowedTo('view_attachments');
// Make sure we can't actually see anything...
- if (empty($boards_allowed))
- $boards_allowed = array(-1);
+ if (empty($boards_allowed)) {
+ $boards_allowed = [-1];
+ }
// This is all the information required to list attachments.
- $list_options = array(
+ $list_options = [
'id' => 'attachments',
'width' => '100%',
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['show_attachments_none'],
'base_href' => Config::$scripturl . '?action=profile;area=showposts;sa=attach;u=' . Profile::$member->id,
'default_sort_col' => 'filename',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getAttachments',
- 'params' => array(
+ 'params' => [
$boards_allowed,
- ),
- ),
- 'get_count' => array(
+ ],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getNumAttachments',
- 'params' => array(
+ 'params' => [
$boards_allowed,
- ),
- ),
- 'data_check' => array(
- 'class' => function($data)
- {
+ ],
+ ],
+ 'data_check' => [
+ 'class' => function ($data) {
return $data['approved'] ? '' : 'approvebg';
- }
- ),
- 'columns' => array(
- 'filename' => array(
- 'header' => array(
+ },
+ ],
+ 'columns' => [
+ 'filename' => [
+ 'header' => [
'value' => Lang::$txt['show_attach_filename'],
'class' => 'lefttext',
'style' => 'width: 25%;',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' %3$s%4$s',
- 'params' => array(
+ 'params' => [
'topic' => true,
'id' => true,
'filename' => false,
'awaiting_approval' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'a.filename',
'reverse' => 'a.filename DESC',
- ),
- ),
- 'downloads' => array(
- 'header' => array(
+ ],
+ ],
+ 'downloads' => [
+ 'header' => [
'value' => Lang::$txt['show_attach_downloads'],
'style' => 'width: 12%;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'downloads',
'comma_format' => true,
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'a.downloads',
'reverse' => 'a.downloads DESC',
- ),
- ),
- 'subject' => array(
- 'header' => array(
+ ],
+ ],
+ 'subject' => [
+ 'header' => [
'value' => Lang::$txt['message'],
'class' => 'lefttext',
'style' => 'width: 30%;',
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' %2$s',
- 'params' => array(
+ 'params' => [
'msg' => true,
'subject' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'm.subject',
'reverse' => 'm.subject DESC',
- ),
- ),
- 'posted' => array(
- 'header' => array(
+ ],
+ ],
+ 'posted' => [
+ 'header' => [
'value' => Lang::$txt['show_attach_posted'],
'class' => 'lefttext',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'posted',
'timeformat' => true,
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'm.poster_time',
'reverse' => 'm.poster_time DESC',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
// Create the request list.
new ItemList($list_options);
@@ -404,8 +410,9 @@ public function attachments(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -429,51 +436,52 @@ public static function call(): void
public static function list_getUnwatched(int $start, int $items_per_page, string $sort): array
{
// Get the list of topics we can see
- $topics = array();
+ $topics = [];
- $request = Db::$db->query('', '
- SELECT lt.id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT lt.id_topic
FROM {db_prefix}log_topics as lt
LEFT JOIN {db_prefix}topics as t ON (lt.id_topic = t.id_topic)
- LEFT JOIN {db_prefix}messages as m ON (t.id_first_msg = m.id_msg)' . (in_array($sort, array('mem.real_name', 'mem.real_name DESC', 'mem.poster_time', 'mem.poster_time DESC')) ? '
+ LEFT JOIN {db_prefix}messages as m ON (t.id_first_msg = m.id_msg)' . (in_array($sort, ['mem.real_name', 'mem.real_name DESC', 'mem.poster_time', 'mem.poster_time DESC']) ? '
LEFT JOIN {db_prefix}members as mem ON (m.id_member = mem.id_member)' : '') . '
WHERE lt.id_member = {int:current_member}
AND unwatched = 1
AND {query_see_message_board}
ORDER BY {raw:sort}
LIMIT {int:offset}, {int:limit}',
- array(
+ [
'current_member' => Profile::$member->id,
'sort' => $sort,
'offset' => $start,
'limit' => $items_per_page,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$topics[] = $row['id_topic'];
}
Db::$db->free_result($request);
// Any topics found?
- $topics_info = array();
+ $topics_info = [];
- if (!empty($topics))
- {
- $request = Db::$db->query('', '
- SELECT mf.subject, mf.poster_time as started_on, COALESCE(memf.real_name, mf.poster_name) as started_by, ml.poster_time as last_post_on, COALESCE(meml.real_name, ml.poster_name) as last_post_by, t.id_topic
+ if (!empty($topics)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT mf.subject, mf.poster_time as started_on, COALESCE(memf.real_name, mf.poster_name) as started_by, ml.poster_time as last_post_on, COALESCE(meml.real_name, ml.poster_name) as last_post_by, t.id_topic
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)
LEFT JOIN {db_prefix}members AS memf ON (memf.id_member = mf.id_member)
WHERE t.id_topic IN ({array_int:topics})',
- array(
+ [
'topics' => $topics,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$topics_info[] = $row;
}
Db::$db->free_result($request);
@@ -490,16 +498,17 @@ public static function list_getUnwatched(int $start, int $items_per_page, string
public static function list_getNumUnwatched(): int
{
// Get the total number of attachments they have posted.
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_topics as lt
LEFT JOIN {db_prefix}topics as t ON (lt.id_topic = t.id_topic)
WHERE lt.id_member = {int:current_member}
AND lt.unwatched = 1
AND {query_see_topic_board}',
- array(
+ [
'current_member' => Profile::$member->id,
- )
+ ],
);
list($unwatched_count) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -519,10 +528,11 @@ public static function list_getNumUnwatched(): int
public static function list_getAttachments(int $start, int $items_per_page, string $sort, array $boards_allowed): array
{
// Retrieve some attachments.
- $attachments = array();
+ $attachments = [];
- $request = Db::$db->query('', '
- SELECT a.id_attach, a.id_msg, a.filename, a.downloads, a.approved, m.id_msg, m.id_topic,
+ $request = Db::$db->query(
+ '',
+ 'SELECT a.id_attach, a.id_msg, a.filename, a.downloads, a.approved, m.id_msg, m.id_topic,
m.id_board, m.poster_time, m.subject, b.name
FROM {db_prefix}attachments AS a
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
@@ -535,7 +545,7 @@ public static function list_getAttachments(int $start, int $items_per_page, stri
AND a.approved = {int:is_approved}') . '
ORDER BY {raw:sort}
LIMIT {int:offset}, {int:limit}',
- array(
+ [
'boards_list' => $boards_allowed,
'attachment_type' => 0,
'no_message' => 0,
@@ -545,11 +555,11 @@ public static function list_getAttachments(int $start, int $items_per_page, stri
'sort' => $sort,
'offset' => $start,
'limit' => $items_per_page,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $attachments[] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $attachments[] = [
'id' => $row['id_attach'],
'filename' => $row['filename'],
'downloads' => $row['downloads'],
@@ -561,7 +571,7 @@ public static function list_getAttachments(int $start, int $items_per_page, stri
'board_name' => $row['name'],
'approved' => $row['approved'],
'awaiting_approval' => (empty($row['approved']) ? ' (' . Lang::$txt['awaiting_approval'] . ')' : ''),
- );
+ ];
}
Db::$db->free_result($request);
@@ -577,8 +587,9 @@ public static function list_getAttachments(int $start, int $items_per_page, stri
public static function list_getNumAttachments(array $boards_allowed): int
{
// Get the total number of attachments they have posted.
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}attachments AS a
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND {query_see_board})' . (!Config::$modSettings['postmod_active'] || User::$me->is_owner || User::$me->allowedTo('approve_posts') ? '' : '
@@ -590,14 +601,14 @@ public static function list_getNumAttachments(array $boards_allowed): int
AND b.id_board IN ({array_int:boards_list})' : '') . (!Config::$modSettings['postmod_active'] || User::$me->is_owner || User::$me->allowedTo('approve_posts') ? '' : '
AND m.approved = {int:is_approved}
AND t.approved = {int:is_approved}'),
- array(
+ [
'boards_list' => $boards_allowed,
'attachment_type' => 0,
'no_message' => 0,
'current_member' => Profile::$member->id,
'is_approved' => 1,
'board' => Board::$info->id ?? 0,
- )
+ ],
);
list($attach_count) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -661,11 +672,13 @@ public static function showAttachments(int $memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
+ }
}
/**
@@ -674,12 +687,12 @@ protected function __construct()
protected function setPageTitle(): void
{
// Shortcut used to determine which Lang::$txt['show*'] string to use for the title, based on the SA
- $title = array(
+ $title = [
'messages' => 'showPosts',
'topics' => 'showTopics',
'unwatchedtopics' => User::$me->is_owner ? 'showUnwatched' : 'showPosts',
'attach' => 'showAttachments',
- );
+ ];
// Set the page title
Utils::$context['page_title'] = Lang::$txt[$title[$_REQUEST['sa'] ?? 'messages'] ?? $title['messages']] . ' - ' . Profile::$member->name;
@@ -691,26 +704,27 @@ protected function setPageTitle(): void
protected function deletePost(): void
{
// Double check, just in case...
- if (!isset($_GET['delete']))
+ if (!isset($_GET['delete'])) {
return;
+ }
User::$me->checkSession('get');
// We need msg info for logging.
- $request = Db::$db->query('', '
- SELECT subject, id_member, id_topic, id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT subject, id_member, id_topic, id_board
FROM {db_prefix}messages
WHERE id_msg = {int:id_msg}',
- array(
+ [
'id_msg' => (int) $_GET['delete'],
- )
+ ],
);
$info = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Trying to remove a message that doesn't exist.
- if (empty($info))
- {
+ if (empty($info)) {
Utils::redirectexit('action=profile;u=' . Profile::$member->id . ';area=showposts;start=' . $_GET['start']);
}
@@ -718,14 +732,13 @@ protected function deletePost(): void
Msg::remove((int) $_GET['delete']);
// Add it to the mod log.
- if (User::$me->allowedTo('delete_any') && (!User::$me->allowedTo('delete_own') || $info[1] != User::$me->id))
- {
- Logging::logAction('delete', array(
+ if (User::$me->allowedTo('delete_any') && (!User::$me->allowedTo('delete_own') || $info[1] != User::$me->id)) {
+ Logging::logAction('delete', [
'topic' => $info[2],
'subject' => $info[0],
'member' => $info[1],
'board' => $info[3],
- ));
+ ]);
}
// Back to... where we are now ;).
@@ -738,70 +751,68 @@ protected function deletePost(): void
protected function loadPosts($is_topics = false): void
{
// Default to 10.
- if (empty($_REQUEST['viewscount']) || !is_numeric($_REQUEST['viewscount']))
+ if (empty($_REQUEST['viewscount']) || !is_numeric($_REQUEST['viewscount'])) {
$_REQUEST['viewscount'] = '10';
+ }
- if ($is_topics)
- {
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ if ($is_topics) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}topics AS t' . '
WHERE {query_see_topic_board}
AND t.id_member_started = {int:current_member}' . (!empty(Board::$info->id) ? '
AND t.id_board = {int:board}' : '') . (!Config::$modSettings['postmod_active'] || User::$me->is_owner ? '' : '
AND t.approved = {int:is_approved}'),
- array(
+ [
'current_member' => Profile::$member->id,
'is_approved' => 1,
'board' => Board::$info->id ?? 0,
- )
+ ],
);
- }
- else
- {
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ } else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}messages AS m' . (!Config::$modSettings['postmod_active'] || User::$me->is_owner ? '' : '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)') . '
WHERE {query_see_message_board} AND m.id_member = {int:current_member}' . (!empty(Board::$info->id) ? '
AND m.id_board = {int:board}' : '') . (!Config::$modSettings['postmod_active'] || User::$me->is_owner ? '' : '
AND m.approved = {int:is_approved}
AND t.approved = {int:is_approved}'),
- array(
+ [
'current_member' => Profile::$member->id,
'is_approved' => 1,
'board' => Board::$info->id ?? 0,
- )
+ ],
);
}
list($msg_count) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- $request = Db::$db->query('', '
- SELECT MIN(id_msg), MAX(id_msg)
+ $request = Db::$db->query(
+ '',
+ 'SELECT MIN(id_msg), MAX(id_msg)
FROM {db_prefix}messages AS m' . (!Config::$modSettings['postmod_active'] || User::$me->is_owner ? '' : '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)') . '
WHERE m.id_member = {int:current_member}' . (!empty(Board::$info->id) ? '
AND m.id_board = {int:board}' : '') . (!Config::$modSettings['postmod_active'] || User::$me->is_owner ? '' : '
AND m.approved = {int:is_approved}
AND t.approved = {int:is_approved}'),
- array(
+ [
'current_member' => Profile::$member->id,
'is_approved' => 1,
'board' => Board::$info->id ?? 0,
- )
+ ],
);
list($min_msg_member, $max_msg_member) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
$range_limit = '';
- if ($is_topics)
- {
+ if ($is_topics) {
$max_per_page = empty(Config::$modSettings['disableCustomPerPage']) && !empty(Theme::$current->options['topics_per_page']) ? Theme::$current->options['topics_per_page'] : Config::$modSettings['defaultMaxTopics'];
- }
- else
- {
+ } else {
$max_per_page = empty(Config::$modSettings['disableCustomPerPage']) && !empty(Theme::$current->options['messages_per_page']) ? Theme::$current->options['messages_per_page'] : Config::$modSettings['defaultMaxMessages'];
}
@@ -816,41 +827,36 @@ protected function loadPosts($is_topics = false): void
$start = Utils::$context['start'];
$reverse = $_REQUEST['start'] > $msg_count / 2;
- if ($reverse)
- {
+ if ($reverse) {
$max_index = $msg_count < Utils::$context['start'] + $max_per_page + 1 && $msg_count > Utils::$context['start'] ? $msg_count - Utils::$context['start'] : $max_per_page;
$start = $msg_count < Utils::$context['start'] + $max_per_page + 1 || $msg_count < Utils::$context['start'] + $max_per_page ? 0 : $msg_count - Utils::$context['start'] - $max_per_page;
}
// Guess the range of messages to be shown.
- if ($msg_count > 1000)
- {
+ if ($msg_count > 1000) {
$margin = floor(($max_msg_member - $min_msg_member) * (($start + $max_per_page) / $msg_count) + .1 * ($max_msg_member - $min_msg_member));
// Make a bigger margin for topics only.
- if ($is_topics)
- {
+ if ($is_topics) {
$margin *= 5;
$range_limit = $reverse ? 't.id_first_msg < ' . ($min_msg_member + $margin) : 't.id_first_msg > ' . ($max_msg_member - $margin);
- }
- else
- {
+ } else {
$range_limit = $reverse ? 'm.id_msg < ' . ($min_msg_member + $margin) : 'm.id_msg > ' . ($max_msg_member - $margin);
}
}
// Find this user's posts. The left join on categories somehow makes this faster, weird as it looks.
$counter = $reverse ? Utils::$context['start'] + $max_index + 1 : Utils::$context['start'];
- Utils::$context['posts'] = array();
- $board_ids = array('own' => array(), 'any' => array());
+ Utils::$context['posts'] = [];
+ $board_ids = ['own' => [], 'any' => []];
$looped = false;
- while (true)
- {
- if ($is_topics)
- {
- $request = Db::$db->query('', '
- SELECT
+
+ while (true) {
+ if ($is_topics) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT
b.id_board, b.name AS bname, c.id_cat, c.name AS cname, t.id_member_started, t.id_first_msg, t.id_last_msg,
t.approved, m.body, m.smileys_enabled, m.subject, m.poster_time, m.id_topic, m.id_msg
FROM {db_prefix}topics AS t
@@ -864,19 +870,18 @@ protected function loadPosts($is_topics = false): void
AND t.approved = {int:is_approved} AND m.approved = {int:is_approved}') . '
ORDER BY t.id_first_msg ' . ($reverse ? 'ASC' : 'DESC') . '
LIMIT {int:start}, {int:max}',
- array(
+ [
'current_member' => Profile::$member->id,
'is_approved' => 1,
'board' => Board::$info->id ?? 0,
'start' => $start,
'max' => $max_index,
- )
+ ],
);
- }
- else
- {
- $request = Db::$db->query('', '
- SELECT
+ } else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT
b.id_board, b.name AS bname, c.id_cat, c.name AS cname, m.id_topic, m.id_msg,
t.id_member_started, t.id_first_msg, t.id_last_msg, m.body, m.smileys_enabled,
m.subject, m.poster_time, m.approved
@@ -891,26 +896,27 @@ protected function loadPosts($is_topics = false): void
AND t.approved = {int:is_approved} AND m.approved = {int:is_approved}') . '
ORDER BY m.id_msg ' . ($reverse ? 'ASC' : 'DESC') . '
LIMIT {int:start}, {int:max}',
- array(
+ [
'current_member' => Profile::$member->id,
'is_approved' => 1,
'board' => Board::$info->id ?? 0,
'start' => $start,
'max' => $max_index,
- )
+ ],
);
}
// Make sure we quit this loop.
- if (Db::$db->num_rows($request) === $max_index || $looped || $range_limit == '')
+ if (Db::$db->num_rows($request) === $max_index || $looped || $range_limit == '') {
break;
+ }
$looped = true;
$range_limit = '';
}
+
// Start counting at the number of the first message displayed.
- while ($row = Db::$db->fetch_assoc($request))
- {
+ while ($row = Db::$db->fetch_assoc($request)) {
// Censor....
Lang::censorText($row['body']);
Lang::censorText($row['subject']);
@@ -919,17 +925,17 @@ protected function loadPosts($is_topics = false): void
$row['body'] = BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], $row['id_msg']);
// And the array...
- Utils::$context['posts'][$counter += $reverse ? -1 : 1] = array(
+ Utils::$context['posts'][$counter += $reverse ? -1 : 1] = [
'body' => $row['body'],
'counter' => $counter,
- 'category' => array(
+ 'category' => [
'name' => $row['cname'],
- 'id' => $row['id_cat']
- ),
- 'board' => array(
+ 'id' => $row['id_cat'],
+ ],
+ 'board' => [
'name' => $row['bname'],
- 'id' => $row['id_board']
- ),
+ 'id' => $row['id_board'],
+ ],
'topic' => $row['id_topic'],
'subject' => $row['subject'],
'start' => 'msg' . $row['id_msg'],
@@ -942,43 +948,42 @@ protected function loadPosts($is_topics = false): void
'delete_possible' => ($row['id_first_msg'] != $row['id_msg'] || $row['id_last_msg'] == $row['id_msg']) && (empty(Config::$modSettings['edit_disable_time']) || $row['poster_time'] + Config::$modSettings['edit_disable_time'] * 60 >= time()),
'approved' => $row['approved'],
'css_class' => $row['approved'] ? 'windowbg' : 'approvebg',
- );
+ ];
- if (User::$me->id == $row['id_member_started'])
+ if (User::$me->id == $row['id_member_started']) {
$board_ids['own'][$row['id_board']][] = $counter;
+ }
$board_ids['any'][$row['id_board']][] = $counter;
}
Db::$db->free_result($request);
// All posts were retrieved in reverse order, get them right again.
- if ($reverse)
+ if ($reverse) {
Utils::$context['posts'] = array_reverse(Utils::$context['posts'], true);
+ }
// These are all the permissions that are different from board to board..
- if ($is_topics)
- {
- $permissions = array(
- 'own' => array(
+ if ($is_topics) {
+ $permissions = [
+ 'own' => [
'post_reply_own' => 'can_reply',
- ),
- 'any' => array(
+ ],
+ 'any' => [
'post_reply_any' => 'can_reply',
- )
- );
- }
- else
- {
- $permissions = array(
- 'own' => array(
+ ],
+ ];
+ } else {
+ $permissions = [
+ 'own' => [
'post_reply_own' => 'can_reply',
'delete_own' => 'can_delete',
- ),
- 'any' => array(
+ ],
+ 'any' => [
'post_reply_any' => 'can_reply',
'delete_any' => 'can_delete',
- )
- );
+ ],
+ ];
}
// Create an array for the permissions.
@@ -986,36 +991,36 @@ protected function loadPosts($is_topics = false): void
array_keys(
iterator_to_array(
new \RecursiveIteratorIterator(
- new \RecursiveArrayIterator($permissions)
- )
- )
+ new \RecursiveArrayIterator($permissions),
+ ),
+ ),
),
true,
- false
+ false,
);
// For every permission in the own/any lists...
- foreach ($permissions as $type => $list)
- {
- foreach ($list as $permission => $allowed)
- {
+ foreach ($permissions as $type => $list) {
+ foreach ($list as $permission => $allowed) {
// Get the boards they can do this on...
$boards = $boards_can[$permission];
// Hmm, they can do it on all boards, can they?
- if (!empty($boards) && $boards[0] == 0)
+ if (!empty($boards) && $boards[0] == 0) {
$boards = array_keys($board_ids[$type]);
+ }
// Now go through each board they can do the permission on.
- foreach ($boards as $board_id)
- {
+ foreach ($boards as $board_id) {
// There aren't any posts displayed from this board.
- if (!isset($board_ids[$type][$board_id]))
+ if (!isset($board_ids[$type][$board_id])) {
continue;
+ }
// Set the permission to true ;).
- foreach ($board_ids[$type][$board_id] as $counter)
+ foreach ($board_ids[$type][$board_id] as $counter) {
Utils::$context['posts'][$counter][$allowed] = true;
+ }
}
}
}
@@ -1023,8 +1028,7 @@ protected function loadPosts($is_topics = false): void
// Clean up after posts that cannot be deleted and quoted.
$quote_enabled = empty(Config::$modSettings['disabledBBC']) || !in_array('quote', explode(',', Config::$modSettings['disabledBBC']));
- foreach (Utils::$context['posts'] as $counter => $dummy)
- {
+ foreach (Utils::$context['posts'] as $counter => $dummy) {
Utils::$context['posts'][$counter]['can_delete'] &= Utils::$context['posts'][$counter]['delete_possible'];
Utils::$context['posts'][$counter]['can_quote'] = Utils::$context['posts'][$counter]['can_reply'] && $quote_enabled;
@@ -1033,36 +1037,36 @@ protected function loadPosts($is_topics = false): void
// Allow last minute changes.
IntegrationHook::call('integrate_profile_showPosts');
- foreach (Utils::$context['posts'] as $key => $post)
- {
- Utils::$context['posts'][$key]['quickbuttons'] = array(
- 'reply' => array(
+ foreach (Utils::$context['posts'] as $key => $post) {
+ Utils::$context['posts'][$key]['quickbuttons'] = [
+ 'reply' => [
'label' => Lang::$txt['reply'],
'href' => Config::$scripturl . '?action=post;topic=' . $post['topic'] . '.' . $post['start'],
'icon' => 'reply_button',
- 'show' => $post['can_reply']
- ),
- 'quote' => array(
+ 'show' => $post['can_reply'],
+ ],
+ 'quote' => [
'label' => Lang::$txt['quote_action'],
'href' => Config::$scripturl . '?action=post;topic=' . $post['topic'] . '.' . $post['start'] . ';quote=' . $post['id'],
'icon' => 'quote',
- 'show' => $post['can_quote']
- ),
- 'remove' => array(
+ 'show' => $post['can_quote'],
+ ],
+ 'remove' => [
'label' => Lang::$txt['remove'],
'href' => Config::$scripturl . '?action=deletemsg;msg=' . $post['id'] . ';topic=' . $post['topic'] . ';profile;u=' . Utils::$context['member']['id'] . ';start=' . Utils::$context['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'javascript' => 'data-confirm="' . Lang::$txt['remove_message'] . '"',
'class' => 'you_sure',
'icon' => 'remove_button',
- 'show' => $post['can_delete']
- )
- );
+ 'show' => $post['can_delete'],
+ ],
+ ];
}
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ShowPosts::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ShowPosts::exportStatic')) {
ShowPosts::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/StatPanel.php b/Sources/Actions/Profile/StatPanel.php
index d9b60b855a..f4167dd47f 100644
--- a/Sources/Actions/Profile/StatPanel.php
+++ b/Sources/Actions/Profile/StatPanel.php
@@ -13,10 +13,10 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -24,7 +24,6 @@
use SMF\Profile;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Rename here and in the exportStatic call at the end of the file.
@@ -38,12 +37,11 @@ class StatPanel implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'statPanel' => 'statPanel',
+ ],
+ ];
/****************************
* Internal static properties
@@ -69,14 +67,13 @@ public function execute(): void
Utils::$context['page_title'] = Lang::$txt['statPanel_showStats'] . ' ' . Profile::$member->name;
// Menu tab
- Menu::$loaded['profile']->tab_data = array(
+ Menu::$loaded['profile']->tab_data = [
'title' => Lang::$txt['statPanel_generalStats'] . ' - ' . Profile::$member->name,
- 'icon' => 'stats_info.png'
- );
+ 'icon' => 'stats_info.png',
+ ];
// Is the load average too high to allow searching just now?
- if (!empty(Utils::$context['load_average']) && !empty(Config::$modSettings['loadavg_userstats']) && Utils::$context['load_average'] >= Config::$modSettings['loadavg_userstats'])
- {
+ if (!empty(Utils::$context['load_average']) && !empty(Config::$modSettings['loadavg_userstats']) && Utils::$context['load_average'] >= Config::$modSettings['loadavg_userstats']) {
ErrorHandler::fatalLang('loadavg_userstats_disabled', false);
}
@@ -86,28 +83,30 @@ public function execute(): void
Utils::$context['num_posts'] = Lang::numberFormat(Profile::$member->posts);
// Number of topics started and Number polls started
- $result = Db::$db->query('', '
- SELECT COUNT(*), COUNT( CASE WHEN id_poll != {int:no_poll} THEN 1 ELSE NULL END )
+ $result = Db::$db->query(
+ '',
+ 'SELECT COUNT(*), COUNT( CASE WHEN id_poll != {int:no_poll} THEN 1 ELSE NULL END )
FROM {db_prefix}topics
WHERE id_member_started = {int:current_member}' . (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0 ? '
AND id_board != {int:recycle_board}' : ''),
- array(
+ [
'current_member' => Profile::$member->id,
'recycle_board' => Config::$modSettings['recycle_board'],
'no_poll' => 0,
- )
+ ],
);
list(Utils::$context['num_topics'], Utils::$context['num_polls']) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
// Number polls voted in.
- $result = Db::$db->query('distinct_poll_votes', '
- SELECT COUNT(DISTINCT id_poll)
+ $result = Db::$db->query(
+ 'distinct_poll_votes',
+ 'SELECT COUNT(DISTINCT id_poll)
FROM {db_prefix}log_polls
WHERE id_member = {int:current_member}',
- array(
+ [
'current_member' => Profile::$member->id,
- )
+ ],
);
list(Utils::$context['num_votes']) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
@@ -118,10 +117,11 @@ public function execute(): void
Utils::$context['num_votes'] = Lang::numberFormat(Utils::$context['num_votes']);
// Grab the boards this member posted in most often.
- Utils::$context['popular_boards'] = array();
+ Utils::$context['popular_boards'] = [];
- $result = Db::$db->query('', '
- SELECT
+ $result = Db::$db->query(
+ '',
+ 'SELECT
b.id_board, MAX(b.name) AS name, MAX(b.num_posts) AS num_posts, COUNT(*) AS message_count
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
@@ -131,14 +131,14 @@ public function execute(): void
GROUP BY b.id_board
ORDER BY message_count DESC
LIMIT 10',
- array(
+ [
'current_member' => Profile::$member->id,
'count_enabled' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
- Utils::$context['popular_boards'][$row['id_board']] = array(
+
+ while ($row = Db::$db->fetch_assoc($result)) {
+ Utils::$context['popular_boards'][$row['id_board']] = [
'id' => $row['id_board'],
'posts' => $row['message_count'],
'href' => Config::$scripturl . '?board=' . $row['id_board'] . '.0',
@@ -146,15 +146,16 @@ public function execute(): void
'posts_percent' => Profile::$member->posts == 0 ? 0 : ($row['message_count'] * 100) / Profile::$member->posts,
'total_posts' => $row['num_posts'],
'total_posts_member' => Profile::$member->posts,
- );
+ ];
}
Db::$db->free_result($result);
// Now get the 10 boards this user has most often participated in.
- Utils::$context['board_activity'] = array();
+ Utils::$context['board_activity'] = [];
- $result = Db::$db->query('profile_board_stats', '
- SELECT
+ $result = Db::$db->query(
+ 'profile_board_stats',
+ 'SELECT
b.id_board, MAX(b.name) AS name, b.num_posts, COUNT(*) AS message_count,
CASE WHEN COUNT(*) > MAX(b.num_posts) THEN 1 ELSE COUNT(*) / MAX(b.num_posts) END * 100 AS percentage
FROM {db_prefix}messages AS m
@@ -164,13 +165,13 @@ public function execute(): void
GROUP BY b.id_board, b.num_posts
ORDER BY percentage DESC
LIMIT 10',
- array(
+ [
'current_member' => Profile::$member->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
- Utils::$context['board_activity'][$row['id_board']] = array(
+
+ while ($row = Db::$db->fetch_assoc($result)) {
+ Utils::$context['board_activity'][$row['id_board']] = [
'id' => $row['id_board'],
'posts' => $row['message_count'],
'href' => Config::$scripturl . '?board=' . $row['id_board'] . '.0',
@@ -178,16 +179,17 @@ public function execute(): void
'percent' => Lang::numberFormat((float) $row['percentage'], 2),
'posts_percent' => (float) $row['percentage'],
'total_posts' => $row['num_posts'],
- );
+ ];
}
Db::$db->free_result($result);
// Posting activity by time.
$maxPosts = $realPosts = 0;
- Utils::$context['posts_by_time'] = array();
+ Utils::$context['posts_by_time'] = [];
- $result = Db::$db->query('user_activity_by_time', '
- SELECT
+ $result = Db::$db->query(
+ 'user_activity_by_time',
+ 'SELECT
HOUR(FROM_UNIXTIME(poster_time + {int:time_offset})) AS hour,
COUNT(*) AS post_count
FROM (
@@ -197,45 +199,42 @@ public function execute(): void
LIMIT {int:max_messages}
) a
GROUP BY hour',
- array(
+ [
'current_member' => Profile::$member->id,
'time_offset' => User::$me->time_offset * 3600,
'max_messages' => 1001,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
// Cast as an integer to remove the leading 0.
$row['hour'] = (int) $row['hour'];
$maxPosts = max($row['post_count'], $maxPosts);
$realPosts += $row['post_count'];
- Utils::$context['posts_by_time'][$row['hour']] = array(
+ Utils::$context['posts_by_time'][$row['hour']] = [
'hour' => $row['hour'],
'hour_format' => stripos(User::$me->time_format, '%p') === false ? $row['hour'] : date('g a', mktime($row['hour'])),
'posts' => $row['post_count'],
'posts_percent' => 0,
'is_last' => $row['hour'] == 23,
- );
+ ];
}
Db::$db->free_result($result);
- if ($maxPosts > 0)
- {
- for ($hour = 0; $hour < 24; $hour++)
- {
- if (!isset(Utils::$context['posts_by_time'][$hour]))
- Utils::$context['posts_by_time'][$hour] = array(
+ if ($maxPosts > 0) {
+ for ($hour = 0; $hour < 24; $hour++) {
+ if (!isset(Utils::$context['posts_by_time'][$hour])) {
+ Utils::$context['posts_by_time'][$hour] = [
'hour' => $hour,
'hour_format' => stripos(User::$me->time_format, '%p') === false ? $hour : date('g a', mktime($hour)),
'posts' => 0,
'posts_percent' => 0,
'relative_percent' => 0,
'is_last' => $hour == 23,
- );
- else
- {
+ ];
+ } else {
Utils::$context['posts_by_time'][$hour]['posts_percent'] = round((Utils::$context['posts_by_time'][$hour]['posts'] * 100) / $realPosts);
Utils::$context['posts_by_time'][$hour]['relative_percent'] = round((Utils::$context['posts_by_time'][$hour]['posts'] * 100) / $maxPosts);
}
@@ -245,7 +244,7 @@ public function execute(): void
// Put it in the right order.
ksort(Utils::$context['posts_by_time']);
- /**
+ /*
* Adding new entries:
* 'key' => array(
* 'text' => string, // The text that will be shown next to the entry.
@@ -255,28 +254,28 @@ public function execute(): void
* 'key' will be used to look up the language string as Lang::$txt['statPanel_' . $key].
* Make sure to add a new entry when writing your mod!
*/
- Utils::$context['text_stats'] = array(
- 'total_time_online' => array(
+ Utils::$context['text_stats'] = [
+ 'total_time_online' => [
'text' => Utils::$context['time_logged_in'],
- ),
- 'total_posts' => array(
+ ],
+ 'total_posts' => [
'text' => Utils::$context['num_posts'] . ' ' . Lang::$txt['statPanel_posts'],
- 'url' => Config::$scripturl . '?action=profile;area=showposts;sa=messages;u=' . Profile::$member->id
- ),
- 'total_topics' => array(
+ 'url' => Config::$scripturl . '?action=profile;area=showposts;sa=messages;u=' . Profile::$member->id,
+ ],
+ 'total_topics' => [
'text' => Utils::$context['num_topics'] . ' ' . Lang::$txt['statPanel_topics'],
- 'url' => Config::$scripturl . '?action=profile;area=showposts;sa=topics;u=' . Profile::$member->id
- ),
- 'users_polls' => array(
+ 'url' => Config::$scripturl . '?action=profile;area=showposts;sa=topics;u=' . Profile::$member->id,
+ ],
+ 'users_polls' => [
'text' => Utils::$context['num_polls'] . ' ' . Lang::$txt['statPanel_polls'],
- ),
- 'users_votes' => array(
- 'text' => Utils::$context['num_votes'] . ' ' . Lang::$txt['statPanel_votes']
- )
- );
+ ],
+ 'users_votes' => [
+ 'text' => Utils::$context['num_votes'] . ' ' . Lang::$txt['statPanel_votes'],
+ ],
+ ];
// Custom stats (just add a template_layer to add it to the template!)
- IntegrationHook::call('integrate_profile_stats', array(Profile::$member->id, &Utils::$context['text_stats']));
+ IntegrationHook::call('integrate_profile_stats', [Profile::$member->id, &Utils::$context['text_stats']]);
}
/***********************
@@ -290,8 +289,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;
}
@@ -328,13 +328,15 @@ public static function statPanel(int $memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\StatPanel::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\StatPanel::exportStatic')) {
StatPanel::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/Summary.php b/Sources/Actions/Profile/Summary.php
index c4442ee7a7..19e2b3b1b4 100644
--- a/Sources/Actions/Profile/Summary.php
+++ b/Sources/Actions/Profile/Summary.php
@@ -13,10 +13,11 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\Actions\Who;
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\IP;
use SMF\Lang;
use SMF\Menu;
@@ -25,8 +26,6 @@
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Actions\Who;
-use SMF\Db\DatabaseApi as Db;
/**
* Shows a summary of a member's profile.
@@ -40,12 +39,11 @@ class Summary implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'summary' => 'summary',
+ ],
+ ];
/****************************
* Internal static properties
@@ -69,71 +67,59 @@ class Summary implements ActionInterface
public function execute(): void
{
// Menu tab
- Menu::$loaded['profile']->tab_data = array(
+ Menu::$loaded['profile']->tab_data = [
'title' => Lang::$txt['summary'],
- 'icon_class' => 'main_icons profile_hd'
- );
+ 'icon_class' => 'main_icons profile_hd',
+ ];
// Set up the stuff and load the user.
- Utils::$context += array(
+ Utils::$context += [
'page_title' => sprintf(Lang::$txt['profile_of_username'], Profile::$member->formatted['name']),
'can_send_pm' => User::$me->allowedTo('pm_send'),
'can_have_buddy' => User::$me->allowedTo('profile_extra_own') && !empty(Config::$modSettings['enable_buddylist']),
'can_issue_warning' => User::$me->allowedTo('issue_warning') && Config::$modSettings['warning_settings'][0] == 1,
- 'can_view_warning' => (User::$me->allowedTo('moderate_forum') || User::$me->allowedTo('issue_warning') || User::$me->allowedTo('view_warning_any') || (User::$me->is_owner && User::$me->allowedTo('view_warning_own'))) && Config::$modSettings['warning_settings'][0] === '1'
- );
+ 'can_view_warning' => (User::$me->allowedTo('moderate_forum') || User::$me->allowedTo('issue_warning') || User::$me->allowedTo('view_warning_any') || (User::$me->is_owner && User::$me->allowedTo('view_warning_own'))) && Config::$modSettings['warning_settings'][0] === '1',
+ ];
// Set a canonical URL for this page.
Utils::$context['canonical_url'] = Config::$scripturl . '?action=profile;u=' . Profile::$member->id;
// See if they have broken any warning levels...
- if (!empty(Config::$modSettings['warning_mute']) && Config::$modSettings['warning_mute'] <= Profile::$member->formatted['warning'])
- {
+ if (!empty(Config::$modSettings['warning_mute']) && Config::$modSettings['warning_mute'] <= Profile::$member->formatted['warning']) {
Utils::$context['warning_status'] = Lang::$txt['profile_warning_is_muted'];
- }
- elseif (!empty(Config::$modSettings['warning_moderate']) && Config::$modSettings['warning_moderate'] <= Profile::$member->formatted['warning'])
- {
+ } elseif (!empty(Config::$modSettings['warning_moderate']) && Config::$modSettings['warning_moderate'] <= Profile::$member->formatted['warning']) {
Utils::$context['warning_status'] = Lang::$txt['profile_warning_is_moderation'];
- }
- elseif (!empty(Config::$modSettings['warning_watch']) && Config::$modSettings['warning_watch'] <= Profile::$member->formatted['warning'])
- {
+ } elseif (!empty(Config::$modSettings['warning_watch']) && Config::$modSettings['warning_watch'] <= Profile::$member->formatted['warning']) {
Utils::$context['warning_status'] = Lang::$txt['profile_warning_is_watch'];
}
// They haven't even been registered for a full day!?
$days_registered = (int) ((time() - Profile::$member->date_registered) / (3600 * 24));
- if (empty(Profile::$member->date_registered) || $days_registered < 1)
- {
+ if (empty(Profile::$member->date_registered) || $days_registered < 1) {
Profile::$member->formatted['posts_per_day'] = Lang::$txt['not_applicable'];
- }
- else
- {
+ } else {
Profile::$member->formatted['posts_per_day'] = Lang::numberFormat(Profile::$member->formatted['real_posts'] / $days_registered, 3);
}
// Set the age...
- if (empty(Profile::$member->formatted['birth_date']) || substr(Profile::$member->formatted['birth_date'], 0, 4) < 1002)
- {
- Profile::$member->formatted += array(
+ if (empty(Profile::$member->formatted['birth_date']) || substr(Profile::$member->formatted['birth_date'], 0, 4) < 1002) {
+ Profile::$member->formatted += [
'age' => Lang::$txt['not_applicable'],
- 'today_is_birthday' => false
- );
- }
- else
- {
+ 'today_is_birthday' => false,
+ ];
+ } else {
list($birth_year, $birth_month, $birth_day) = sscanf(Profile::$member->formatted['birth_date'], '%d-%d-%d');
$datearray = getdate(time());
- Profile::$member->formatted += array(
+ Profile::$member->formatted += [
'age' => $birth_year <= 1004 ? Lang::$txt['not_applicable'] : $datearray['year'] - $birth_year - (($datearray['mon'] > $birth_month || ($datearray['mon'] == $birth_month && $datearray['mday'] >= $birth_day)) ? 0 : 1),
- 'today_is_birthday' => $datearray['mon'] == $birth_month && $datearray['mday'] == $birth_day && $birth_year > 1004
- );
+ 'today_is_birthday' => $datearray['mon'] == $birth_month && $datearray['mday'] == $birth_day && $birth_year > 1004,
+ ];
}
- if (Utils::$context['can_see_ip'] && empty(Config::$modSettings['disableHostnameLookup']) && filter_var(Profile::$member->formatted['ip'], FILTER_VALIDATE_IP) !== false)
- {
+ if (Utils::$context['can_see_ip'] && empty(Config::$modSettings['disableHostnameLookup']) && filter_var(Profile::$member->formatted['ip'], FILTER_VALIDATE_IP) !== false) {
$ip = new IP(Profile::$member->formatted['ip']);
Profile::$member->formatted['hostname'] = $ip->getHost();
}
@@ -142,126 +128,120 @@ public function execute(): void
Profile::$member->formatted['is_hidden'] = empty(Profile::$member->show_online);
Profile::$member->formatted['show_last_login'] = User::$me->allowedTo('admin_forum') || !Profile::$member->formatted['is_hidden'];
- if (!empty(Config::$modSettings['who_enabled']) && Profile::$member->formatted['show_last_login'])
- {
+ if (!empty(Config::$modSettings['who_enabled']) && Profile::$member->formatted['show_last_login']) {
$action = Who::determineActions(Profile::$member->url);
- if ($action !== false)
+ if ($action !== false) {
Profile::$member->formatted['action'] = $action;
+ }
}
// If the user is awaiting activation, and the viewer has permission, set up some activation context messages.
- if (Profile::$member->formatted['is_activated'] % 10 != 1 && User::$me->allowedTo('moderate_forum'))
- {
+ if (Profile::$member->formatted['is_activated'] % 10 != 1 && User::$me->allowedTo('moderate_forum')) {
Utils::$context['activate_type'] = Profile::$member->formatted['is_activated'];
// What should the link text be?
- Utils::$context['activate_link_text'] = in_array(Profile::$member->formatted['is_activated'], array(3, 4, 5, 13, 14, 15)) ? Lang::$txt['account_approve'] : Lang::$txt['account_activate'];
+ Utils::$context['activate_link_text'] = in_array(Profile::$member->formatted['is_activated'], [3, 4, 5, 13, 14, 15]) ? Lang::$txt['account_approve'] : Lang::$txt['account_activate'];
// Should we show a custom message?
- Utils::$context['activate_message'] = isset(Lang::$txt['account_activate_method_' . Profile::$member->formatted['is_activated'] % 10]) ? Lang::$txt['account_activate_method_' . Profile::$member->formatted['is_activated'] % 10] : Lang::$txt['account_not_activated'];
+ Utils::$context['activate_message'] = Lang::$txt['account_activate_method_' . Profile::$member->formatted['is_activated'] % 10] ?? Lang::$txt['account_not_activated'];
// If they can be approved, we need to set up a token for them.
Utils::$context['token_check'] = 'profile-aa' . Profile::$member->id;
SecurityToken::create(Utils::$context['token_check'], 'get');
// Puerile comment
- $type = in_array(Profile::$member->formatted['is_activated'], array(3, 4, 5, 13, 14, 15)) ? 'approve' : 'activate';
+ $type = in_array(Profile::$member->formatted['is_activated'], [3, 4, 5, 13, 14, 15]) ? 'approve' : 'activate';
Utils::$context['activate_link'] = Config::$scripturl . '?action=admin;area=viewmembers;sa=browse;type=' . $type . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'] . ';' . Utils::$context[Utils::$context['token_check'] . '_token_var'] . '=' . Utils::$context[Utils::$context['token_check'] . '_token'];
}
// Prevent signature images from going outside the box.
- if (Utils::$context['signature_enabled'])
- {
+ if (Utils::$context['signature_enabled']) {
list($sig_limits, $sig_bbc) = explode(':', Config::$modSettings['signature_settings']);
$sig_limits = explode(',', $sig_limits);
- if (!empty($sig_limits[5]) || !empty($sig_limits[6]))
- {
+ if (!empty($sig_limits[5]) || !empty($sig_limits[6])) {
Theme::addInlineCss("\n\t" . '.signature img { ' . (!empty($sig_limits[5]) ? 'max-width: ' . (int) $sig_limits[5] . 'px; ' : '') . (!empty($sig_limits[6]) ? 'max-height: ' . (int) $sig_limits[6] . 'px; ' : '') . '}');
}
}
// How about, are they banned?
- Profile::$member->formatted['bans'] = array();
+ Profile::$member->formatted['bans'] = [];
- if (User::$me->allowedTo('moderate_forum'))
- {
+ if (User::$me->allowedTo('moderate_forum')) {
// Can they edit the ban?
Utils::$context['can_edit_ban'] = User::$me->allowedTo('manage_bans');
- $ban_query = array();
- $ban_query_vars = array(
+ $ban_query = [];
+ $ban_query_vars = [
'time' => time(),
- );
+ ];
$ban_query[] = 'id_member = ' . Profile::$member->formatted['id'];
$ban_query[] = ' {inet:ip} BETWEEN bi.ip_low and bi.ip_high';
$ban_query_vars['ip'] = Profile::$member->formatted['ip'];
// Do we have a hostname already?
- if (!empty(Profile::$member->formatted['hostname']))
- {
+ if (!empty(Profile::$member->formatted['hostname'])) {
$ban_query[] = '({string:hostname} LIKE hostname)';
$ban_query_vars['hostname'] = Profile::$member->formatted['hostname'];
}
// Check their email as well...
- if (strlen(Profile::$member->formatted['email']) != 0)
- {
+ if (strlen(Profile::$member->formatted['email']) != 0) {
$ban_query[] = '({string:email} LIKE bi.email_address)';
$ban_query_vars['email'] = Profile::$member->formatted['email'];
}
// So... are they banned? Dying to know!
- $request = Db::$db->query('', '
- SELECT bg.id_ban_group, bg.name, bg.cannot_access, bg.cannot_post,
+ $request = Db::$db->query(
+ '',
+ 'SELECT bg.id_ban_group, bg.name, bg.cannot_access, bg.cannot_post,
bg.cannot_login, bg.reason
FROM {db_prefix}ban_items AS bi
INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group AND (bg.expire_time IS NULL OR bg.expire_time > {int:time}))
WHERE (' . implode(' OR ', $ban_query) . ')',
- $ban_query_vars
+ $ban_query_vars,
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Work out what restrictions we actually have.
- $ban_restrictions = array();
+ $ban_restrictions = [];
- foreach (array('access', 'login', 'post') as $type)
- {
- if ($row['cannot_' . $type])
+ foreach (['access', 'login', 'post'] as $type) {
+ if ($row['cannot_' . $type]) {
$ban_restrictions[] = Lang::$txt['ban_type_' . $type];
+ }
}
// No actual ban in place?
- if (empty($ban_restrictions))
+ if (empty($ban_restrictions)) {
continue;
+ }
// Prepare the link for context.
$ban_explanation = sprintf(Lang::$txt['user_cannot_due_to'], implode(', ', $ban_restrictions), ' ' . $row['name'] . '');
- Profile::$member->formatted['bans'][$row['id_ban_group']] = array(
+ Profile::$member->formatted['bans'][$row['id_ban_group']] = [
'reason' => empty($row['reason']) ? '' : ' ' . Lang::$txt['ban_reason'] . ': ' . $row['reason'],
- 'cannot' => array(
+ 'cannot' => [
'access' => !empty($row['cannot_access']),
'post' => !empty($row['cannot_post']),
'login' => !empty($row['cannot_login']),
- ),
+ ],
'explanation' => $ban_explanation,
- );
+ ];
}
Db::$db->free_result($request);
}
Profile::$member->loadCustomFields();
- Utils::$context['print_custom_fields'] = array();
+ Utils::$context['print_custom_fields'] = [];
// Any custom profile fields?
- if (!empty(Utils::$context['custom_fields']))
- {
- foreach (Utils::$context['custom_fields'] as $custom)
- {
+ if (!empty(Utils::$context['custom_fields'])) {
+ foreach (Utils::$context['custom_fields'] as $custom) {
Utils::$context['print_custom_fields'][Utils::$context['cust_profile_fields_placement'][$custom['placement']]][] = $custom;
}
}
@@ -278,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;
}
@@ -316,11 +297,12 @@ public static function summary(int $memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
// Are there things we don't show?
- Utils::$context['disabled_fields'] = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : array();
+ Utils::$context['disabled_fields'] = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : [];
// Is the signature even enabled on this forum?
Utils::$context['signature_enabled'] = substr(Config::$modSettings['signature_settings'], 0, 1) == 1;
@@ -334,7 +316,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Summary::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Summary::exportStatic')) {
Summary::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/TFADisable.php b/Sources/Actions/Profile/TFADisable.php
index 6a867dd339..519dfe7509 100644
--- a/Sources/Actions/Profile/TFADisable.php
+++ b/Sources/Actions/Profile/TFADisable.php
@@ -13,15 +13,14 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Profile;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Provides interface to disable two-factor authentication in SMF.
@@ -35,12 +34,11 @@ class TFADisable implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'tfadisable',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -63,35 +61,39 @@ class TFADisable implements ActionInterface
*/
public function execute(): void
{
- if (empty(User::$me->tfa_secret))
+ if (empty(User::$me->tfa_secret)) {
Utils::redirectexit('action=profile;area=account;u=' . Profile::$member->id);
+ }
// Bail if we're forcing SSL for authentication and the network connection isn't secure.
- if (!empty(Config::$modSettings['force_ssl']) && !Config::httpsOn())
+ if (!empty(Config::$modSettings['force_ssl']) && !Config::httpsOn()) {
ErrorHandler::fatalLang('login_ssl_required', false);
+ }
// The admin giveth...
- if (Config::$modSettings['tfa_mode'] == 3 && User::$me->is_owner)
+ if (Config::$modSettings['tfa_mode'] == 3 && User::$me->is_owner) {
ErrorHandler::fatalLang('cannot_disable_tfa', false);
+ }
- if (Config::$modSettings['tfa_mode'] == 2 && User::$me->is_owner)
- {
- $request = Db::$db->query('', '
- SELECT id_group
+ if (Config::$modSettings['tfa_mode'] == 2 && User::$me->is_owner) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_group
FROM {db_prefix}membergroups
WHERE tfa_required = {int:tfa_required}
AND id_group IN ({array_int:groups})',
- array(
+ [
'tfa_required' => 1,
- 'groups' => array_diff(User::$me->groups, array(User::$me->post_group_id)),
- )
+ 'groups' => array_diff(User::$me->groups, [User::$me->post_group_id]),
+ ],
);
$tfa_required_groups = Db::$db->num_rows($request);
Db::$db->free_result($request);
// They belong to a membergroup that requires tfa.
- if (!empty($tfa_required_groups))
+ if (!empty($tfa_required_groups)) {
ErrorHandler::fatalLang('cannot_disable_tfa2', false);
+ }
}
}
@@ -106,8 +108,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;
}
@@ -129,13 +132,15 @@ public static function call(): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TFADisable::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TFADisable::exportStatic')) {
TFADisable::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/TFASetup.php b/Sources/Actions/Profile/TFASetup.php
index 61b2cbfdee..830e7c3174 100644
--- a/Sources/Actions/Profile/TFASetup.php
+++ b/Sources/Actions/Profile/TFASetup.php
@@ -13,18 +13,17 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
use SMF\Cookie;
use SMF\ErrorHandler;
use SMF\Profile;
use SMF\Security;
use SMF\Theme;
+use SMF\TOTP\Auth as Tfa;
use SMF\User;
use SMF\Utils;
-use SMF\TOTP\Auth as Tfa;
/**
* Provides interface to set up two-factor authentication in SMF.
@@ -38,12 +37,11 @@ class TFASetup implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'tfasetup',
- ),
- );
+ ],
+ ];
/*********************
* Internal properties
@@ -78,33 +76,29 @@ class TFASetup implements ActionInterface
public function execute(): void
{
// Users have to do this for themselves, and can't do it again if they already did.
- if (!User::$me->is_owner || !empty(User::$me->tfa_secret))
+ if (!User::$me->is_owner || !empty(User::$me->tfa_secret)) {
Utils::redirectexit('action=profile;area=account;u=' . Profile::$member->id);
+ }
// Load JS lib for QR
- Theme::loadJavaScriptFile('qrcode.js', array('force_current' => false, 'validate' => true));
+ Theme::loadJavaScriptFile('qrcode.js', ['force_current' => false, 'validate' => true]);
// Check to ensure we're forcing SSL for authentication.
- if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn())
- {
+ if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn()) {
ErrorHandler::fatalLang('login_ssl_required', false);
}
// In some cases (forced 2FA or backup code) they would be forced to be redirected here,
// we do not want too much AJAX to confuse them.
- if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && !isset($_REQUEST['backup']) && !isset($_REQUEST['forced']))
- {
+ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && !isset($_REQUEST['backup']) && !isset($_REQUEST['forced'])) {
Utils::$context['from_ajax'] = true;
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
}
// When the code is being sent, verify to make sure the user got it right
- if (!empty($_REQUEST['save']) && !empty($_SESSION['tfa_secret']))
- {
+ if (!empty($_REQUEST['save']) && !empty($_SESSION['tfa_secret'])) {
$this->validateAndSave();
- }
- else
- {
+ } else {
$this->generate();
}
@@ -122,8 +116,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;
}
@@ -145,8 +140,9 @@ public static function call(): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
/**
@@ -160,15 +156,14 @@ protected function validateAndSave(): void
$this->totp->setRange(1);
$valid_code = strlen($code) == $this->totp->getCodeLength() && $this->totp->validateCode($code);
- if (empty(Utils::$context['password_auth_failed']) && $valid_code)
- {
+ if (empty(Utils::$context['password_auth_failed']) && $valid_code) {
$backup = substr(sha1(Utils::randomInt()), 0, 16);
$backup_encrypted = Security::hashPassword(User::$me->username, $backup);
- User::updateMemberData(Profile::$member->id, array(
+ User::updateMemberData(Profile::$member->id, [
'tfa_secret' => $_SESSION['tfa_secret'],
'tfa_backup' => $backup_encrypted,
- ));
+ ]);
Cookie::setTFACookie(3153600, Profile::$member->id, Cookie::encrypt($backup_encrypted, User::$me->password_salt));
@@ -176,9 +171,7 @@ protected function validateAndSave(): void
Utils::$context['tfa_backup'] = $backup;
Utils::$context['sub_template'] = 'tfasetup_backup';
- }
- else
- {
+ } else {
Utils::$context['tfa_secret'] = $_SESSION['tfa_secret'];
Utils::$context['tfa_error'] = !$valid_code;
Utils::$context['tfa_pass_value'] = $_POST['oldpasswrd'];
@@ -200,7 +193,8 @@ protected function generate(): void
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TFASetup::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TFASetup::exportStatic')) {
TFASetup::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/ThemeOptions.php b/Sources/Actions/Profile/ThemeOptions.php
index 7c4cbbebe1..0546dec658 100644
--- a/Sources/Actions/Profile/ThemeOptions.php
+++ b/Sources/Actions/Profile/ThemeOptions.php
@@ -13,9 +13,8 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Profile;
@@ -35,12 +34,11 @@ class ThemeOptions implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'theme',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -71,23 +69,22 @@ public function execute(): void
Profile::$member->loadThemeOptions();
- if (User::$me->allowedTo(array('profile_extra_own', 'profile_extra_any')))
- {
+ if (User::$me->allowedTo(['profile_extra_own', 'profile_extra_any'])) {
Profile::$member->loadCustomFields('theme');
}
Utils::$context['page_desc'] = Lang::$txt['theme_info'];
Profile::$member->setupContext(
- array(
- 'id_theme',
- 'smiley_set',
- 'hr',
- 'time_format',
- 'timezone',
- 'hr',
+ [
+ 'id_theme',
+ 'smiley_set',
+ 'hr',
+ 'time_format',
+ 'timezone',
+ 'hr',
'theme_settings',
- ),
+ ],
);
}
@@ -102,8 +99,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;
}
@@ -125,13 +123,15 @@ public static function call(): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ThemeOptions::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ThemeOptions::exportStatic')) {
ThemeOptions::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/Tracking.php b/Sources/Actions/Profile/Tracking.php
index 5c63d256ff..0a88b402b0 100644
--- a/Sources/Actions/Profile/Tracking.php
+++ b/Sources/Actions/Profile/Tracking.php
@@ -13,11 +13,12 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\Actions\TrackIP;
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IP;
use SMF\ItemList;
@@ -27,8 +28,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Actions\TrackIP;
-use SMF\Db\DatabaseApi as Db;
/**
* Rename here and in the exportStatic call at the end of the file.
@@ -42,12 +41,23 @@ class Tracking implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'tracking',
- ),
- );
+ 'list_getUserErrors' => 'list_getUserErrors',
+ 'list_getUserErrorCount' => 'list_getUserErrorCount',
+ 'list_getProfileEdits' => 'list_getProfileEdits',
+ 'list_getProfileEditCount' => 'list_getProfileEditCount',
+ 'list_getGroupRequests' => 'list_getGroupRequests',
+ 'list_getGroupRequestsCount' => 'list_getGroupRequestsCount',
+ 'list_getLogins' => 'list_getLogins',
+ 'list_getLoginCount' => 'list_getLoginCount',
+ 'trackActivity' => 'trackActivity',
+ 'trackEdits' => 'trackEdits',
+ 'trackGroupReq' => 'trackGroupReq',
+ 'trackLogins' => 'TrackLogins',
+ ],
+ ];
/*******************
* Public properties
@@ -75,33 +85,33 @@ class Tracking implements ActionInterface
*
* array('method', 'txt_key_for_page_title', 'permission')
*/
- public static array $subactions = array(
- 'activity' => array(
+ public static array $subactions = [
+ 'activity' => [
'activity',
'trackActivity',
'moderate_forum',
- ),
- 'ip' => array(
+ ],
+ 'ip' => [
'ip',
'trackIP',
'moderate_forum',
- ),
- 'edits' => array(
+ ],
+ 'edits' => [
'edits',
'trackEdits',
'moderate_forum',
- ),
- 'groupreq' => array(
+ ],
+ 'groupreq' => [
'groupRequests',
'trackGroupRequests',
'approve_group_requests',
- ),
- 'logins' => array(
+ ],
+ 'logins' => [
'logins',
'trackLogins',
'moderate_forum',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -124,30 +134,33 @@ class Tracking implements ActionInterface
*/
public function execute(): void
{
- if (!isset($this->subaction, self::$subactions))
+ if (!isset($this->subaction, self::$subactions)) {
ErrorHandler::fatalLang('no_access', false);
+ }
// This is only here for backward compatiblity in case a mod needs it.
Utils::$context['tracking_area'] = &$this->subaction;
// Create the tabs for the template.
- Menu::$loaded['profile']->tab_data = array(
+ Menu::$loaded['profile']->tab_data = [
'title' => Lang::$txt['tracking'],
'description' => Lang::$txt['tracking_description'],
'icon_class' => 'main_icons profile_hd',
- 'tabs' => array(),
- );
+ 'tabs' => [],
+ ];
- foreach (self::$subactions as $sa => $dummy)
- Menu::$loaded['profile']->tab_data['tabs'][$sa] = array();
+ foreach (self::$subactions as $sa => $dummy) {
+ Menu::$loaded['profile']->tab_data['tabs'][$sa] = [];
+ }
// Set a page title.
Utils::$context['page_title'] = Lang::$txt['trackUser'] . ' - ' . Lang::$txt[self::$subactions[$this->subaction][1]] . ' - ' . Profile::$member->name;
- $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);
+ }
}
/**
@@ -163,100 +176,101 @@ public function activity(): void
Utils::$context['last_ip'] = Profile::$member->ip;
- if (Utils::$context['last_ip'] != Profile::$member->ip2)
+ if (Utils::$context['last_ip'] != Profile::$member->ip2) {
Utils::$context['last_ip2'] = Profile::$member->ip2;
+ }
Utils::$context['member']['name'] = Profile::$member->name;
// Set the options for the list component.
- $list_options = array(
+ $list_options = [
'id' => 'track_user_list',
'title' => Lang::$txt['errors_by'] . ' ' . Utils::$context['member']['name'],
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['no_errors_from_user'],
'base_href' => Config::$scripturl . '?action=profile;area=tracking;sa=user;u=' . Profile::$member->id,
'default_sort_col' => 'date',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getUserErrors',
- 'params' => array(
+ 'params' => [
'le.id_member = {int:current_member}',
- array('current_member' => Profile::$member->id),
- ),
- ),
- 'get_count' => array(
+ ['current_member' => Profile::$member->id],
+ ],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getUserErrorCount',
- 'params' => array(
+ 'params' => [
'id_member = {int:current_member}',
- array('current_member' => Profile::$member->id),
- ),
- ),
- 'columns' => array(
- 'ip_address' => array(
- 'header' => array(
+ ['current_member' => Profile::$member->id],
+ ],
+ ],
+ 'columns' => [
+ 'ip_address' => [
+ 'header' => [
'value' => Lang::$txt['ip_address'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' %1$s',
- 'params' => array(
+ 'params' => [
'ip' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'le.ip',
'reverse' => 'le.ip DESC',
- ),
- ),
- 'message' => array(
- 'header' => array(
+ ],
+ ],
+ 'message' => [
+ 'header' => [
'value' => Lang::$txt['message'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => '%1$s %2$s',
- 'params' => array(
+ 'params' => [
'message' => false,
'url' => false,
- ),
- ),
- ),
- ),
- 'date' => array(
- 'header' => array(
+ ],
+ ],
+ ],
+ ],
+ 'date' => [
+ 'header' => [
'value' => Lang::$txt['date'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'le.id_error DESC',
'reverse' => 'le.id_error',
- ),
- ),
- ),
- 'additional_rows' => array(
- array(
+ ],
+ ],
+ ],
+ 'additional_rows' => [
+ [
'position' => 'after_title',
'value' => Lang::$txt['errors_desc'],
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the list for viewing.
new ItemList($list_options);
// @todo cache this
// If this is a big forum, or a large posting user, let's limit the search.
- if (Config::$modSettings['totalMessages'] > 50000 && Profile::$member->posts > 500)
- {
- $request = Db::$db->query('', '
- SELECT MAX(id_msg)
+ if (Config::$modSettings['totalMessages'] > 50000 && Profile::$member->posts > 500) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT MAX(id_msg)
FROM {db_prefix}messages AS m
WHERE m.id_member = {int:current_member}',
- array(
+ [
'current_member' => Profile::$member->id,
- )
+ ],
);
list($max_msg_member) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -266,30 +280,31 @@ public function activity(): void
}
// Default to at least the ones we know about.
- $ips = array(
+ $ips = [
Profile::$member->ip,
Profile::$member->ip2,
- );
+ ];
// @todo cache this
// Get all IP addresses this user has used for his messages.
- Utils::$context['ips'] = array();
+ Utils::$context['ips'] = [];
- $request = Db::$db->query('', '
- SELECT poster_ip
+ $request = Db::$db->query(
+ '',
+ 'SELECT poster_ip
FROM {db_prefix}messages
WHERE id_member = {int:current_member}
' . (isset($min_msg_member) ? '
AND id_msg >= {int:min_msg_member} AND id_msg <= {int:max_msg_member}' : '') . '
GROUP BY poster_ip',
- array(
+ [
'current_member' => Profile::$member->id,
'min_msg_member' => !empty($min_msg_member) ? $min_msg_member : 0,
'max_msg_member' => !empty($max_msg_member) ? $max_msg_member : 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$row['poster_ip'] = new IP($row['poster_ip']);
Utils::$context['ips'][] = ' ' . $row['poster_ip'] . '';
@@ -299,19 +314,20 @@ public function activity(): void
Db::$db->free_result($request);
// Now also get the IP addresses from the error messages.
- Utils::$context['error_ips'] = array();
+ Utils::$context['error_ips'] = [];
- $request = Db::$db->query('', '
- SELECT COUNT(*) AS error_count, ip
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*) AS error_count, ip
FROM {db_prefix}log_errors
WHERE id_member = {int:current_member}
GROUP BY ip',
- array(
+ [
'current_member' => Profile::$member->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$row['ip'] = new IP($row['ip']);
Utils::$context['error_ips'][] = ' ' . $row['ip'] . '';
@@ -322,60 +338,61 @@ public function activity(): void
// Find other users that might use the same IP.
$ips = array_unique($ips);
- Utils::$context['members_in_range'] = array();
+ Utils::$context['members_in_range'] = [];
- if (!empty($ips))
- {
+ if (!empty($ips)) {
// Get member ID's which are in messages...
- $message_members = array();
- $request = Db::$db->query('', '
- SELECT DISTINCT mem.id_member
+ $message_members = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT DISTINCT mem.id_member
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
WHERE m.poster_ip IN ({array_inet:ip_list})
AND mem.id_member != {int:current_member}',
- array(
+ [
'current_member' => Profile::$member->id,
'ip_list' => $ips,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$message_members[] = $row['id_member'];
}
Db::$db->free_result($request);
// Fetch their names, cause of the GROUP BY doesn't like giving us that normally.
- if (!empty($message_members))
- {
- $request = Db::$db->query('', '
- SELECT id_member, real_name
+ if (!empty($message_members)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name
FROM {db_prefix}members
WHERE id_member IN ({array_int:message_members})',
- array(
+ [
'message_members' => $message_members,
'ip_list' => $ips,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Utils::$context['members_in_range'][$row['id_member']] = ' ' . $row['real_name'] . '';
}
Db::$db->free_result($request);
}
- $request = Db::$db->query('', '
- SELECT id_member, real_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name
FROM {db_prefix}members
WHERE id_member != {int:current_member}
AND member_ip IN ({array_inet:ip_list})',
- array(
+ [
'current_member' => Profile::$member->id,
'ip_list' => $ips,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Utils::$context['members_in_range'][$row['id_member']] = ' ' . $row['real_name'] . '';
}
Db::$db->free_result($request);
@@ -396,86 +413,87 @@ public function ip(): void
public function edits(): void
{
// Get the names of any custom fields.
- Utils::$context['custom_field_titles'] = array();
+ Utils::$context['custom_field_titles'] = [];
- $request = Db::$db->query('', '
- SELECT col_name, field_name, bbc
+ $request = Db::$db->query(
+ '',
+ 'SELECT col_name, field_name, bbc
FROM {db_prefix}custom_fields',
- array(
- )
+ [
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- Utils::$context['custom_field_titles']['customfield_' . $row['col_name']] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ Utils::$context['custom_field_titles']['customfield_' . $row['col_name']] = [
'title' => $row['field_name'],
'parse_bbc' => $row['bbc'],
- );
+ ];
}
Db::$db->free_result($request);
// Set the options for the error lists.
- $list_options = array(
+ $list_options = [
'id' => 'edit_list',
'title' => Lang::$txt['trackEdits'],
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['trackEdit_no_edits'],
'base_href' => Config::$scripturl . '?action=profile;area=tracking;sa=edits;u=' . Profile::$member->id,
'default_sort_col' => 'time',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getProfileEdits',
- 'params' => array(),
- ),
- 'get_count' => array(
+ 'params' => [],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getProfileEditCount',
- 'params' => array(),
- ),
- 'columns' => array(
- 'action' => array(
- 'header' => array(
+ 'params' => [],
+ ],
+ 'columns' => [
+ 'action' => [
+ 'header' => [
'value' => Lang::$txt['trackEdit_action'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'action_text',
- ),
- ),
- 'before' => array(
- 'header' => array(
+ ],
+ ],
+ 'before' => [
+ 'header' => [
'value' => Lang::$txt['trackEdit_before'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'before',
- ),
- ),
- 'after' => array(
- 'header' => array(
+ ],
+ ],
+ 'after' => [
+ 'header' => [
'value' => Lang::$txt['trackEdit_after'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'after',
- ),
- ),
- 'time' => array(
- 'header' => array(
+ ],
+ ],
+ 'time' => [
+ 'header' => [
'value' => Lang::$txt['date'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'id_action DESC',
'reverse' => 'id_action',
- ),
- ),
- 'applicator' => array(
- 'header' => array(
+ ],
+ ],
+ 'applicator' => [
+ 'header' => [
'value' => Lang::$txt['trackEdit_applicator'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'member_link',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
// Create the error list.
new ItemList($list_options);
@@ -490,61 +508,61 @@ public function edits(): void
public function groupRequests(): void
{
// Set the options for the error lists.
- $list_options = array(
+ $list_options = [
'id' => 'request_list',
'title' => sprintf(Lang::$txt['trackGroupRequests_title'], Utils::$context['member']['name']),
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['requested_none'],
'base_href' => Config::$scripturl . '?action=profile;area=tracking;sa=groupreq;u=' . Profile::$member->id,
'default_sort_col' => 'time_applied',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getGroupRequests',
- 'params' => array(),
- ),
- 'get_count' => array(
+ 'params' => [],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getGroupRequestsCount',
- 'params' => array(),
- ),
- 'columns' => array(
- 'group' => array(
- 'header' => array(
+ 'params' => [],
+ ],
+ 'columns' => [
+ 'group' => [
+ 'header' => [
'value' => Lang::$txt['requested_group'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'group_name',
- ),
- ),
- 'group_reason' => array(
- 'header' => array(
+ ],
+ ],
+ 'group_reason' => [
+ 'header' => [
'value' => Lang::$txt['requested_group_reason'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'group_reason',
- ),
- ),
- 'time_applied' => array(
- 'header' => array(
+ ],
+ ],
+ 'time_applied' => [
+ 'header' => [
'value' => Lang::$txt['requested_group_time'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time_applied',
'timeformat' => true,
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'time_applied DESC',
'reverse' => 'time_applied',
- ),
- ),
- 'outcome' => array(
- 'header' => array(
+ ],
+ ],
+ 'outcome' => [
+ 'header' => [
'value' => Lang::$txt['requested_group_outcome'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'outcome',
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ];
// Create the error list.
new ItemList($list_options);
@@ -561,56 +579,56 @@ public function logins(): void
Utils::$context['base_url'] = Config::$scripturl . '?action=profile;area=tracking;sa=ip;u=' . Profile::$member->id;
// Start with the user messages.
- $list_options = array(
+ $list_options = [
'id' => 'track_logins_list',
'title' => Lang::$txt['trackLogins'],
'no_items_label' => Lang::$txt['trackLogins_none_found'],
'base_href' => Utils::$context['base_url'],
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getLogins',
- 'params' => array(
+ 'params' => [
'id_member = {int:current_member}',
- array('current_member' => Profile::$member->id),
- ),
- ),
- 'get_count' => array(
+ ['current_member' => Profile::$member->id],
+ ],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getLoginCount',
- 'params' => array(
+ 'params' => [
'id_member = {int:current_member}',
- array('current_member' => Profile::$member->id),
- ),
- ),
- 'columns' => array(
- 'time' => array(
- 'header' => array(
+ ['current_member' => Profile::$member->id],
+ ],
+ ],
+ 'columns' => [
+ 'time' => [
+ 'header' => [
'value' => Lang::$txt['date'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
- ),
- ),
- 'ip' => array(
- 'header' => array(
+ ],
+ ],
+ 'ip' => [
+ 'header' => [
'value' => Lang::$txt['ip_address'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' %1$s ( %2$s) ',
- 'params' => array(
+ 'params' => [
'ip' => false,
- 'ip2' => false
- ),
- ),
- ),
- ),
- ),
- 'additional_rows' => array(
- array(
+ 'ip2' => false,
+ ],
+ ],
+ ],
+ ],
+ ],
+ 'additional_rows' => [
+ [
'position' => 'after_title',
'value' => Lang::$txt['trackLogins_desc'],
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the messages list.
new ItemList($list_options);
@@ -630,8 +648,9 @@ public function logins(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -654,13 +673,14 @@ public static function call(): void
* @param array $where_vars An array of parameters for $where
* @return array An array of information about the error messages
*/
- public static function list_getUserErrors($start, $items_per_page, $sort, $where, $where_vars = array()): array
+ public static function list_getUserErrors($start, $items_per_page, $sort, $where, $where_vars = []): array
{
// Get a list of error messages from this ip (range).
- $error_messages = array();
+ $error_messages = [];
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
le.log_time, le.ip, le.url, le.message, COALESCE(mem.id_member, 0) AS id_member,
COALESCE(mem.real_name, {string:guest_title}) AS display_name, mem.member_name
FROM {db_prefix}log_errors AS le
@@ -668,23 +688,23 @@ public static function list_getUserErrors($start, $items_per_page, $sort, $where
WHERE ' . $where . '
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array_merge($where_vars, array(
+ array_merge($where_vars, [
'guest_title' => Lang::$txt['guest_title'],
'sort' => $sort,
'start' => $start,
'max' => $items_per_page,
- ))
+ ]),
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $error_messages[] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $error_messages[] = [
'ip' => new IP($row['ip']),
'member_link' => $row['id_member'] > 0 ? ' ' . $row['display_name'] . '' : $row['display_name'],
- 'message' => strtr($row['message'], array('<span class="remove">' => '', '</span>' => '')),
+ 'message' => strtr($row['message'], ['<span class="remove">' => '', '</span>' => '']),
'url' => $row['url'],
'time' => Time::create('@' . $row['log_time'])->format(),
'timestamp' => $row['log_time'],
- );
+ ];
}
Db::$db->free_result($request);
@@ -698,13 +718,14 @@ public static function list_getUserErrors($start, $items_per_page, $sort, $where
* @param array $where_vars The parameters for $where
* @return int Number of user errors
*/
- public static function list_getUserErrorCount($where, $where_vars = array()): int
+ public static function list_getUserErrorCount($where, $where_vars = []): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_errors
WHERE ' . $where,
- $where_vars
+ $where_vars,
);
list($count) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -722,56 +743,52 @@ public static function list_getUserErrorCount($where, $where_vars = array()): in
*/
public static function list_getProfileEdits(int $start, int $items_per_page, string $sort): array
{
- $edits = array();
- $applicators = array();
+ $edits = [];
+ $applicators = [];
// Get a list of error messages from this ip (range).
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
id_action, id_member, ip, log_time, action, extra
FROM {db_prefix}log_actions
WHERE id_log = {int:log_type}
AND id_member = {int:owner}
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array(
+ [
'log_type' => 2,
'owner' => Profile::$member->id,
'sort' => $sort,
'start' => $start,
'max' => $items_per_page,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$extra = Utils::jsonDecode($row['extra'], true);
- if (!empty($extra['applicator']))
+ if (!empty($extra['applicator'])) {
$applicators[] = $extra['applicator'];
+ }
// Work out what the name of the action is.
- if (isset(Lang::$txt['trackEdit_action_' . $row['action']]))
- {
+ if (isset(Lang::$txt['trackEdit_action_' . $row['action']])) {
$action_text = Lang::$txt['trackEdit_action_' . $row['action']];
- }
- elseif (isset(Lang::$txt[$row['action']]))
- {
+ } elseif (isset(Lang::$txt[$row['action']])) {
$action_text = Lang::$txt[$row['action']];
}
// Custom field?
- elseif (isset(Utils::$context['custom_field_titles'][$row['action']]))
- {
+ elseif (isset(Utils::$context['custom_field_titles'][$row['action']])) {
$action_text = Utils::$context['custom_field_titles'][$row['action']]['title'];
- }
- else
- {
+ } else {
$action_text = $row['action'];
}
// Parse BBC?
$parse_bbc = isset(Utils::$context['custom_field_titles'][$row['action']]) && Utils::$context['custom_field_titles'][$row['action']]['parse_bbc'] ? true : false;
- $edits[] = array(
+ $edits[] = [
'id' => $row['id_action'],
'ip' => new IP($row['ip']),
'id_member' => !empty($extra['applicator']) ? $extra['applicator'] : 0,
@@ -781,34 +798,32 @@ public static function list_getProfileEdits(int $start, int $items_per_page, str
'before' => !empty($extra['previous']) ? ($parse_bbc ? BBCodeParser::load()->parse($extra['previous']) : $extra['previous']) : '',
'after' => !empty($extra['new']) ? ($parse_bbc ? BBCodeParser::load()->parse($extra['new']) : $extra['new']) : '',
'time' => Time::create('@' . $row['log_time'])->format(),
- );
+ ];
}
Db::$db->free_result($request);
// Get any member names.
- if (!empty($applicators))
- {
- $members = array();
+ if (!empty($applicators)) {
+ $members = [];
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
id_member, real_name
FROM {db_prefix}members
WHERE id_member IN ({array_int:applicators})',
- array(
+ [
'applicators' => $applicators,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$members[$row['id_member']] = $row['real_name'];
}
Db::$db->free_result($request);
- foreach ($edits as $key => $value)
- {
- if (isset($members[$value['id_member']]))
- {
+ foreach ($edits as $key => $value) {
+ if (isset($members[$value['id_member']])) {
$edits[$key]['member_link'] = ' ' . $members[$value['id_member']] . '';
}
}
@@ -824,15 +839,16 @@ public static function list_getProfileEdits(int $start, int $items_per_page, str
*/
public static function list_getProfileEditCount(): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*) AS edit_count
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*) AS edit_count
FROM {db_prefix}log_actions
WHERE id_log = {int:log_type}
AND id_member = {int:owner}',
- array(
+ [
'log_type' => 2,
'owner' => Profile::$member->id,
- )
+ ],
);
list($edit_count) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -850,10 +866,11 @@ public static function list_getProfileEditCount(): int
*/
public static function list_getGroupRequests(int $start, int $items_per_page, string $sort): array
{
- $groupreq = array();
+ $groupreq = [];
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
lgr.id_group, mg.group_name, mg.online_color, lgr.time_applied, lgr.reason, lgr.status,
ma.id_member AS id_member_acted, COALESCE(ma.member_name, lgr.member_name_acted) AS act_name, lgr.time_acted, lgr.act_reason
FROM {db_prefix}log_group_requests AS lgr
@@ -863,29 +880,31 @@ public static function list_getGroupRequests(int $start, int $items_per_page, st
AND ' . (User::$me->mod_cache['gq'] == '1=1' ? User::$me->mod_cache['gq'] : 'lgr.' . User::$me->mod_cache['gq']) . '
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array(
+ [
'memID' => Profile::$member->id,
'sort' => $sort,
'start' => $start,
'max' => $items_per_page,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $this_req = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $this_req = [
'group_name' => empty($row['online_color']) ? $row['group_name'] : ' ' . $row['group_name'] . '',
'group_reason' => $row['reason'],
'time_applied' => $row['time_applied'],
- );
- switch ($row['status'])
- {
+ ];
+
+ switch ($row['status']) {
case 0:
$this_req['outcome'] = Lang::$txt['outcome_pending'];
break;
+
case 1:
$member_link = empty($row['id_member_acted']) ? $row['act_name'] : ' ' . $row['act_name'] . '';
$this_req['outcome'] = sprintf(Lang::$txt['outcome_approved'], $member_link, Time::create('@' . $row['time_acted'])->format());
break;
+
case 2:
$member_link = empty($row['id_member_acted']) ? $row['act_name'] : ' ' . $row['act_name'] . '';
$this_req['outcome'] = sprintf(!empty($row['act_reason']) ? Lang::$txt['outcome_refused_reason'] : Lang::$txt['outcome_refused'], $member_link, Time::create('@' . $row['time_acted'])->format(), $row['act_reason']);
@@ -906,14 +925,15 @@ public static function list_getGroupRequests(int $start, int $items_per_page, st
*/
public static function list_getGroupRequestsCount(): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*) AS req_count
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*) AS req_count
FROM {db_prefix}log_group_requests AS lgr
WHERE id_member = {int:memID}
AND ' . (User::$me->mod_cache['gq'] == '1=1' ? User::$me->mod_cache['gq'] : 'lgr.' . User::$me->mod_cache['gq']),
- array(
+ [
'memID' => Profile::$member->id,
- )
+ ],
);
list($report_count) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -931,24 +951,27 @@ public static function list_getGroupRequestsCount(): int
* @param array $where_vars An array of parameters for $where. Only 'current_member' (the ID of the member) is used here
* @return array An array of information about user logins
*/
- public static function list_getLogins(int $start, int $items_per_page, string $sort, string $where, array $where_vars = array()): array
+ public static function list_getLogins(int $start, int $items_per_page, string $sort, string $where, array $where_vars = []): array
{
- $request = Db::$db->query('', '
- SELECT time, ip, ip2
+ $request = Db::$db->query(
+ '',
+ 'SELECT time, ip, ip2
FROM {db_prefix}member_logins
WHERE id_member = {int:id_member}
ORDER BY time DESC',
- array(
+ [
'id_member' => $where_vars['current_member'],
- )
+ ],
);
- $logins = array();
- while ($row = Db::$db->fetch_assoc($request))
- $logins[] = array(
+ $logins = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $logins[] = [
'time' => Time::create('@' . $row['time'])->format(),
'ip' => new IP($row['ip']),
'ip2' => new IP($row['ip2']),
- );
+ ];
+ }
Db::$db->free_result($request);
return $logins;
@@ -961,15 +984,16 @@ public static function list_getLogins(int $start, int $items_per_page, string $s
* @param array $where_vars An array of parameters for $where
* @return int count of messages matching the IP
*/
- public static function list_getLoginCount(string $where, array $where_vars = array()): int
+ public static function list_getLoginCount(string $where, array $where_vars = []): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*) AS message_count
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*) AS message_count
FROM {db_prefix}member_logins
WHERE id_member = {int:id_member}',
- array(
+ [
'id_member' => $where_vars['current_member'],
- )
+ ],
);
list($count) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -1058,39 +1082,40 @@ public static function trackLogins(int $memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
// Moderation must be on to track edits.
- if (empty(Config::$modSettings['userlog_enabled']))
+ if (empty(Config::$modSettings['userlog_enabled'])) {
unset(self::$subactions['edits']);
+ }
// Group requests must be active to show it...
- if (empty(Config::$modSettings['show_group_membership']))
+ if (empty(Config::$modSettings['show_group_membership'])) {
unset(self::$subactions['groupreq']);
+ }
// Only show the sub-actions they are allowed to see.
- foreach (self::$subactions as $sa => $action)
- {
- if (!User::$me->allowedTo($action[2]))
+ foreach (self::$subactions as $sa => $action) {
+ if (!User::$me->allowedTo($action[2])) {
unset(self::$subactions[$sa]);
+ }
}
// Now that we've filtered out all the sub-actions they cannot do,
// let them choose from whatever is left.
- if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']]))
- {
+ if (!empty($_REQUEST['sa']) && isset(self::$subactions[$_REQUEST['sa']])) {
$this->subaction = $_REQUEST['sa'];
- }
- elseif (!empty(self::$subactions))
- {
+ } elseif (!empty(self::$subactions)) {
$this->subaction = array_key_first(self::$subactions);
}
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Tracking::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Tracking::exportStatic')) {
Tracking::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/ViewWarning.php b/Sources/Actions/Profile/ViewWarning.php
index 8997d047f3..cc095ab499 100644
--- a/Sources/Actions/Profile/ViewWarning.php
+++ b/Sources/Actions/Profile/ViewWarning.php
@@ -13,9 +13,8 @@
namespace SMF\Actions\Profile;
-use SMF\BackwardCompatibility;
use SMF\Actions\ActionInterface;
-
+use SMF\BackwardCompatibility;
use SMF\Config;
use SMF\ErrorHandler;
use SMF\ItemList;
@@ -36,12 +35,11 @@ class ViewWarning implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'viewWarning' => 'viewWarning',
+ ],
+ ];
/****************************
* Internal static properties
@@ -70,90 +68,89 @@ public function execute(): void
&& !User::$me->allowedTo('view_warning_any')
&& !User::$me->allowedTo('issue_warning')
&& !User::$me->allowedTo('moderate_forum')
- )
- {
+ ) {
ErrorHandler::fatalLang('no_access', false);
}
// Let's use a generic list to get all the current warnings, and use the issue warnings grab-a-granny thing.
- $list_options = array(
+ $list_options = [
'id' => 'view_warnings',
'title' => Lang::$txt['profile_viewwarning_previous_warnings'],
'items_per_page' => Config::$modSettings['defaultMaxListItems'],
'no_items_label' => Lang::$txt['profile_viewwarning_no_warnings'],
'base_href' => Config::$scripturl . '?action=profile;area=viewwarning;sa=user;u=' . Profile::$member->id,
'default_sort_col' => 'log_time',
- 'get_items' => array(
+ 'get_items' => [
'function' => __NAMESPACE__ . '\\IssueWarning::list_getUserWarnings',
- 'params' => array(),
- ),
- 'get_count' => array(
+ 'params' => [],
+ ],
+ 'get_count' => [
'function' => __NAMESPACE__ . '\\IssueWarning::list_getUserWarningCount',
- 'params' => array(),
- ),
- 'columns' => array(
- 'log_time' => array(
- 'header' => array(
+ 'params' => [],
+ ],
+ 'columns' => [
+ 'log_time' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_time'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lc.log_time DESC',
'reverse' => 'lc.log_time',
- ),
- ),
- 'reason' => array(
- 'header' => array(
+ ],
+ ],
+ 'reason' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_reason'],
'style' => 'width: 50%;',
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'reason',
- ),
- ),
- 'level' => array(
- 'header' => array(
+ ],
+ ],
+ 'level' => [
+ 'header' => [
'value' => Lang::$txt['profile_warning_previous_level'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'counter',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'lc.counter DESC',
'reverse' => 'lc.counter',
- ),
- ),
- ),
- 'additional_rows' => array(
- array(
+ ],
+ ],
+ ],
+ 'additional_rows' => [
+ [
'position' => 'after_title',
'value' => Lang::$txt['profile_viewwarning_desc'],
'class' => 'smalltext',
'style' => 'padding: 2ex;',
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the list for viewing.
new ItemList($list_options);
// Create some common text bits for the template.
- Utils::$context['level_effects'] = array(
+ Utils::$context['level_effects'] = [
0 => '',
Config::$modSettings['warning_watch'] => Lang::$txt['profile_warning_effect_own_watched'],
Config::$modSettings['warning_moderate'] => Lang::$txt['profile_warning_effect_own_moderated'],
Config::$modSettings['warning_mute'] => Lang::$txt['profile_warning_effect_own_muted'],
- );
+ ];
// Figure out which warning level this member is at.
Utils::$context['current_level'] = 0;
- foreach (Utils::$context['level_effects'] as $limit => $dummy)
- {
- if (Utils::$context['member']['warning'] >= $limit)
+ foreach (Utils::$context['level_effects'] as $limit => $dummy) {
+ if (Utils::$context['member']['warning'] >= $limit) {
Utils::$context['current_level'] = $limit;
+ }
}
}
@@ -168,8 +165,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;
}
@@ -206,8 +204,9 @@ public static function viewWarning(int $memID): void
*/
protected function __construct()
{
- if (!isset(Profile::$member))
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
// Make sure things which are disabled stay disabled.
Config::$modSettings['warning_watch'] = !empty(Config::$modSettings['warning_watch']) ? Config::$modSettings['warning_watch'] : 110;
@@ -219,7 +218,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ViewWarning::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ViewWarning::exportStatic')) {
ViewWarning::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Profile/index.php b/Sources/Actions/Profile/index.php
new file mode 100644
index 0000000000..976d292448
--- /dev/null
+++ b/Sources/Actions/Profile/index.php
@@ -0,0 +1,9 @@
+
\ No newline at end of file
diff --git a/Sources/Actions/QuickModeration.php b/Sources/Actions/QuickModeration.php
index c20beae2a6..02dd47e69a 100644
--- a/Sources/Actions/QuickModeration.php
+++ b/Sources/Actions/QuickModeration.php
@@ -14,18 +14,15 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\IntegrationHook;
use SMF\Logging;
use SMF\Mail;
-use SMF\Msg;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* Handles moderation from the message index.
@@ -39,13 +36,11 @@ class QuickModeration implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'QuickModeration',
- 'getActions' => false,
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -65,7 +60,7 @@ class QuickModeration implements ActionInterface
* Note: it is better to access this via self::getActions() in case any mods
* have something to add to the list.
*/
- public static array $known_actions = array(
+ public static array $known_actions = [
'approve',
'remove',
'lock',
@@ -74,43 +69,43 @@ class QuickModeration implements ActionInterface
'merge',
'restore',
'markread',
- );
+ ];
/**
* @var array
*
* Permissions need to carry out different actions.
*/
- public static array $action_permissions = array(
- 'markread' => array(
+ public static array $action_permissions = [
+ 'markread' => [
'any' => 'is_not_guest',
- ),
- 'sticky' => array(
+ ],
+ 'sticky' => [
'any' => 'make_sticky',
- ),
- 'lock' => array(
+ ],
+ 'lock' => [
'any' => 'lock_any',
'own' => 'lock_own',
- ),
- 'approve' => array(
+ ],
+ 'approve' => [
'any' => 'approve_posts',
- ),
- 'remove' => array(
+ ],
+ 'remove' => [
'any' => 'remove_any',
'own' => 'remove_own',
- ),
- 'move' => array(
+ ],
+ 'move' => [
'any' => 'move_any',
'own' => 'move_own',
- ),
- 'merge' => array(
+ ],
+ 'merge' => [
'any' => 'merge_any',
- ),
- 'restore' => array(
+ ],
+ 'restore' => [
'any' => 'move_any',
'where' => 'recycle_board',
- ),
- );
+ ],
+ ];
/*********************
* Internal properties
@@ -121,14 +116,14 @@ class QuickModeration implements ActionInterface
*
* Actions that this user is allowed perform on topics.
*/
- protected array $possible_actions = array();
+ protected array $possible_actions = [];
/**
* @var array
*
* Boards where this user can do different actions.
*/
- protected array $boards_can = array();
+ protected array $boards_can = [];
/**
* @var string
@@ -157,19 +152,19 @@ class QuickModeration implements ActionInterface
* sub-array contains info about the board that each topic should be
* moved to.
*/
- protected array $topic_actions = array(
- 'markread' => array(),
- 'sticky' => array(),
- 'lock' => array(),
- 'approve' => array(),
- 'remove' => array(),
- 'move' => array(
- 'topics' => array(),
- 'to' => array(),
- ),
- 'merge' => array(),
- 'restore' => array(),
- );
+ protected array $topic_actions = [
+ 'markread' => [],
+ 'sticky' => [],
+ 'lock' => [],
+ 'approve' => [],
+ 'remove' => [],
+ 'move' => [
+ 'topics' => [],
+ 'to' => [],
+ ],
+ 'merge' => [],
+ 'restore' => [],
+ ];
/****************************
* Internal static properties
@@ -196,8 +191,9 @@ public function execute(): void
User::$me->checkSession('request');
// This won't be valid anymore.
- if (isset($_SESSION['topicseen_cache']))
- $_SESSION['topicseen_cache'] = array();
+ if (isset($_SESSION['topicseen_cache'])) {
+ $_SESSION['topicseen_cache'] = [];
+ }
// Which actions can this user perform?
$this->setPossibleActions();
@@ -218,12 +214,13 @@ public function execute(): void
// Update stats and such.
Logging::updateStats('topic');
Logging::updateStats('message');
- Config::updateModSettings(array(
+ Config::updateModSettings([
'calendar_updated' => time(),
- ));
+ ]);
- if ($this->should_redirect)
+ if ($this->should_redirect) {
Utils::redirectexit($this->redirect_url);
+ }
}
/***********************
@@ -237,8 +234,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;
}
@@ -265,16 +263,13 @@ public static function getActions(bool $search = false): array
{
Utils::$context['qmod_actions'] = &self::$known_actions;
- if ($search)
- {
+ if ($search) {
// Approve isn't applicable when viewing search results.
- self::$known_actions = array_diff(self::$known_actions, array('approve'));
+ self::$known_actions = array_diff(self::$known_actions, ['approve']);
- IntegrationHook::call('integrate_quick_mod_actions_search', array(self::$known_actions));
- }
- else
- {
- IntegrationHook::call('integrate_quick_mod_actions', array(self::$known_actions));
+ IntegrationHook::call('integrate_quick_mod_actions_search', [self::$known_actions]);
+ } else {
+ IntegrationHook::call('integrate_quick_mod_actions', [self::$known_actions]);
}
return self::$known_actions;
@@ -296,8 +291,9 @@ protected function __construct()
$this->topic_actions = array_intersect_key($this->topic_actions, array_flip(self::$known_actions));
// Add any custom actions to topic_actions.
- foreach (self::$known_actions as $action)
- $this->topic_actions[$action] = array();
+ foreach (self::$known_actions as $action) {
+ $this->topic_actions[$action] = [];
+ }
$this->setRequestActions();
}
@@ -322,20 +318,22 @@ protected function __construct()
*/
protected function setRequestActions(): void
{
- if (!empty($_REQUEST['topics']))
- {
+ if (!empty($_REQUEST['topics'])) {
// If the action isn't valid, just quit now.
- if (empty($_REQUEST['qaction']) || !isset($this->topic_actions[$_REQUEST['qaction']]))
+ if (empty($_REQUEST['qaction']) || !isset($this->topic_actions[$_REQUEST['qaction']])) {
Utils::redirectexit($this->redirect_url);
+ }
// Just convert to the other method, to make it easier.
- foreach ($_REQUEST['topics'] as $topic)
+ foreach ($_REQUEST['topics'] as $topic) {
$_REQUEST['actions'][(int) $topic] = $_REQUEST['qaction'];
+ }
}
// Weird... how'd you get here?
- if (empty($_REQUEST['actions']))
+ if (empty($_REQUEST['actions'])) {
Utils::redirectexit($this->redirect_url);
+ }
}
/**
@@ -347,69 +345,61 @@ protected function setRequestActions(): void
protected function setPossibleActions(): void
{
// Which permissions do we need to check?
- $permissions_to_check = array();
- foreach (self::$action_permissions as $action => $permissions)
- {
+ $permissions_to_check = [];
+
+ foreach (self::$action_permissions as $action => $permissions) {
// Skip permissions for actions that weren't requested.
// Exception: always check the approval permission.
- if (!in_array($action, $_REQUEST['actions']) && $action !== 'approve')
+ if (!in_array($action, $_REQUEST['actions']) && $action !== 'approve') {
continue;
+ }
// If the permission specifies a particular board, only proceed
// if we are in that board.
- if (!empty($permissions['where']))
- {
+ if (!empty($permissions['where'])) {
// The 'where' can be a $modSettings key or a raw board ID.
- if (!is_numeric($permissions['where']))
+ if (!is_numeric($permissions['where'])) {
$permissions['where'] = Config::$modSettings[$permissions['where']] ?? null;
+ }
// Can't do it if not in the required board.
- if (!empty($permissions['where']) && !empty(Board::$info->id) && Board::$info->id != $permissions['where'])
+ if (!empty($permissions['where']) && !empty(Board::$info->id) && Board::$info->id != $permissions['where']) {
continue;
+ }
}
$permissions_to_check = array_unique(array_merge($permissions_to_check, array_values($permissions)));
}
- if (!empty(Board::$info->id))
- {
- foreach ($permissions_to_check as $permission)
- {
- $this->boards_can[$permission] = User::$me->allowedTo($permission) ? array(Board::$info->id) : array();
+ if (!empty(Board::$info->id)) {
+ foreach ($permissions_to_check as $permission) {
+ $this->boards_can[$permission] = User::$me->allowedTo($permission) ? [Board::$info->id] : [];
}
$this->redirect_url = 'board=' . Board::$info->id . '.' . $_REQUEST['start'];
- }
- else
- {
+ } else {
$this->boards_can = User::$me->boardsAllowedTo($permissions_to_check, true, false);
- $this->redirect_url = isset($_POST['redirect_url']) ? $_POST['redirect_url'] : (isset($_SESSION['old_url']) ? $_SESSION['old_url'] : '');
+ $this->redirect_url = $_POST['redirect_url'] ?? ($_SESSION['old_url'] ?? '');
}
// Are we enforcing the "no moving topics to boards where you can't post new ones" rule?
- if (!User::$me->is_admin && !Config::$modSettings['topic_move_any'])
- {
+ if (!User::$me->is_admin && !Config::$modSettings['topic_move_any']) {
// Don't count this board, if it's specified
- if (!empty(Board::$info->id))
- {
- $this->boards_can['post_new'] = array_diff(User::$me->boardsAllowedTo('post_new'), array(Board::$info->id));
- }
- else
- {
+ if (!empty(Board::$info->id)) {
+ $this->boards_can['post_new'] = array_diff(User::$me->boardsAllowedTo('post_new'), [Board::$info->id]);
+ } else {
$this->boards_can['post_new'] = User::$me->boardsAllowedTo('post_new');
}
- if (empty($this->boards_can['post_new']))
- $this->boards_can['move_any'] = $this->boards_can['move_own'] = array();
+ if (empty($this->boards_can['post_new'])) {
+ $this->boards_can['move_any'] = $this->boards_can['move_own'] = [];
+ }
}
- foreach (self::$action_permissions as $action => $permissions)
- {
- foreach (array('any', 'own') as $scope)
- {
- if (isset($permissions[$scope]) && !empty($this->boards_can[$permissions[$scope]]))
- {
+ foreach (self::$action_permissions as $action => $permissions) {
+ foreach (['any', 'own'] as $scope) {
+ if (isset($permissions[$scope]) && !empty($this->boards_can[$permissions[$scope]])) {
$this->possible_actions[] = $action;
break;
}
@@ -423,102 +413,106 @@ protected function setPossibleActions(): void
protected function setTopicActions(): void
{
// Validate each action.
- $temp = array();
- foreach ($_REQUEST['actions'] as $topic => $action)
- {
- if (in_array($action, $this->possible_actions))
+ $temp = [];
+
+ foreach ($_REQUEST['actions'] as $topic => $action) {
+ if (in_array($action, $this->possible_actions)) {
$temp[(int) $topic] = $action;
+ }
}
$_REQUEST['actions'] = $temp;
- if (!empty($_REQUEST['actions']))
- {
+ if (!empty($_REQUEST['actions'])) {
// Find all topics...
- $request = Db::$db->query('', '
- SELECT id_topic, id_member_started, id_board, locked, approved, unapproved_posts
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic, id_member_started, id_board, locked, approved, unapproved_posts
FROM {db_prefix}topics
WHERE id_topic IN ({array_int:action_topic_ids})
LIMIT {int:limit}',
- array(
+ [
'action_topic_ids' => array_keys($_REQUEST['actions']),
'limit' => count($_REQUEST['actions']),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Can't act on topics that aren't in this board.
- if (!empty(Board::$info->id) && $row['id_board'] != Board::$info->id)
- {
+ if (!empty(Board::$info->id) && $row['id_board'] != Board::$info->id) {
unset($_REQUEST['actions'][$row['id_topic']]);
+
continue;
}
// Can't act on topics that they can't see...
- if (Config::$modSettings['postmod_active'] && !$row['approved'] && array_intersect(array(0, $row['id_board']), $this->boards_can['approve_posts']) === array())
- {
+ if (Config::$modSettings['postmod_active'] && !$row['approved'] && array_intersect([0, $row['id_board']], $this->boards_can['approve_posts']) === []) {
unset($_REQUEST['actions'][$row['id_topic']]);
+
continue;
}
- foreach (self::$action_permissions as $action => $permissions)
- {
- if ($action !== $_REQUEST['actions'][$row['id_topic']])
+ foreach (self::$action_permissions as $action => $permissions) {
+ if ($action !== $_REQUEST['actions'][$row['id_topic']]) {
continue;
+ }
- $boards_can_any = isset($permissions['any']) ? array_intersect(array(0, $row['id_board']), $this->boards_can[$permissions['any']]) : array();
+ $boards_can_any = isset($permissions['any']) ? array_intersect([0, $row['id_board']], $this->boards_can[$permissions['any']]) : [];
- $boards_can_own = isset($permissions['own']) ? array_intersect(array(0, $row['id_board']), $this->boards_can[$permissions['own']]) : array();
+ $boards_can_own = isset($permissions['own']) ? array_intersect([0, $row['id_board']], $this->boards_can[$permissions['own']]) : [];
$own_topic = $row['id_member_started'] == User::$me->id;
// If locked by a moderator, non-moderators cannot unlock.
$mod_locked = $action === 'lock' && $row['locked'] == 1;
- if (empty($boards_can_any) && (!$own_topic || empty($boards_can_own) || $mod_locked))
+ if (empty($boards_can_any) && (!$own_topic || empty($boards_can_own) || $mod_locked)) {
unset($_REQUEST['actions'][$row['id_topic']]);
+ }
// Don't bother approving if there are no unapproved posts.
- if ($action === 'approve' && empty($row['unapproved_posts']))
+ if ($action === 'approve' && empty($row['unapproved_posts'])) {
unset($_REQUEST['actions'][$row['id_topic']]);
+ }
}
}
Db::$db->free_result($request);
}
// Separate the actions.
- foreach ($_REQUEST['actions'] as $topic => $action)
- {
+ foreach ($_REQUEST['actions'] as $topic => $action) {
$topic = (int) $topic;
- switch ($action)
- {
+ switch ($action) {
case 'move':
TopicMove2::moveTopicConcurrence();
// If action is 'move', $_REQUEST['move_to'] or $_REQUEST['move_tos'][$topic] is used.
- $this->topic_actions['move']['to'][$topic] = (int) (isset($_REQUEST['move_tos'][$topic]) ? $_REQUEST['move_tos'][$topic] : $_REQUEST['move_to']);
+ $this->topic_actions['move']['to'][$topic] = (int) ($_REQUEST['move_tos'][$topic] ?? $_REQUEST['move_to']);
- if (empty($this->topic_actions['move']['to'][$topic]))
+ if (empty($this->topic_actions['move']['to'][$topic])) {
break;
+ }
// Never move topics to redirect boards
- $redirect_boards = array();
- $request = Db::$db->query('', '
- SELECT id_board
+ $redirect_boards = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board
FROM {db_prefix}boards
WHERE redirect != {string:blank_redirect}',
- array(
+ [
'blank_redirect' => '',
- )
+ ],
);
- while ($row = Db::$db->fetch_row($request))
- {
+
+ while ($row = Db::$db->fetch_row($request)) {
$redirect_boards[] = $row[0];
}
Db::$db->free_result($request);
- if (in_array($this->topic_actions['move']['to'][$topic], $redirect_boards))
+ if (in_array($this->topic_actions['move']['to'][$topic], $redirect_boards)) {
break;
+ }
$this->topic_actions['move']['topics'][] = $topic;
break;
@@ -535,38 +529,41 @@ protected function setTopicActions(): void
*/
protected function doMarkRead(): void
{
- if (empty($this->topic_actions['markread']))
+ if (empty($this->topic_actions['markread'])) {
return;
+ }
- $logged_topics = array();
+ $logged_topics = [];
- $request = Db::$db->query('', '
- SELECT id_topic, unwatched
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic, unwatched
FROM {db_prefix}log_topics
WHERE id_topic IN ({array_int:selected_topics})
AND id_member = {int:current_user}',
- array(
+ [
'selected_topics' => $this->topic_actions['markread'],
'current_user' => User::$me->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$logged_topics[$row['id_topic']] = $row['unwatched'];
}
Db::$db->free_result($request);
- $markreadArray = array();
- foreach ($this->topic_actions['markread'] as $topic)
- {
- $markreadArray[] = array(Config::$modSettings['maxMsgID'], User::$me->id, $topic, (isset($logged_topics[$topic]) ? $logged_topics[$topic] : 0));
+ $markreadArray = [];
+
+ foreach ($this->topic_actions['markread'] as $topic) {
+ $markreadArray[] = [Config::$modSettings['maxMsgID'], User::$me->id, $topic, ($logged_topics[$topic] ?? 0)];
}
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_topics',
- array('id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int', 'unwatched' => 'int'),
+ ['id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int', 'unwatched' => 'int'],
$markreadArray,
- array('id_member', 'id_topic')
+ ['id_member', 'id_topic'],
);
}
@@ -575,43 +572,45 @@ protected function doMarkRead(): void
*/
protected function doSticky(): void
{
- if (empty($this->topic_actions['sticky']))
+ if (empty($this->topic_actions['sticky'])) {
return;
+ }
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET is_sticky = CASE WHEN is_sticky = {int:is_sticky} THEN 0 ELSE 1 END
WHERE id_topic IN ({array_int:sticky_topic_ids})',
- array(
+ [
'sticky_topic_ids' => $this->topic_actions['sticky'],
'is_sticky' => 1,
- )
+ ],
);
// Get the board IDs and Sticky status
- $sticky_cache_boards = array();
- $sticky_cache_status = array();
+ $sticky_cache_boards = [];
+ $sticky_cache_status = [];
- $request = Db::$db->query('', '
- SELECT id_topic, id_board, is_sticky
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic, id_board, is_sticky
FROM {db_prefix}topics
WHERE id_topic IN ({array_int:sticky_topic_ids})
LIMIT {int:limit}',
- array(
+ [
'sticky_topic_ids' => $this->topic_actions['sticky'],
'limit' => count($this->topic_actions['sticky']),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$sticky_cache_boards[$row['id_topic']] = $row['id_board'];
$sticky_cache_status[$row['id_topic']] = empty($row['is_sticky']);
}
Db::$db->free_result($request);
- foreach ($this->topic_actions['sticky'] as $topic)
- {
- Logging::logAction($sticky_cache_status[$topic] ? 'unsticky' : 'sticky', array('topic' => $topic, 'board' => $sticky_cache_boards[$topic]));
+ foreach ($this->topic_actions['sticky'] as $topic) {
+ Logging::logAction($sticky_cache_status[$topic] ? 'unsticky' : 'sticky', ['topic' => $topic, 'board' => $sticky_cache_boards[$topic]]);
Mail::sendNotifications($topic, 'sticky');
}
@@ -622,33 +621,34 @@ protected function doSticky(): void
*/
protected function doLock(): void
{
- if (empty($this->topic_actions['lock']))
+ if (empty($this->topic_actions['lock'])) {
return;
+ }
- $lock_status = array();
+ $lock_status = [];
// Gotta make sure they CAN lock/unlock these topics...
- if (!empty(Board::$info->id) && !User::$me->allowedTo('lock_any'))
- {
+ if (!empty(Board::$info->id) && !User::$me->allowedTo('lock_any')) {
// Make sure they started the topic AND it isn't already locked by someone with higher priv's.
- $locked_topic_ids = array();
- $lock_cache_boards = array();
+ $locked_topic_ids = [];
+ $lock_cache_boards = [];
- $result = Db::$db->query('', '
- SELECT id_topic, locked, id_board
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_topic, locked, id_board
FROM {db_prefix}topics
WHERE id_topic IN ({array_int:locked_topic_ids})
AND id_member_started = {int:current_member}
AND locked IN (2, 0)
LIMIT {int:limit}',
- array(
+ [
'current_member' => User::$me->id,
'locked_topic_ids' => $this->topic_actions['lock'],
'limit' => count($locked_topic_ids),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$locked_topic_ids[] = $row['id_topic'];
$lock_cache_boards[$row['id_topic']] = $row['id_board'];
$lock_status[$row['id_topic']] = empty($row['locked']);
@@ -656,23 +656,22 @@ protected function doLock(): void
Db::$db->free_result($result);
$this->topic_actions['lock'] = $locked_topic_ids;
- }
- else
- {
- $lock_cache_boards = array();
+ } else {
+ $lock_cache_boards = [];
- $result = Db::$db->query('', '
- SELECT id_topic, locked, id_board
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_topic, locked, id_board
FROM {db_prefix}topics
WHERE id_topic IN ({array_int:locked_topic_ids})
LIMIT {int:limit}',
- array(
+ [
'locked_topic_ids' => $this->topic_actions['lock'],
- 'limit' => count($this->topic_actions['lock'])
- )
+ 'limit' => count($this->topic_actions['lock']),
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$lock_status[$row['id_topic']] = empty($row['locked']);
$lock_cache_boards[$row['id_topic']] = $row['id_board'];
}
@@ -680,23 +679,22 @@ protected function doLock(): void
}
// It could just be that *none* were their own topics...
- if (!empty($this->topic_actions['lock']))
- {
+ if (!empty($this->topic_actions['lock'])) {
// Alternate the locked value.
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET locked = CASE WHEN locked = {int:is_locked} THEN ' . (User::$me->allowedTo('lock_any') ? '1' : '2') . ' ELSE 0 END
WHERE id_topic IN ({array_int:locked_topic_ids})',
- array(
+ [
'locked_topic_ids' => $this->topic_actions['lock'],
'is_locked' => 0,
- )
+ ],
);
}
- foreach ($this->topic_actions['lock'] as $topic)
- {
- Logging::logAction($lock_status[$topic] ? 'lock' : 'unlock', array('topic' => $topic, 'board' => $lock_cache_boards[$topic]));
+ foreach ($this->topic_actions['lock'] as $topic) {
+ Logging::logAction($lock_status[$topic] ? 'lock' : 'unlock', ['topic' => $topic, 'board' => $lock_cache_boards[$topic]]);
Mail::sendNotifications($topic, $lock_status[$topic] ? 'lock' : 'unlock');
}
@@ -711,79 +709,82 @@ protected function doLock(): void
protected function doMove(): void
{
// Remember the last board they moved things to.
- if (isset($_REQUEST['move_to']))
+ if (isset($_REQUEST['move_to'])) {
$_SESSION['move_to_topic'] = $_REQUEST['move_to'];
+ }
- if (empty($this->topic_actions['move']['topics']))
+ if (empty($this->topic_actions['move']['topics'])) {
return;
+ }
// I know - I just KNOW you're trying to beat the system. Too bad for you... we CHECK :P.
- $moveTos = array();
- $moveCache2 = array();
- $countPosts = array();
+ $moveTos = [];
+ $moveCache2 = [];
+ $countPosts = [];
- $request = Db::$db->query('', '
- SELECT t.id_topic, t.id_board, b.count_posts
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_topic, t.id_board, b.count_posts
FROM {db_prefix}topics AS t
LEFT JOIN {db_prefix}boards AS b ON (t.id_board = b.id_board)
WHERE t.id_topic IN ({array_int:move_topic_ids})' . (!empty(Board::$info->id) && !User::$me->allowedTo('move_any') ? '
AND t.id_member_started = {int:current_member}' : '') . '
LIMIT {int:limit}',
- array(
+ [
'current_member' => User::$me->id,
'move_topic_ids' => $this->topic_actions['move']['topics'],
- 'limit' => count($this->topic_actions['move']['topics'])
- )
+ 'limit' => count($this->topic_actions['move']['topics']),
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$to = $this->topic_actions['move']['to'][$row['id_topic']];
- if (empty($to))
+ if (empty($to)) {
continue;
+ }
// Does this topic's board count the posts or not?
$countPosts[$row['id_topic']] = empty($row['count_posts']);
- if (!isset($moveTos[$to]))
- $moveTos[$to] = array();
+ if (!isset($moveTos[$to])) {
+ $moveTos[$to] = [];
+ }
$moveTos[$to][] = $row['id_topic'];
// For reporting...
- $moveCache2[] = array($row['id_topic'], $row['id_board'], $to);
+ $moveCache2[] = [$row['id_topic'], $row['id_board'], $to];
}
Db::$db->free_result($request);
$this->topic_actions['move'] = $moveCache2;
// Do the actual moves...
- foreach ($moveTos as $to => $topics)
+ foreach ($moveTos as $to => $topics) {
Topic::move($topics, $to);
+ }
// Does the post counts need to be updated?
- if (!empty($moveTos))
- {
- $topicRecounts = array();
- $request = Db::$db->query('', '
- SELECT id_board, count_posts
+ if (!empty($moveTos)) {
+ $topicRecounts = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board, count_posts
FROM {db_prefix}boards
WHERE id_board IN ({array_int:move_boards})',
- array(
+ [
'move_boards' => array_keys($moveTos),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+ while ($row = Db::$db->fetch_assoc($request)) {
$cp = empty($row['count_posts']);
// Go through all the topics that are being moved to this board.
- foreach ($moveTos[$row['id_board']] as $topic)
- {
+ foreach ($moveTos[$row['id_board']] as $topic) {
// If both boards have the same value for post counting then no adjustment needs to be made.
- if ($countPosts[$topic] != $cp)
- {
+ if ($countPosts[$topic] != $cp) {
// If the board being moved to does count the posts then the other one doesn't so add to their post count.
$topicRecounts[$topic] = $cp ? '+' : '-';
}
@@ -792,30 +793,28 @@ protected function doMove(): void
Db::$db->free_result($request);
- if (!empty($topicRecounts))
- {
- $members = array();
+ if (!empty($topicRecounts)) {
+ $members = [];
// Get all the members who have posted in the moved topics.
- $request = Db::$db->query('', '
- SELECT id_member, id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, id_topic
FROM {db_prefix}messages
WHERE id_topic IN ({array_int:moved_topic_ids})',
- array(
+ [
'moved_topic_ids' => array_keys($topicRecounts),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (!isset($members[$row['id_member']]))
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (!isset($members[$row['id_member']])) {
$members[$row['id_member']] = 0;
+ }
- if ($topicRecounts[$row['id_topic']] === '+')
- {
+ if ($topicRecounts[$row['id_topic']] === '+') {
$members[$row['id_member']]++;
- }
- else
- {
+ } else {
$members[$row['id_member']]--;
}
@@ -824,18 +823,19 @@ protected function doMove(): void
Db::$db->free_result($request);
// And now update them member's post counts
- foreach ($members as $id_member => $post_adj)
- User::updateMemberData($id_member, array('posts' => 'posts + ' . $post_adj));
+ foreach ($members as $id_member => $post_adj) {
+ User::updateMemberData($id_member, ['posts' => 'posts + ' . $post_adj]);
+ }
}
}
- foreach ($this->topic_actions['move'] as $topic)
- {
+ foreach ($this->topic_actions['move'] as $topic) {
// Didn't actually move anything!
- if (!isset($topic[0]))
+ if (!isset($topic[0])) {
break;
+ }
- Logging::logAction('move', array('topic' => $topic[0], 'board_from' => $topic[1], 'board_to' => $topic[2]));
+ Logging::logAction('move', ['topic' => $topic[0], 'board_from' => $topic[1], 'board_to' => $topic[2]]);
Mail::sendNotifications($topic[0], 'move');
}
@@ -849,27 +849,29 @@ protected function doMove(): void
*/
protected function doRemove(): void
{
- if (empty($this->topic_actions['remove']))
+ if (empty($this->topic_actions['remove'])) {
return;
+ }
// They can only delete their own topics. (we wouldn't be here if they couldn't do that..)
- $removed_topic_ids = array();
- $remove_cache_boards = array();
+ $removed_topic_ids = [];
+ $remove_cache_boards = [];
- $result = Db::$db->query('', '
- SELECT id_topic, id_board
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_topic, id_board
FROM {db_prefix}topics
WHERE id_topic IN ({array_int:removed_topic_ids})' . (!empty(Board::$info->id) && !User::$me->allowedTo('remove_any') ? '
AND id_member_started = {int:current_member}' : '') . '
LIMIT {int:limit}',
- array(
+ [
'current_member' => User::$me->id,
'removed_topic_ids' => $this->topic_actions['remove'],
'limit' => count($this->topic_actions['remove']),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$removed_topic_ids[] = $row['id_topic'];
$remove_cache_boards[$row['id_topic']] = $row['id_board'];
}
@@ -878,13 +880,11 @@ protected function doRemove(): void
$this->topic_actions['remove'] = $removed_topic_ids;
// Maybe *none* were their own topics.
- if (!empty($this->topic_actions['remove']))
- {
+ if (!empty($this->topic_actions['remove'])) {
// Gotta send the notifications *first*!
- foreach ($this->topic_actions['remove'] as $topic)
- {
+ foreach ($this->topic_actions['remove'] as $topic) {
// Only log the topic ID if it's not in the recycle board.
- Logging::logAction('remove', array((empty(Config::$modSettings['recycle_enable']) || Config::$modSettings['recycle_board'] != $remove_cache_boards[$topic] ? 'topic' : 'old_topic_id') => $topic, 'board' => $remove_cache_boards[$topic]));
+ Logging::logAction('remove', [(empty(Config::$modSettings['recycle_enable']) || Config::$modSettings['recycle_board'] != $remove_cache_boards[$topic] ? 'topic' : 'old_topic_id') => $topic, 'board' => $remove_cache_boards[$topic]]);
Mail::sendNotifications($topic, 'remove');
}
@@ -901,27 +901,29 @@ protected function doRemove(): void
*/
protected function doApprove(): void
{
- if (empty($this->topic_actions['approve']))
+ if (empty($this->topic_actions['approve'])) {
return;
+ }
// We need unapproved topic ids and their authors!
- $approve_topic_ids = array();
- $approve_cache_members = array();
+ $approve_topic_ids = [];
+ $approve_cache_members = [];
- $request = Db::$db->query('', '
- SELECT id_topic, id_member_started
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic, id_member_started
FROM {db_prefix}topics
WHERE id_topic IN ({array_int:approve_topic_ids})
AND approved = {int:not_approved}
LIMIT {int:limit}',
- array(
+ [
'approve_topic_ids' => $this->topic_actions['approve'],
'not_approved' => 0,
'limit' => count($this->topic_actions['approve']),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$approve_topic_ids[] = $row['id_topic'];
$approve_cache_members[$row['id_topic']] = $row['id_member_started'];
}
@@ -930,15 +932,13 @@ protected function doApprove(): void
$this->topic_actions['approve'] = $approve_topic_ids;
// Any topics to approve?
- if (!empty($this->topic_actions['approve']))
- {
+ if (!empty($this->topic_actions['approve'])) {
// Handle the approval part...
Topic::approve($this->topic_actions['approve']);
// Time for some logging!
- foreach ($this->topic_actions['approve'] as $topic)
- {
- Logging::logAction('approve_topic', array('topic' => $topic, 'member' => $approve_cache_members[$topic]));
+ foreach ($this->topic_actions['approve'] as $topic) {
+ Logging::logAction('approve_topic', ['topic' => $topic, 'member' => $approve_cache_members[$topic]]);
}
}
}
@@ -952,8 +952,9 @@ protected function doApprove(): void
protected function doMerge(): void
{
// Merge requires at least two topics.
- if (count($this->topic_actions['merge']) < 2)
+ if (count($this->topic_actions['merge']) < 2) {
return;
+ }
TopicMerge::initiate($this->topic_actions['merge']);
@@ -969,15 +970,17 @@ protected function doMerge(): void
protected function doRestore(): void
{
// Merge requires at least two topics.
- if (empty($this->topic_actions['restore']))
+ if (empty($this->topic_actions['restore'])) {
return;
+ }
Utils::redirectexit('action=restoretopic;topics=' . implode(',', $this->topic_actions['restore']) . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id']);
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\QuickModeration::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\QuickModeration::exportStatic')) {
QuickModeration::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/QuickModerationInTopic.php b/Sources/Actions/QuickModerationInTopic.php
index 6f659329c1..b38d36e666 100644
--- a/Sources/Actions/QuickModerationInTopic.php
+++ b/Sources/Actions/QuickModerationInTopic.php
@@ -14,15 +14,14 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\Logging;
use SMF\Msg;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Handles quick moderation actions from within a topic.
@@ -39,12 +38,11 @@ class QuickModerationInTopic implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'QuickInTopicModeration',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -55,7 +53,7 @@ class QuickModerationInTopic implements ActionInterface
*
* IDs of the messages to act on.
*/
- public array $messages = array();
+ public array $messages = [];
/****************************
* Internal static properties
@@ -81,12 +79,13 @@ public function execute(): void
// Check the session = get or post.
User::$me->checkSession('request');
- if (isset($_REQUEST['restore_selected']))
+ if (isset($_REQUEST['restore_selected'])) {
$this->restore();
- elseif (isset($_REQUEST['split_selection']))
+ } elseif (isset($_REQUEST['split_selection'])) {
$this->split();
- else
+ } else {
$this->delete();
+ }
}
/***********************
@@ -100,8 +99,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;
}
@@ -139,14 +139,15 @@ protected function restore()
*/
protected function split()
{
- $request = Db::$db->query('', '
- SELECT subject
+ $request = Db::$db->query(
+ '',
+ 'SELECT subject
FROM {db_prefix}messages
WHERE id_msg = {int:message}
LIMIT 1',
- array(
+ [
'message' => min($this->messages),
- )
+ ],
);
list($subname) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -164,92 +165,92 @@ protected function split()
protected function delete()
{
// Allowed to delete any message?
- if (User::$me->allowedTo('delete_any'))
- {
+ if (User::$me->allowedTo('delete_any')) {
$allowed_all = true;
}
// Allowed to delete replies to their messages?
- elseif (User::$me->allowedTo('delete_replies'))
- {
- $request = Db::$db->query('', '
- SELECT id_member_started
+ elseif (User::$me->allowedTo('delete_replies')) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member_started
FROM {db_prefix}topics
WHERE id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
- )
+ ],
);
- list ($starter) = Db::$db->fetch_row($request);
+ list($starter) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
$allowed_all = $starter == User::$me->id;
- }
- else
+ } else {
$allowed_all = false;
+ }
// Make sure they're allowed to delete their own messages, if not any.
- if (!$allowed_all)
+ if (!$allowed_all) {
User::$me->isAllowedTo('delete_own');
+ }
// Allowed to remove which messages?
- $request = Db::$db->query('', '
- SELECT id_msg, subject, id_member, poster_time
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_msg, subject, id_member, poster_time
FROM {db_prefix}messages
WHERE id_msg IN ({array_int:message_list})
AND id_topic = {int:current_topic}' . (!$allowed_all ? '
AND id_member = {int:current_member}' : '') . '
LIMIT {int:limit}',
- array(
+ [
'current_member' => User::$me->id,
'current_topic' => Topic::$topic_id,
'message_list' => $this->messages,
'limit' => count($this->messages),
- )
+ ],
);
- $message_info = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (!$allowed_all && !empty(Config::$modSettings['edit_disable_time']) && $row['poster_time'] + Config::$modSettings['edit_disable_time'] * 60 < time())
+ $message_info = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (!$allowed_all && !empty(Config::$modSettings['edit_disable_time']) && $row['poster_time'] + Config::$modSettings['edit_disable_time'] * 60 < time()) {
continue;
+ }
- $message_info[$row['id_msg']] = array($row['subject'], $row['id_member']);
+ $message_info[$row['id_msg']] = [$row['subject'], $row['id_member']];
}
Db::$db->free_result($request);
// Get the first message in the topic - because you can't delete that!
- $request = Db::$db->query('', '
- SELECT id_first_msg, id_last_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_first_msg, id_last_msg
FROM {db_prefix}topics
WHERE id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
- )
+ ],
);
- list ($first_message, $last_message) = Db::$db->fetch_row($request);
+ list($first_message, $last_message) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Delete all the messages we know they can delete. ($message_info)
- foreach ($message_info as $message => $info)
- {
+ foreach ($message_info as $message => $info) {
// Just skip the first message - if it's not the last.
- if ($message == $first_message && $message != $last_message)
- {
+ if ($message == $first_message && $message != $last_message) {
continue;
}
+
// If the first message is going then don't bother going back to the topic as we're effectively deleting it.
- elseif ($message == $first_message)
- {
+ if ($message == $first_message) {
$topicGone = true;
}
Msg::remove($message);
// Log this moderation action ;).
- if (User::$me->allowedTo('delete_any') && (!User::$me->allowedTo('delete_own') || $info[1] != User::$me->id))
- {
- Logging::logAction('delete', array('topic' => Topic::$topic_id, 'subject' => $info[0], 'member' => $info[1], 'board' => Board::$info->id));
+ if (User::$me->allowedTo('delete_any') && (!User::$me->allowedTo('delete_own') || $info[1] != User::$me->id)) {
+ Logging::logAction('delete', ['topic' => Topic::$topic_id, 'subject' => $info[0], 'member' => $info[1], 'board' => Board::$info->id]);
}
}
@@ -258,7 +259,8 @@ protected function delete()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\QuickModerationInTopic::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\QuickModerationInTopic::exportStatic')) {
QuickModerationInTopic::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/QuoteFast.php b/Sources/Actions/QuoteFast.php
index 7c2503048b..16df05b605 100644
--- a/Sources/Actions/QuoteFast.php
+++ b/Sources/Actions/QuoteFast.php
@@ -14,15 +14,13 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\Lang;
use SMF\Msg;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
-
/**
* This class handles quoting posts via JavaScript.
@@ -42,12 +40,11 @@ class QuoteFast implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'QuoteFast',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -72,8 +69,9 @@ public function execute(): void
{
$moderate_boards = User::$me->boardsAllowedTo('moderate_board');
- $request = Db::$db->query('', '
- SELECT COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.body, m.id_topic, m.subject,
+ $request = Db::$db->query(
+ '',
+ 'SELECT COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.body, m.id_topic, m.subject,
m.id_board, m.id_member, m.approved, m.modified_time, m.modified_name, m.modified_reason
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
@@ -82,23 +80,24 @@ public function execute(): void
AND m.id_msg = {int:id_msg}' . (isset($_REQUEST['modify']) || (!empty($moderate_boards) && $moderate_boards[0] == 0) ? '' : '
AND (t.locked = {int:not_locked}' . (empty($moderate_boards) ? '' : ' OR m.id_board IN ({array_int:moderation_board_list})') . ')') . '
LIMIT 1',
- array(
+ [
'current_member' => User::$me->id,
'moderation_board_list' => $moderate_boards,
'id_msg' => (int) $_REQUEST['quote'],
'not_locked' => 0,
- )
+ ],
);
Utils::$context['close_window'] = Db::$db->num_rows($request) == 0;
$row = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
Utils::$context['sub_template'] = 'quotefast';
- if (!empty($row))
+
+ if (!empty($row)) {
$can_view_post = $row['approved'] || ($row['id_member'] != 0 && $row['id_member'] == User::$me->id) || User::$me->allowedTo('approve_posts', $row['id_board']);
+ }
- if (!empty($can_view_post))
- {
+ if (!empty($can_view_post)) {
// Remove special formatting we don't want anymore.
$row['body'] = Msg::un_preparsecode($row['body']);
@@ -106,60 +105,59 @@ public function execute(): void
Lang::censorText($row['body']);
// Want to modify a single message by double clicking it?
- if (isset($_REQUEST['modify']))
- {
+ if (isset($_REQUEST['modify'])) {
Lang::censorText($row['subject']);
Utils::$context['sub_template'] = 'modifyfast';
- Utils::$context['message'] = array(
+ Utils::$context['message'] = [
'id' => $_REQUEST['quote'],
'body' => $row['body'],
'subject' => addcslashes($row['subject'], '"'),
- 'reason' => array(
+ 'reason' => [
'name' => $row['modified_name'],
'text' => $row['modified_reason'],
'time' => $row['modified_time'],
- ),
- );
+ ],
+ ];
return;
}
// Remove any nested quotes.
- if (!empty(Config::$modSettings['removeNestedQuotes']))
- $row['body'] = preg_replace(array('~\n?\[quote.*?\].+?\[/quote\]\n?~is', '~^\n~', '~\[/quote\]~'), '', $row['body']);
+ if (!empty(Config::$modSettings['removeNestedQuotes'])) {
+ $row['body'] = preg_replace(['~\n?\[quote.*?\].+?\[/quote\]\n?~is', '~^\n~', '~\[/quote\]~'], '', $row['body']);
+ }
$lb = "\n";
// Add a quote string on the front and end.
Utils::$context['quote']['xml'] = '[quote author=' . $row['poster_name'] . ' link=msg=' . (int) $_REQUEST['quote'] . ' date=' . $row['poster_time'] . ']' . $lb . $row['body'] . $lb . '[/quote]';
- Utils::$context['quote']['text'] = strtr(Utils::htmlspecialcharsDecode(Utils::$context['quote']['xml']), array('\'' => '\\\'', '\\' => '\\\\', "\n" => '\\n', '' => '\' + \'script>'));
- Utils::$context['quote']['xml'] = strtr(Utils::$context['quote']['xml'], array(' ' => ' ', '<' => '<', '>' => '>'));
+ Utils::$context['quote']['text'] = strtr(Utils::htmlspecialcharsDecode(Utils::$context['quote']['xml']), ['\'' => '\\\'', '\\' => '\\\\', "\n" => '\\n', '' => '\' + \'script>']);
+ Utils::$context['quote']['xml'] = strtr(Utils::$context['quote']['xml'], [' ' => ' ', '<' => '<', '>' => '>']);
- Utils::$context['quote']['mozilla'] = strtr(Utils::htmlspecialchars(Utils::$context['quote']['text']), array('"' => '"'));
+ Utils::$context['quote']['mozilla'] = strtr(Utils::htmlspecialchars(Utils::$context['quote']['text']), ['"' => '"']);
}
- //@todo Needs a nicer interface.
+ // @todo Needs a nicer interface.
// In case our message has been removed in the meantime.
- elseif (isset($_REQUEST['modify']))
- {
+ elseif (isset($_REQUEST['modify'])) {
Utils::$context['sub_template'] = 'modifyfast';
- Utils::$context['message'] = array(
+ Utils::$context['message'] = [
'id' => 0,
'body' => '',
'subject' => '',
- 'reason' => array(
+ 'reason' => [
'name' => '',
'text' => '',
'time' => '',
- ),
- );
- }
- else
- Utils::$context['quote'] = array(
+ ],
+ ];
+ } else {
+ Utils::$context['quote'] = [
'xml' => '',
'mozilla' => '',
'text' => '',
- );
+ ];
+ }
}
/***********************
@@ -173,8 +171,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;
}
@@ -198,13 +197,15 @@ protected function __construct()
{
Lang::load('Post');
- if (!isset($_REQUEST['xml']))
+ if (!isset($_REQUEST['xml'])) {
Theme::loadTemplate('Post');
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\QuoteFast::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\QuoteFast::exportStatic')) {
QuoteFast::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Recent.php b/Sources/Actions/Recent.php
index 6566ef713f..b4559a708a 100644
--- a/Sources/Actions/Recent.php
+++ b/Sources/Actions/Recent.php
@@ -14,10 +14,11 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\BBCodeParser;
use SMF\Board;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -27,8 +28,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* Finds and retrieves information about recently posted messages.
@@ -42,19 +41,19 @@ class Recent implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'RecentPosts',
- ),
- );
+ 'getLastPost' => 'getLastPost',
+ ],
+ ];
/*****************
* Class constants
*****************/
- const PER_PAGE = 10;
- const PAGES = 10;
+ public const PER_PAGE = 10;
+ public const PAGES = 10;
/*********************
* Internal properties
@@ -79,7 +78,7 @@ class Recent implements ActionInterface
*
* Parameters for the main query.
*/
- protected array $query_parameters = array();
+ protected array $query_parameters = [];
/**
* @var string
@@ -100,18 +99,17 @@ class Recent implements ActionInterface
*
* IDs of some recent messages.
*/
- protected array $messages = array();
+ protected array $messages = [];
/**
* @var array
*
* Boards that we need to check for some own/any permissions.
*/
- protected array $permission_boards = array(
- 'own' => array(),
- 'any' => array(),
- );
-
+ protected array $permission_boards = [
+ 'own' => [],
+ 'any' => [],
+ ];
/****************************
* Internal static properties
@@ -142,8 +140,9 @@ public function execute(): void
$this->getMsgIds();
// Nothing here... Or at least, nothing you can see...
- if (empty($this->messages))
+ if (empty($this->messages)) {
return;
+ }
$this->getMessages();
$this->doPermissions();
@@ -164,8 +163,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;
}
@@ -189,8 +189,9 @@ public static function call(): void
public static function getLastPost()
{
// Find it by the board - better to order by board than sort the entire messages table.
- $request = Db::$db->query('substring', '
- SELECT m.poster_time, m.subject, m.id_topic, m.poster_name, SUBSTRING(m.body, 1, 385) AS body,
+ $request = Db::$db->query(
+ 'substring',
+ 'SELECT m.poster_time, m.subject, m.id_topic, m.poster_name, SUBSTRING(m.body, 1, 385) AS body,
m.smileys_enabled
FROM {db_prefix}messages AS m' . (!empty(Config::$modSettings['postmod_active']) ? '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)' : '') . '
@@ -200,13 +201,15 @@ public static function getLastPost()
AND t.approved = {int:is_approved}' : '') . '
ORDER BY m.id_msg DESC
LIMIT 1',
- array(
+ [
'recycle_board' => Config::$modSettings['recycle_board'],
'is_approved' => 1,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- return array();
+
+ if (Db::$db->num_rows($request) == 0) {
+ return [];
+ }
$row = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
@@ -214,12 +217,14 @@ public static function getLastPost()
Lang::censorText($row['subject']);
Lang::censorText($row['body']);
- $row['body'] = strip_tags(strtr(BBCodeParser::load()->parse($row['body'], $row['smileys_enabled']), array(' ' => '
')));
- if (Utils::entityStrlen($row['body']) > 128)
+ $row['body'] = strip_tags(strtr(BBCodeParser::load()->parse($row['body'], $row['smileys_enabled']), [' ' => '
']));
+
+ if (Utils::entityStrlen($row['body']) > 128) {
$row['body'] = Utils::entitySubstr($row['body'], 0, 128) . '...';
+ }
// Send the data.
- return array(
+ return [
'topic' => $row['id_topic'],
'subject' => $row['subject'],
'short_subject' => Utils::shorten($row['subject'], 24),
@@ -227,8 +232,8 @@ public static function getLastPost()
'time' => Time::create('@' . $row['poster_time'])->format(),
'timestamp' => $row['poster_time'],
'href' => Config::$scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new',
- 'link' => ' ' . $row['subject'] . ''
- );
+ 'link' => ' ' . $row['subject'] . '',
+ ];
}
/******************
@@ -242,7 +247,7 @@ protected function __construct()
{
$this->action_url = Config::$scripturl . '?action=recent';
- Utils::$context['posts'] = array();
+ Utils::$context['posts'] = [];
Theme::loadTemplate('Recent');
Utils::$context['page_title'] = Lang::$txt['recent_posts'];
@@ -256,16 +261,19 @@ protected function __construct()
Utils::$context['start'] -= Utils::$context['start'] % self::PER_PAGE;
// Convert $_REQUEST['boards'] to an array of integers.
- if (!empty($_REQUEST['boards']))
+ if (!empty($_REQUEST['boards'])) {
$_REQUEST['boards'] = array_map('intval', explode(',', $_REQUEST['boards']));
+ }
// Board requests takes precedence over category requests.
- if (!empty($_REQUEST['boards']) || !empty(Board::$info->id))
+ if (!empty($_REQUEST['boards']) || !empty(Board::$info->id)) {
unset($_REQUEST['c']);
+ }
// Convert $_REQUEST['c'] to an array of integers.
- if (!empty($_REQUEST['c']))
+ if (!empty($_REQUEST['c'])) {
$_REQUEST['c'] = array_map('intval', explode(',', $_REQUEST['c']));
+ }
}
/**
@@ -278,38 +286,38 @@ protected function __construct()
protected function getBoards()
{
// Requested one or more categories.
- if (!empty($_REQUEST['c']))
- {
- $boards = array();
- $request = Db::$db->query('', '
- SELECT b.id_board, b.num_posts
+ if (!empty($_REQUEST['c'])) {
+ $boards = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board, b.num_posts
FROM {db_prefix}boards AS b
WHERE b.id_cat IN ({array_int:category_list})
AND b.redirect = {string:empty}' . (!empty(Config::$modSettings['recycle_enable']) && !empty(Config::$modSettings['recycle_board']) ? '
AND b.id_board != {int:recycle_board}' : '') . '
AND {query_wanna_see_board}',
- array(
+ [
'category_list' => $_REQUEST['c'],
'empty' => '',
'recycle_board' => !empty(Config::$modSettings['recycle_board']) ? Config::$modSettings['recycle_board'] : 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$boards[] = $row['id_board'];
$this->total_posts += $row['num_posts'];
}
Db::$db->free_result($request);
- if (empty($boards))
+ if (empty($boards)) {
ErrorHandler::fatalLang('error_no_boards_selected');
+ }
$this->query_this_board = 'm.id_board IN ({array_int:boards})';
$this->query_parameters['boards'] = $boards;
// If this category has a significant number of posts in it...
- if ($this->total_posts > 100 && $this->total_posts > Config::$modSettings['totalMessages'] / 15)
- {
+ if ($this->total_posts > 100 && $this->total_posts > Config::$modSettings['totalMessages'] / 15) {
$this->query_this_board .= '
AND m.id_msg >= {int:max_id_msg}';
$this->query_parameters['max_id_msg'] = max(0, Config::$modSettings['maxMsgID'] - 400 - Utils::$context['start'] * 7);
@@ -318,42 +326,44 @@ protected function getBoards()
$this->action_url .= ';c=' . implode(',', $_REQUEST['c']);
}
// Requested some boards.
- elseif (!empty($_REQUEST['boards']))
- {
+ elseif (!empty($_REQUEST['boards'])) {
$_REQUEST['boards'] = explode(',', $_REQUEST['boards']);
- foreach ($_REQUEST['boards'] as $i => $b)
+
+ foreach ($_REQUEST['boards'] as $i => $b) {
$_REQUEST['boards'][$i] = (int) $b;
+ }
- $request = Db::$db->query('', '
- SELECT b.id_board, b.num_posts
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board, b.num_posts
FROM {db_prefix}boards AS b
WHERE b.id_board IN ({array_int:board_list})
AND b.redirect = {string:empty}
AND {query_see_board}
LIMIT {int:limit}',
- array(
+ [
'board_list' => $_REQUEST['boards'],
'limit' => count($_REQUEST['boards']),
'empty' => '',
- )
+ ],
);
- $boards = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $boards = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$boards[] = $row['id_board'];
$this->total_posts += $row['num_posts'];
}
Db::$db->free_result($request);
- if (empty($boards))
+ if (empty($boards)) {
ErrorHandler::fatalLang('error_no_boards_selected');
+ }
$this->query_this_board = 'm.id_board IN ({array_int:boards})';
$this->query_parameters['boards'] = $boards;
// If these boards have a significant number of posts in them...
- if ($this->total_posts > 100 && $this->total_posts > Config::$modSettings['totalMessages'] / 12)
- {
+ if ($this->total_posts > 100 && $this->total_posts > Config::$modSettings['totalMessages'] / 12) {
$this->query_this_board .= '
AND m.id_msg >= {int:max_id_msg}';
$this->query_parameters['max_id_msg'] = max(0, Config::$modSettings['maxMsgID'] - 500 - Utils::$context['start'] * 9);
@@ -362,23 +372,22 @@ protected function getBoards()
$this->action_url .= ';boards=' . implode(',', $_REQUEST['boards']);
}
// Requested a single board.
- elseif (!empty(Board::$info->id))
- {
- $request = Db::$db->query('', '
- SELECT num_posts, redirect
+ elseif (!empty(Board::$info->id)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT num_posts, redirect
FROM {db_prefix}boards
WHERE id_board = {int:current_board}
LIMIT 1',
- array(
+ [
'current_board' => Board::$info->id,
- )
+ ],
);
- list ($this->total_posts, $redirect) = Db::$db->fetch_row($request);
+ list($this->total_posts, $redirect) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// If this is a redirection board, don't bother counting topics here...
- if ($redirect != '')
- {
+ if ($redirect != '') {
Utils::$context['is_redirect'] = true;
}
@@ -386,8 +395,7 @@ protected function getBoards()
$this->query_parameters['board'] = Board::$info->id;
// If this board has a significant number of posts in it...
- if ($this->total_posts > 80 && $this->total_posts > Config::$modSettings['totalMessages'] / 10)
- {
+ if ($this->total_posts > 80 && $this->total_posts > Config::$modSettings['totalMessages'] / 10) {
$this->query_this_board .= '
AND m.id_msg >= {int:max_id_msg}';
$this->query_parameters['max_id_msg'] = max(0, Config::$modSettings['maxMsgID'] - 600 - Utils::$context['start'] * 10);
@@ -396,8 +404,7 @@ protected function getBoards()
$this->action_url .= ';board=' . Board::$info->id . '.%1$d';
}
// Requested recent posts from across the whole forum.
- else
- {
+ else {
$this->query_this_board = '{query_wanna_see_message_board}' . (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0 ? '
AND m.id_board != {int:recycle_board}' : '') . '
AND m.id_msg >= {int:max_id_msg}';
@@ -409,12 +416,13 @@ protected function getBoards()
$query_these_boards_params = $this->query_parameters;
unset($query_these_boards_params['max_id_msg']);
- $get_num_posts = Db::$db->query('', '
- SELECT COALESCE(SUM(b.num_posts), 0)
+ $get_num_posts = Db::$db->query(
+ '',
+ 'SELECT COALESCE(SUM(b.num_posts), 0)
FROM {db_prefix}boards AS b
WHERE ' . $query_these_boards . '
AND b.redirect = {string:empty}',
- array_merge($query_these_boards_params, array('empty' => ''))
+ array_merge($query_these_boards_params, ['empty' => '']),
);
list($this->total_posts) = Db::$db->fetch_row($get_num_posts);
@@ -428,18 +436,18 @@ protected function getBoards()
*/
protected function getCatName()
{
- if (!empty($_REQUEST['c']) && is_array($_REQUEST['c']) && count($_REQUEST['c']) == 1)
- {
- $request = Db::$db->query('', '
- SELECT name
+ if (!empty($_REQUEST['c']) && is_array($_REQUEST['c']) && count($_REQUEST['c']) == 1) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT name
FROM {db_prefix}categories
WHERE id_cat = {int:id_cat}
LIMIT 1',
- array(
+ [
'id_cat' => (int) $_REQUEST['c'][0],
- )
+ ],
);
- list ($this->cat_name) = Db::$db->fetch_row($request);
+ list($this->cat_name) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
}
}
@@ -450,21 +458,21 @@ protected function getCatName()
protected function getMsgIds()
{
// If you selected a redirection board, don't try getting posts for it...
- if (Utils::$context['is_redirect'])
+ if (Utils::$context['is_redirect']) {
return;
+ }
- $cache_key = 'recent-' . User::$me->id . '-' . md5(Utils::jsonEncode(array_diff_key($this->query_parameters, array('max_id_msg' => 0)))) . '-' . Utils::$context['start'];
+ $cache_key = 'recent-' . User::$me->id . '-' . md5(Utils::jsonEncode(array_diff_key($this->query_parameters, ['max_id_msg' => 0]))) . '-' . Utils::$context['start'];
- if (empty(CacheApi::$enable) || ($this->messages = CacheApi::get($cache_key, 120)) == null)
- {
+ if (empty(CacheApi::$enable) || ($this->messages = CacheApi::get($cache_key, 120)) == null) {
$done = false;
- while (!$done)
- {
+ while (!$done) {
// Find the most recent messages they can *view*.
// @todo SLOW This query is really slow still, probably?
- $request = Db::$db->query('', '
- SELECT m.id_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg
FROM {db_prefix}messages AS m ' . (!empty(Config::$modSettings['postmod_active']) ? '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)' : '') . '
WHERE ' . $this->query_this_board . (!empty(Config::$modSettings['postmod_active']) ? '
@@ -472,16 +480,15 @@ protected function getMsgIds()
AND t.approved = {int:is_approved}' : '') . '
ORDER BY m.id_msg DESC
LIMIT {int:offset}, {int:limit}',
- array_merge($this->query_parameters, array(
+ array_merge($this->query_parameters, [
'is_approved' => 1,
'offset' => Utils::$context['start'],
'limit' => self::PER_PAGE,
- ))
+ ]),
);
// If we don't have enough results, try again with an unoptimized version covering all rows, and cache the result.
- if (isset($this->query_parameters['max_id_msg']) && Db::$db->num_rows($request) < self::PER_PAGE)
- {
+ if (isset($this->query_parameters['max_id_msg']) && Db::$db->num_rows($request) < self::PER_PAGE) {
Db::$db->free_result($request);
$this->query_this_board = str_replace('AND m.id_msg >= {int:max_id_msg}', '', $this->query_this_board);
@@ -489,18 +496,19 @@ protected function getMsgIds()
$cache_results = true;
unset($this->query_parameters['max_id_msg']);
- }
- else
+ } else {
$done = true;
+ }
}
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$this->messages[] = $row['id_msg'];
}
Db::$db->free_result($request);
- if (!empty($cache_results))
+ if (!empty($cache_results)) {
CacheApi::put($cache_key, $this->messages, 120);
+ }
}
}
@@ -509,49 +517,50 @@ protected function getMsgIds()
*/
protected function getMessages()
{
- $query_customizations = array(
- 'selects' => array(
+ $query_customizations = [
+ 'selects' => [
'm.*',
'COALESCE(mem.real_name, m.poster_name) AS poster_name',
'b.name AS bname',
't.id_member_started',
't.id_first_msg',
't.id_last_msg',
- ),
- 'joins' => array(
+ ],
+ 'joins' => [
'INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)',
'INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)',
'LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)',
- ),
- 'order' => array('m.id_msg DESC'),
+ ],
+ 'order' => ['m.id_msg DESC'],
'limit' => count($this->messages),
- 'params' => array(),
- );
+ 'params' => [],
+ ];
$counter = Utils::$context['start'] + 1;
- foreach (Msg::get($this->messages, $query_customizations) as $msg)
- {
- Utils::$context['posts'][$msg->id] = $msg->format($counter++, array(
+
+ foreach (Msg::get($this->messages, $query_customizations) as $msg) {
+ Utils::$context['posts'][$msg->id] = $msg->format($counter++, [
'do_permissions' => false,
'do_icon' => false,
'load_author' => false,
'shorten_subject' => 30,
- ));
+ ]);
- Utils::$context['posts'][$msg->id]['board'] = array(
+ Utils::$context['posts'][$msg->id]['board'] = [
'id' => $msg->id_board,
'name' => $msg->bname,
'href' => Config::$scripturl . '?board=' . $msg->id_board . '.0',
- 'link' => ' ' . $msg->bname . ''
- );
+ 'link' => ' ' . $msg->bname . '',
+ ];
Utils::$context['posts'][$msg->id]['can_reply'] = false;
Utils::$context['posts'][$msg->id]['can_delete'] = false;
Utils::$context['posts'][$msg->id]['delete_possible'] = ($msg->id_first_msg != $msg->id || $msg->id_last_msg == $msg->id) && (empty(Config::$modSettings['edit_disable_time']) || $msg->poster_time + Config::$modSettings['edit_disable_time'] * 60 >= time());
- if (User::$me->id == $msg->id_member_started)
+ if (User::$me->id == $msg->id_member_started) {
$this->permission_boards['own'][$msg->id_board][] = $msg->id;
+ }
$this->permission_boards['any'][$msg->id_board][] = $msg->id;
}
@@ -563,46 +572,45 @@ protected function getMessages()
protected function doPermissions(): void
{
// There might be - and are - different permissions between any and own.
- $permissions = array(
- 'own' => array(
+ $permissions = [
+ 'own' => [
'post_reply_own' => 'can_reply',
'delete_own' => 'can_delete',
- ),
- 'any' => array(
+ ],
+ 'any' => [
'post_reply_any' => 'can_reply',
'delete_any' => 'can_delete',
- )
- );
+ ],
+ ];
// Create an array for the permissions.
- $boards_can = User::$me->boardsAllowedTo(array_keys(iterator_to_array(
- new \RecursiveIteratorIterator(new \RecursiveArrayIterator($permissions)))
+ $boards_can = User::$me->boardsAllowedTo(array_keys(
+ iterator_to_array(
+ new \RecursiveIteratorIterator(new \RecursiveArrayIterator($permissions)),
+ ),
), true, false);
// Now go through all the permissions, looking for boards they can do it on.
- foreach ($permissions as $type => $list)
- {
- foreach ($list as $permission => $allowed)
- {
+ foreach ($permissions as $type => $list) {
+ foreach ($list as $permission => $allowed) {
// They can do it on these boards...
$boards = $boards_can[$permission];
// If 0 is the only thing in the array, they can do it everywhere!
- if (!empty($boards) && $boards[0] == 0)
+ if (!empty($boards) && $boards[0] == 0) {
$boards = array_keys($this->permission_boards[$type]);
+ }
// Go through the boards, and look for posts they can do this on.
- foreach ($boards as $board_id)
- {
+ foreach ($boards as $board_id) {
// Hmm, they have permission, but there are no topics from that board on this page.
- if (!isset($this->permission_boards[$type][$board_id]))
+ if (!isset($this->permission_boards[$type][$board_id])) {
continue;
+ }
// Okay, looks like they can do it for these posts.
- foreach ($this->permission_boards[$type][$board_id] as $counter)
- {
- if ($type == 'any' || Utils::$context['posts'][$counter]['poster']['id'] == User::$me->id)
- {
+ foreach ($this->permission_boards[$type][$board_id] as $counter) {
+ if ($type == 'any' || Utils::$context['posts'][$counter]['poster']['id'] == User::$me->id) {
Utils::$context['posts'][$counter][$allowed] = true;
}
}
@@ -612,8 +620,7 @@ protected function doPermissions(): void
$quote_enabled = empty(Config::$modSettings['disabledBBC']) || !in_array('quote', explode(',', Config::$modSettings['disabledBBC']));
- foreach (Utils::$context['posts'] as $counter => $dummy)
- {
+ foreach (Utils::$context['posts'] as $counter => $dummy) {
// Some posts - the first posts - can't just be deleted.
Utils::$context['posts'][$counter]['can_delete'] &= Utils::$context['posts'][$counter]['delete_possible'];
@@ -631,35 +638,34 @@ protected function setPaginationAndLinks()
$not_first_page = Utils::$context['start'] >= self::PER_PAGE;
$not_last_page = Utils::$context['start'] + self::PER_PAGE < $this->total_posts;
- if (isset($this->cat_name))
- {
- Utils::$context['linktree'][] = array(
+ if (isset($this->cat_name)) {
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '#c' . (int) $_REQUEST['c'][0],
'name' => $this->cat_name,
- );
+ ];
}
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => sprintf($this->action_url, 0),
'name' => Utils::$context['page_title'],
- );
+ ];
Utils::$context['page_index'] = new PageIndex($this->action_url, Utils::$context['start'], $total, self::PER_PAGE, !empty(Board::$info->id));
Utils::$context['current_page'] = floor(Utils::$context['start'] / self::PER_PAGE);
- Utils::$context['links'] = array(
+ Utils::$context['links'] = [
'first' => $not_first_page ? sprintf($this->action_url, 0) : '',
'prev' => $not_first_page ? sprintf($this->action_url, Utils::$context['start'] - self::PER_PAGE) : '',
'next' => $not_last_page ? sprintf($this->action_url, Utils::$context['start'] + self::PER_PAGE) : '',
'last' => $not_last_page ? sprintf($this->action_url, $total - ($total % self::PER_PAGE)) : '',
'up' => Config::$scripturl,
- );
+ ];
- Utils::$context['page_info'] = array(
+ Utils::$context['page_info'] = [
'current_page' => Utils::$context['current_page'] + 1,
'num_pages' => floor(($total - 1) / self::PER_PAGE) + 1,
- );
+ ];
}
/**
@@ -667,36 +673,36 @@ protected function setPaginationAndLinks()
*/
protected function buildQuickButtons()
{
- foreach (Utils::$context['posts'] as $key => $post)
- {
- Utils::$context['posts'][$key]['quickbuttons'] = array(
- 'reply' => array(
+ foreach (Utils::$context['posts'] as $key => $post) {
+ Utils::$context['posts'][$key]['quickbuttons'] = [
+ 'reply' => [
'label' => Lang::$txt['reply'],
- 'href' => Config::$scripturl . '?action=post;topic=' . $post['topic'] .'.0',
+ 'href' => Config::$scripturl . '?action=post;topic=' . $post['topic'] . '.0',
'icon' => 'reply_button',
- 'show' => $post['can_reply']
- ),
- 'quote' => array(
+ 'show' => $post['can_reply'],
+ ],
+ 'quote' => [
'label' => Lang::$txt['quote_action'],
'href' => Config::$scripturl . '?action=post;topic=' . $post['topic'] . '.0;quote=' . $post['id'],
'icon' => 'quote',
- 'show' => $post['can_quote']
- ),
- 'delete' => array(
+ 'show' => $post['can_quote'],
+ ],
+ 'delete' => [
'label' => Lang::$txt['remove'],
'href' => Config::$scripturl . '?action=deletemsg;msg=' . $post['id'] . ';topic=' . $post['topic'] . ';recent;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
'javascript' => 'data-confirm="' . Lang::$txt['remove_message'] . '"',
'class' => 'you_sure',
'icon' => 'remove_button',
- 'show' => $post['can_delete']
- ),
- );
+ 'show' => $post['can_delete'],
+ ],
+ ];
}
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Recent::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Recent::exportStatic')) {
Recent::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Register.php b/Sources/Actions/Register.php
index 12b240dc27..aa4006ce9b 100644
--- a/Sources/Actions/Register.php
+++ b/Sources/Actions/Register.php
@@ -14,19 +14,16 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\BBCodeParser;
use SMF\Config;
use SMF\ErrorHandler;
use SMF\Lang;
-use SMF\Mail;
use SMF\Profile;
use SMF\SecurityToken;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
use SMF\Verifier;
-use SMF\Db\DatabaseApi as Db;
/**
* Shows the registration form.
@@ -40,12 +37,11 @@ class Register implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'register' => 'Register',
+ ],
+ ];
/*******************
* Public properties
@@ -63,7 +59,7 @@ class Register implements ActionInterface
*
* Errors encountered while trying to register.
*/
- public array $errors = array();
+ public array $errors = [];
/**************************
* Public static properties
@@ -74,10 +70,10 @@ class Register implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'show' => 'show',
'usernamecheck' => 'checkUsername',
- );
+ ];
/****************************
* Internal static properties
@@ -100,10 +96,11 @@ class Register 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);
+ }
}
/**
@@ -112,15 +109,18 @@ public function execute(): void
public function show(): void
{
// Check if the administrator has it disabled.
- if (!empty(Config::$modSettings['registration_method']) && Config::$modSettings['registration_method'] == '3')
+ if (!empty(Config::$modSettings['registration_method']) && Config::$modSettings['registration_method'] == '3') {
ErrorHandler::fatalLang('registration_disabled', false);
+ }
// If this user is an admin - redirect them to the admin registration page.
- if (User::$me->allowedTo('moderate_forum') && !User::$me->is_guest)
+ if (User::$me->allowedTo('moderate_forum') && !User::$me->is_guest) {
Utils::redirectexit('action=admin;area=regcenter;sa=register');
+ }
// You are not a guest, so you are a member - and members don't get to register twice!
- elseif (empty(User::$me->is_guest))
+ elseif (empty(User::$me->is_guest)) {
Utils::redirectexit();
+ }
Lang::load('Login');
Theme::loadTemplate('Register');
@@ -133,86 +133,85 @@ public function show(): void
Utils::$context['show_coppa'] = !empty(Config::$modSettings['coppaAge']);
$agree_txt_key = '';
- if ($current_step == 1)
- {
- if (!empty(Config::$modSettings['requireAgreement']) && !empty(Config::$modSettings['requirePolicyAgreement']))
+
+ if ($current_step == 1) {
+ if (!empty(Config::$modSettings['requireAgreement']) && !empty(Config::$modSettings['requirePolicyAgreement'])) {
$agree_txt_key = 'agreement_policy_';
- elseif (!empty(Config::$modSettings['requireAgreement']))
+ } elseif (!empty(Config::$modSettings['requireAgreement'])) {
$agree_txt_key = 'agreement_';
- elseif (!empty(Config::$modSettings['requirePolicyAgreement']))
+ } elseif (!empty(Config::$modSettings['requirePolicyAgreement'])) {
$agree_txt_key = 'policy_';
+ }
}
// Under age restrictions?
- if (Utils::$context['show_coppa'])
- {
+ if (Utils::$context['show_coppa']) {
Utils::$context['skip_coppa'] = false;
Utils::$context['coppa_agree_above'] = sprintf(Lang::$txt[$agree_txt_key . 'agree_coppa_above'], Config::$modSettings['coppaAge']);
Utils::$context['coppa_agree_below'] = sprintf(Lang::$txt[$agree_txt_key . 'agree_coppa_below'], Config::$modSettings['coppaAge']);
- }
- elseif ($agree_txt_key != '')
+ } elseif ($agree_txt_key != '') {
Utils::$context['agree'] = Lang::$txt[$agree_txt_key . 'agree'];
+ }
// Does this user agree to the registration agreement?
- if ($current_step == 1 && (isset($_POST['accept_agreement']) || isset($_POST['accept_agreement_coppa'])))
- {
+ if ($current_step == 1 && (isset($_POST['accept_agreement']) || isset($_POST['accept_agreement_coppa']))) {
Utils::$context['registration_passed_agreement'] = $_SESSION['registration_agreed'] = true;
$current_step = 2;
// Skip the coppa procedure if the user says he's old enough.
- if (Utils::$context['show_coppa'])
- {
+ if (Utils::$context['show_coppa']) {
$_SESSION['skip_coppa'] = !empty($_POST['accept_agreement']);
// Are they saying they're under age, while under age registration is disabled?
- if (empty(Config::$modSettings['coppaType']) && empty($_SESSION['skip_coppa']))
- {
+ if (empty(Config::$modSettings['coppaType']) && empty($_SESSION['skip_coppa'])) {
Lang::load('Login');
- ErrorHandler::fatalLang('under_age_registration_prohibited', false, array(Config::$modSettings['coppaAge']));
+ ErrorHandler::fatalLang('under_age_registration_prohibited', false, [Config::$modSettings['coppaAge']]);
}
}
}
// Make sure they don't squeeze through without agreeing.
- elseif ($current_step > 1 && (!empty(Config::$modSettings['requireAgreement']) || !empty(Config::$modSettings['requirePolicyAgreement'])) && !Utils::$context['registration_passed_agreement'])
+ elseif ($current_step > 1 && (!empty(Config::$modSettings['requireAgreement']) || !empty(Config::$modSettings['requirePolicyAgreement'])) && !Utils::$context['registration_passed_agreement']) {
$current_step = 1;
+ }
// Show the user the right form.
Utils::$context['sub_template'] = $current_step == 1 ? 'registration_agreement' : 'registration_form';
Utils::$context['page_title'] = $current_step == 1 ? Lang::$txt['registration_agreement'] : Lang::$txt['registration_form'];
// Kinda need this.
- if (Utils::$context['sub_template'] == 'registration_form')
- Theme::loadJavaScriptFile('register.js', array('defer' => false, 'minimize' => true), 'smf_register');
+ if (Utils::$context['sub_template'] == 'registration_form') {
+ Theme::loadJavaScriptFile('register.js', ['defer' => false, 'minimize' => true], 'smf_register');
+ }
// Add the register chain to the link tree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=signup',
'name' => Lang::$txt['register'],
- );
+ ];
// Prepare the time gate! Do it like so, in case later steps want to reset the limit for any reason, but make sure the time is the current one.
- if (!isset($_SESSION['register']))
- $_SESSION['register'] = array(
+ if (!isset($_SESSION['register'])) {
+ $_SESSION['register'] = [
'timenow' => time(),
'limit' => 10, // minimum number of seconds required on this page for registration
- );
- else
+ ];
+ } else {
$_SESSION['register']['timenow'] = time();
+ }
// If you have to agree to the agreement, it needs to be fetched from the file.
- if (!empty(Config::$modSettings['requireAgreement']))
- {
+ if (!empty(Config::$modSettings['requireAgreement'])) {
// Have we got a localized one?
- if (file_exists(Config::$boarddir . '/agreement.' . User::$me->language . '.txt'))
+ if (file_exists(Config::$boarddir . '/agreement.' . User::$me->language . '.txt')) {
Utils::$context['agreement'] = BBCodeParser::load()->parse(file_get_contents(Config::$boarddir . '/agreement.' . User::$me->language . '.txt'), true, 'agreement_' . User::$me->language);
- elseif (file_exists(Config::$boarddir . '/agreement.txt'))
+ } elseif (file_exists(Config::$boarddir . '/agreement.txt')) {
Utils::$context['agreement'] = BBCodeParser::load()->parse(file_get_contents(Config::$boarddir . '/agreement.txt'), true, 'agreement');
- else
+ } else {
Utils::$context['agreement'] = '';
+ }
// Nothing to show, lets disable registration and inform the admin of this error
- if (empty(Utils::$context['agreement']))
- {
+ if (empty(Utils::$context['agreement'])) {
// No file found or a blank file, log the error so the admin knows there is a problem!
ErrorHandler::log(Lang::$txt['registration_agreement_missing'], 'critical');
ErrorHandler::fatalLang('registration_disabled', false);
@@ -222,35 +221,33 @@ public function show(): void
$prefs = Notify::getNotifyPrefs(0, 'announcements');
Utils::$context['notify_announcements'] = !empty($prefs[0]['announcements']);
- if (!empty(Config::$modSettings['userLanguage']))
- {
+ if (!empty(Config::$modSettings['userLanguage'])) {
$selectedLanguage = empty($_SESSION['language']) ? Lang::$default : $_SESSION['language'];
// Do we have any languages?
- if (empty(Utils::$context['languages']))
+ if (empty(Utils::$context['languages'])) {
Lang::get();
+ }
// Try to find our selected language.
- foreach (Utils::$context['languages'] as $key => $lang)
- {
- Utils::$context['languages'][$key]['name'] = strtr($lang['name'], array('-utf8' => ''));
+ foreach (Utils::$context['languages'] as $key => $lang) {
+ Utils::$context['languages'][$key]['name'] = strtr($lang['name'], ['-utf8' => '']);
// Found it!
- if ($selectedLanguage == $lang['filename'])
+ if ($selectedLanguage == $lang['filename']) {
Utils::$context['languages'][$key]['selected'] = true;
+ }
}
}
// If you have to agree to the privacy policy, it needs to be loaded from the database.
- if (!empty(Config::$modSettings['requirePolicyAgreement']))
- {
+ if (!empty(Config::$modSettings['requirePolicyAgreement'])) {
// Have we got a localized one?
- if (!empty(Config::$modSettings['policy_' . User::$me->language]))
+ if (!empty(Config::$modSettings['policy_' . User::$me->language])) {
Utils::$context['privacy_policy'] = BBCodeParser::load()->parse(Config::$modSettings['policy_' . User::$me->language]);
- elseif (!empty(Config::$modSettings['policy_' . Lang::$default]))
+ } elseif (!empty(Config::$modSettings['policy_' . Lang::$default])) {
Utils::$context['privacy_policy'] = BBCodeParser::load()->parse(Config::$modSettings['policy_' . Lang::$default]);
- else
- {
+ } else {
// None was found; log the error so the admin knows there is a problem!
ErrorHandler::log(Lang::$txt['registration_policy_missing'], 'critical');
ErrorHandler::fatalLang('registration_disabled', false);
@@ -262,9 +259,8 @@ public function show(): void
Profile::$member->loadCustomFields('register');
// Or any standard ones?
- if (!empty(Config::$modSettings['registration_fields']))
- {
- require_once(Config::$sourcedir . '/Profile-Modify.php');
+ if (!empty(Config::$modSettings['registration_fields'])) {
+ require_once Config::$sourcedir . '/Profile-Modify.php';
// Setup some important context.
Lang::load('Profile');
@@ -273,47 +269,54 @@ public function show(): void
User::$me->is_owner = true;
// Here, and here only, emulate the permissions the user would have to do this.
- User::$me->permissions = array_merge(User::$me->permissions, array('profile_account_own', 'profile_extra_own', 'profile_other_own', 'profile_password_own', 'profile_website_own', 'profile_blurb'));
+ User::$me->permissions = array_merge(User::$me->permissions, ['profile_account_own', 'profile_extra_own', 'profile_other_own', 'profile_password_own', 'profile_website_own', 'profile_blurb']);
$reg_fields = explode(',', Config::$modSettings['registration_fields']);
// Website is a little different
- if (in_array('website', $reg_fields))
- {
+ if (in_array('website', $reg_fields)) {
unset($reg_fields['website']);
- if (isset($_POST['website_title']))
+
+ if (isset($_POST['website_title'])) {
User::$profiles[User::$me->id]['website_title'] = Utils::htmlspecialchars($_POST['website_title']);
- if (isset($_POST['website_url']))
+ }
+
+ if (isset($_POST['website_url'])) {
User::$profiles[User::$me->id]['website_url'] = Utils::htmlspecialchars($_POST['website_url']);
+ }
}
// We might have had some submissions on this front - go check.
- foreach ($reg_fields as $field)
- if (isset($_POST[$field]))
+ foreach ($reg_fields as $field) {
+ if (isset($_POST[$field])) {
User::$profiles[User::$me->id][$field] = Utils::htmlspecialchars($_POST[$field]);
+ }
+ }
// Load all the fields in question.
Profile::$member->setupContext($reg_fields);
}
// Generate a visual verification code to make sure the user is no bot.
- if (!empty(Config::$modSettings['reg_verification']))
- {
- $verifier = new Verifier(array('id' => 'register'));
+ if (!empty(Config::$modSettings['reg_verification'])) {
+ $verifier = new Verifier(['id' => 'register']);
}
// Otherwise we have nothing to show.
- else
+ else {
Utils::$context['visual_verification'] = false;
+ }
- Utils::$context += array(
+ Utils::$context += [
'username' => isset($_POST['user']) ? Utils::htmlspecialchars($_POST['user']) : '',
'email' => isset($_POST['email']) ? Utils::htmlspecialchars($_POST['email']) : '',
'notify_announcements' => !empty($_POST['notify_announcements']) ? 1 : 0,
- );
+ ];
// Were there any errors?
- Utils::$context['registration_errors'] = array();
- if (!empty($this->errors))
+ Utils::$context['registration_errors'] = [];
+
+ if (!empty($this->errors)) {
Utils::$context['registration_errors'] = $this->errors;
+ }
SecurityToken::create('register');
}
@@ -330,7 +333,7 @@ public function checkUsername()
Utils::$context['valid_username'] = true;
// Clean it up like mother would.
- Utils::$context['checked_username'] = trim(Utils::normalizeSpaces(Utils::sanitizeChars(Utils::$context['checked_username'], 1, ' '), true, true, array('no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true)));
+ Utils::$context['checked_username'] = trim(Utils::normalizeSpaces(Utils::sanitizeChars(Utils::$context['checked_username'], 1, ' '), true, true, ['no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true]));
$errors = User::validateUsername(0, Utils::$context['checked_username'], true);
@@ -348,8 +351,9 @@ public function checkUsername()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -367,7 +371,7 @@ public static function call(): void
*
* @param array $reg_errors Holds information about any errors that occurred.
*/
- public static function register($reg_errors = array()): void
+ public static function register($reg_errors = []): void
{
self::load();
self::$obj->subaction = 'show';
@@ -384,13 +388,15 @@ public static function register($reg_errors = array()): void
*/
protected function __construct()
{
- if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
+ if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Register::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Register::exportStatic')) {
Register::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Register2.php b/Sources/Actions/Register2.php
index 85984e6f8d..72a5cf6f20 100644
--- a/Sources/Actions/Register2.php
+++ b/Sources/Actions/Register2.php
@@ -14,14 +14,15 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\Cookie;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Group;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Logging;
+use SMF\Mail;
use SMF\Profile;
use SMF\Security;
use SMF\SecurityToken;
@@ -32,7 +33,6 @@
use SMF\User;
use SMF\Utils;
use SMF\Verifier;
-use SMF\Db\DatabaseApi as Db;
/**
* Actually registers the new member.
@@ -46,12 +46,12 @@ class Register2 extends Register
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'Register2',
- ),
- );
+ 'registerMember' => 'registerMember',
+ ],
+ ];
/*******************
* Public properties
@@ -62,7 +62,7 @@ class Register2 extends Register
*
* Registration fields that take strings.
*/
- public array $possible_strings = array(
+ public array $possible_strings = [
'birthdate',
'timezone',
'buddy_list',
@@ -73,34 +73,34 @@ class Register2 extends Register
'lngfile',
'secret_question',
'secret_answer',
- );
+ ];
/**
* @var array
*
* Registration fields that take integers.
*/
- public array $possible_ints = array(
+ public array $possible_ints = [
'id_theme',
- );
+ ];
/**
* @var array
*
* Registration fields that take floats.
*/
- public array $possible_floats = array(
+ public array $possible_floats = [
'time_offset',
- );
+ ];
/**
* @var array
*
* Registration fields that take booleans.
*/
- public array $possible_bools = array(
+ public array $possible_bools = [
'show_online',
- );
+ ];
/****************************
* Internal static properties
@@ -127,158 +127,146 @@ public function execute(): void
SecurityToken::validate('register');
// Check to ensure we're forcing SSL for authentication
- if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn())
+ if (!empty(Config::$modSettings['force_ssl']) && empty(Config::$maintenance) && !Config::httpsOn()) {
ErrorHandler::fatalLang('register_ssl_required');
+ }
// You can't register if it's disabled.
- if (!empty(Config::$modSettings['registration_method']) && Config::$modSettings['registration_method'] == 3)
+ if (!empty(Config::$modSettings['registration_method']) && Config::$modSettings['registration_method'] == 3) {
ErrorHandler::fatalLang('registration_disabled', false);
+ }
// Well, if you don't agree, you can't register.
- if ((!empty(Config::$modSettings['requireAgreement']) || !empty(Config::$modSettings['requirePolicyAgreement'])) && empty($_SESSION['registration_agreed']))
+ if ((!empty(Config::$modSettings['requireAgreement']) || !empty(Config::$modSettings['requirePolicyAgreement'])) && empty($_SESSION['registration_agreed'])) {
Utils::redirectexit();
+ }
// Make sure they came from *somewhere*, have a session.
- if (!isset($_SESSION['old_url']))
+ if (!isset($_SESSION['old_url'])) {
Utils::redirectexit('action=signup');
+ }
// If we require neither an agreement nor a privacy policy, we need a extra check for coppa.
- if (empty(Config::$modSettings['requireAgreement']) && empty(Config::$modSettings['requirePolicyAgreement']) && !empty(Config::$modSettings['coppaAge']))
- {
+ if (empty(Config::$modSettings['requireAgreement']) && empty(Config::$modSettings['requirePolicyAgreement']) && !empty(Config::$modSettings['coppaAge'])) {
$_SESSION['skip_coppa'] = !empty($_POST['accept_agreement']);
}
// Are they under age, and under age users are banned?
- if (!empty(Config::$modSettings['coppaAge']) && empty(Config::$modSettings['coppaType']) && empty($_SESSION['skip_coppa']))
- {
+ if (!empty(Config::$modSettings['coppaAge']) && empty(Config::$modSettings['coppaType']) && empty($_SESSION['skip_coppa'])) {
Lang::load('Errors');
- ErrorHandler::fatalLang('under_age_registration_prohibited', false, array(Config::$modSettings['coppaAge']));
+ ErrorHandler::fatalLang('under_age_registration_prohibited', false, [Config::$modSettings['coppaAge']]);
}
// Check the time gate for miscreants. First make sure they came from somewhere that actually set it up.
- if (empty($_SESSION['register']['timenow']) || empty($_SESSION['register']['limit']))
+ if (empty($_SESSION['register']['timenow']) || empty($_SESSION['register']['limit'])) {
Utils::redirectexit('action=signup');
+ }
// Failing that, check the time on it.
- if (time() - $_SESSION['register']['timenow'] < $_SESSION['register']['limit'])
- {
+ if (time() - $_SESSION['register']['timenow'] < $_SESSION['register']['limit']) {
Lang::load('Errors');
$this->errors[] = Lang::$txt['error_too_quickly'];
}
// Check whether the visual verification code was entered correctly.
- if (!empty(Config::$modSettings['reg_verification']))
- {
- $verifier = new Verifier(array('id' => 'register'));
+ if (!empty(Config::$modSettings['reg_verification'])) {
+ $verifier = new Verifier(['id' => 'register']);
- if (!empty($verifier->errors))
- {
+ if (!empty($verifier->errors)) {
Lang::load('Errors');
- foreach ($verifier->errors as $error)
+ foreach ($verifier->errors as $error) {
$this->errors[] = Lang::$txt['error_' . $error];
+ }
}
}
array_walk_recursive(
$_POST,
- function (&$value, $key)
- {
+ function (&$value, $key) {
// Normalize Unicode characters. (Does nothing if not in UTF-8 mode.)
$value = Utils::normalize($value);
// Replace any kind of space or illegal character with a normal space, and then trim.
- $value = Utils::htmlTrim(Utils::normalizeSpaces(Utils::sanitizeChars($value, 1, ' '), true, true, array('no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true)));
- }
+ $value = Utils::htmlTrim(Utils::normalizeSpaces(Utils::sanitizeChars($value, 1, ' '), true, true, ['no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true]));
+ },
);
// We may want to add certain things to these if selected in the admin panel.
- if (!empty(Config::$modSettings['registration_fields']))
- {
+ if (!empty(Config::$modSettings['registration_fields'])) {
$reg_fields = explode(',', Config::$modSettings['registration_fields']);
// Website is a little different
- if (in_array('website', $reg_fields))
- {
- $this->possible_strings = array_merge(array('website_url', 'website_title'), $this->possible_strings);
+ if (in_array('website', $reg_fields)) {
+ $this->possible_strings = array_merge(['website_url', 'website_title'], $this->possible_strings);
// Make sure their website URL is squeaky clean
- if (isset($_POST['website_url']))
- {
+ if (isset($_POST['website_url'])) {
$_POST['website_url'] = (string) Url::create($_POST['website_url'], true)->validate();
}
}
}
- if (isset($_POST['secret_answer']) && $_POST['secret_answer'] != '')
+ if (isset($_POST['secret_answer']) && $_POST['secret_answer'] != '') {
$_POST['secret_answer'] = Security::hashPassword($_POST['user'], $_POST['secret_answer']);
+ }
// Maybe you want set the displayed name during registration
- if (isset($_POST['real_name']))
- {
+ if (isset($_POST['real_name'])) {
// Are you already allowed to edit the displayed name?
- if (User::$me->allowedTo('profile_displayed_name') || User::$me->allowedTo('moderate_forum'))
- {
+ if (User::$me->allowedTo('profile_displayed_name') || User::$me->allowedTo('moderate_forum')) {
$can_edit_display_name = true;
}
// If you are a guest, will you be allowed to once you register?
- else
- {
- $request = Db::$db->query('', '
- SELECT add_deny
+ else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT add_deny
FROM {db_prefix}permissions
WHERE id_group = {int:id_group} AND permission = {string:permission}',
- array(
+ [
'id_group' => 0,
'permission' => 'profile_displayed_name_own',
- )
+ ],
);
list($can_edit_display_name) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
}
// Only set it if you can and if we are sure it is good
- if ($can_edit_display_name && Utils::htmlTrim($_POST['real_name']) != '' && !User::isReservedName($_POST['real_name']) && Utils::entityStrlen($_POST['real_name']) < 60)
- {
+ if ($can_edit_display_name && Utils::htmlTrim($_POST['real_name']) != '' && !User::isReservedName($_POST['real_name']) && Utils::entityStrlen($_POST['real_name']) < 60) {
$this->possible_strings[] = 'real_name';
}
}
// Handle a string as a birthdate...
- if (isset($_POST['birthdate']) && $_POST['birthdate'] != '')
- {
+ if (isset($_POST['birthdate']) && $_POST['birthdate'] != '') {
$_POST['birthdate'] = Time::strftime('%Y-%m-%d', strtotime($_POST['birthdate']));
}
// Or birthdate parts...
- elseif (!empty($_POST['bday1']) && !empty($_POST['bday2']))
- {
+ elseif (!empty($_POST['bday1']) && !empty($_POST['bday2'])) {
$_POST['birthdate'] = sprintf('%04d-%02d-%02d', empty($_POST['bday3']) ? 0 : (int) $_POST['bday3'], (int) $_POST['bday1'], (int) $_POST['bday2']);
}
// Validate the passed language file.
- if (isset($_POST['lngfile']) && !empty(Config::$modSettings['userLanguage']))
- {
+ if (isset($_POST['lngfile']) && !empty(Config::$modSettings['userLanguage'])) {
// Do we have any languages?
- if (empty(Utils::$context['languages']))
+ if (empty(Utils::$context['languages'])) {
Lang::get();
+ }
// Did we find it?
- if (isset(Utils::$context['languages'][$_POST['lngfile']]))
- {
+ if (isset(Utils::$context['languages'][$_POST['lngfile']])) {
$_SESSION['language'] = $_POST['lngfile'];
- }
- else
- {
+ } else {
unset($_POST['lngfile']);
}
- }
- else
- {
+ } else {
unset($_POST['lngfile']);
}
// Set the options needed for registration.
- $reg_options = array(
+ $reg_options = [
'interface' => 'guest',
'username' => !empty($_POST['user']) ? $_POST['user'] : '',
'email' => !empty($_POST['email']) ? $_POST['email'] : '',
@@ -289,134 +277,133 @@ function (&$value, $key)
'check_email_ban' => true,
'send_welcome_email' => !empty(Config::$modSettings['send_welcomeEmail']),
'require' => !empty(Config::$modSettings['coppaAge']) && empty($_SESSION['skip_coppa']) ? 'coppa' : (empty(Config::$modSettings['registration_method']) ? 'nothing' : (Config::$modSettings['registration_method'] == 1 ? 'activation' : 'approval')),
- 'extra_register_vars' => array(),
- 'theme_vars' => array(),
- );
+ 'extra_register_vars' => [],
+ 'theme_vars' => [],
+ ];
// Include the additional options that might have been filled in.
- foreach ($this->possible_strings as $var)
- {
- if (isset($_POST[$var]))
+ foreach ($this->possible_strings as $var) {
+ if (isset($_POST[$var])) {
$reg_options['extra_register_vars'][$var] = Utils::htmlspecialchars($_POST[$var], ENT_QUOTES);
+ }
}
- foreach ($this->possible_ints as $var)
- {
- if (isset($_POST[$var]))
+ foreach ($this->possible_ints as $var) {
+ if (isset($_POST[$var])) {
$reg_options['extra_register_vars'][$var] = (int) $_POST[$var];
+ }
}
- foreach ($this->possible_floats as $var)
- {
- if (isset($_POST[$var]))
+ foreach ($this->possible_floats as $var) {
+ if (isset($_POST[$var])) {
$reg_options['extra_register_vars'][$var] = (float) $_POST[$var];
+ }
}
- foreach ($this->possible_bools as $var)
- {
- if (isset($_POST[$var]))
+ foreach ($this->possible_bools as $var) {
+ if (isset($_POST[$var])) {
$reg_options['extra_register_vars'][$var] = empty($_POST[$var]) ? 0 : 1;
+ }
}
// Registration options are always default options...
- if (isset($_POST['default_options']))
- {
+ if (isset($_POST['default_options'])) {
$_POST['options'] = isset($_POST['options']) ? $_POST['options'] + $_POST['default_options'] : $_POST['default_options'];
}
- $reg_options['theme_vars'] = isset($_POST['options']) && is_array($_POST['options']) ? $_POST['options'] : array();
+ $reg_options['theme_vars'] = isset($_POST['options']) && is_array($_POST['options']) ? $_POST['options'] : [];
// Note when they accepted the agreement and privacy policy
- if (!empty(Config::$modSettings['requireAgreement']))
+ if (!empty(Config::$modSettings['requireAgreement'])) {
$reg_options['theme_vars']['agreement_accepted'] = time();
+ }
- if (!empty(Config::$modSettings['requirePolicyAgreement']))
+ if (!empty(Config::$modSettings['requirePolicyAgreement'])) {
$reg_options['theme_vars']['policy_accepted'] = time();
+ }
// Make sure they are clean, dammit!
$reg_options['theme_vars'] = Utils::htmlspecialcharsRecursive($reg_options['theme_vars']);
// Check whether we have fields that simply MUST be displayed?
- $request = Db::$db->query('', '
- SELECT col_name, field_name, field_type, field_length, mask, show_reg
+ $request = Db::$db->query(
+ '',
+ 'SELECT col_name, field_name, field_type, field_length, mask, show_reg
FROM {db_prefix}custom_fields
WHERE active = {int:is_active}
ORDER BY field_order',
- array(
+ [
'is_active' => 1,
- )
+ ],
);
- $custom_field_errors = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $custom_field_errors = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Don't allow overriding of the theme variables.
- if (isset($reg_options['theme_vars'][$row['col_name']]))
+ if (isset($reg_options['theme_vars'][$row['col_name']])) {
unset($reg_options['theme_vars'][$row['col_name']]);
+ }
// Not actually showing it then?
- if (!$row['show_reg'])
+ if (!$row['show_reg']) {
continue;
+ }
// Prepare the value!
$value = isset($_POST['customfield'][$row['col_name']]) ? trim($_POST['customfield'][$row['col_name']]) : '';
// We only care for text fields as the others are valid to be empty.
- if (!in_array($row['field_type'], array('check', 'select', 'radio')))
- {
+ if (!in_array($row['field_type'], ['check', 'select', 'radio'])) {
// Is it too long?
- if ($row['field_length'] && $row['field_length'] < Utils::entityStrlen($value))
- $custom_field_errors[] = array('custom_field_too_long', array($row['field_name'], $row['field_length']));
+ if ($row['field_length'] && $row['field_length'] < Utils::entityStrlen($value)) {
+ $custom_field_errors[] = ['custom_field_too_long', [$row['field_name'], $row['field_length']]];
+ }
// Any masks to apply?
- if ($row['field_type'] == 'text' && !empty($row['mask']) && $row['mask'] != 'none')
- {
- if ($row['mask'] == 'email' && (!filter_var($value, FILTER_VALIDATE_EMAIL) || strlen($value) > 255))
- {
- $custom_field_errors[] = array('custom_field_invalid_email', array($row['field_name']));
- }
- elseif ($row['mask'] == 'number' && preg_match('~[^\d]~', $value))
- {
- $custom_field_errors[] = array('custom_field_not_number', array($row['field_name']));
- }
- elseif (substr($row['mask'], 0, 5) == 'regex' && trim($value) != '' && preg_match(substr($row['mask'], 5), $value) === 0)
- {
- $custom_field_errors[] = array('custom_field_inproper_format', array($row['field_name']));
+ if ($row['field_type'] == 'text' && !empty($row['mask']) && $row['mask'] != 'none') {
+ if ($row['mask'] == 'email' && (!filter_var($value, FILTER_VALIDATE_EMAIL) || strlen($value) > 255)) {
+ $custom_field_errors[] = ['custom_field_invalid_email', [$row['field_name']]];
+ } elseif ($row['mask'] == 'number' && preg_match('~[^\d]~', $value)) {
+ $custom_field_errors[] = ['custom_field_not_number', [$row['field_name']]];
+ } elseif (substr($row['mask'], 0, 5) == 'regex' && trim($value) != '' && preg_match(substr($row['mask'], 5), $value) === 0) {
+ $custom_field_errors[] = ['custom_field_inproper_format', [$row['field_name']]];
}
}
}
// Is this required but not there?
- if (trim($value) == '' && $row['show_reg'] > 1)
- $custom_field_errors[] = array('custom_field_empty', array($row['field_name']));
+ if (trim($value) == '' && $row['show_reg'] > 1) {
+ $custom_field_errors[] = ['custom_field_empty', [$row['field_name']]];
+ }
}
Db::$db->free_result($request);
// Process any errors.
- if (!empty($custom_field_errors))
- {
+ if (!empty($custom_field_errors)) {
Lang::load('Errors');
- foreach ($custom_field_errors as $error)
+ foreach ($custom_field_errors as $error) {
$this->errors[] = vsprintf(Lang::$txt['error_' . $error[0]], (array) $error[1]);
+ }
}
// Lets check for other errors before trying to register the member.
- if (!empty($this->errors))
- {
+ if (!empty($this->errors)) {
$_REQUEST['step'] = 2;
$_SESSION['register']['limit'] = 5; // If they've filled in some details, they won't need the full 10 seconds of the limit.
$this->show();
+
return;
}
$member_id = self::registerMember($reg_options, true);
// What there actually an error of some kind dear boy?
- if (is_array($member_id))
- {
+ if (is_array($member_id)) {
$this->errors = array_merge($this->errors, $member_id);
$_REQUEST['step'] = 2;
$this->show();
+
return;
}
@@ -429,39 +416,33 @@ function (&$value, $key)
$pref = !empty($prefs[$member_id]['announcements']);
// Don't update if the default is the same.
- if ($var != $pref)
- {
- setNotifyPrefs($member_id, array('announcements' => (int) !empty($_POST['notify_announcements'])));
+ if ($var != $pref) {
+ Notify::setNotifyPrefs($member_id, ['announcements' => (int) !empty($_POST['notify_announcements'])]);
}
// We'll do custom fields after as then we get to use the helper function!
- if (!empty($_POST['customfield']))
- {
+ if (!empty($_POST['customfield'])) {
Profile::load($member_id);
Profile::$member->loadCustomFields('register');
Profile::$member->save();
}
// If COPPA has been selected then things get complicated, setup the template.
- if (!empty(Config::$modSettings['coppaAge']) && empty($_SESSION['skip_coppa']))
- {
+ if (!empty(Config::$modSettings['coppaAge']) && empty($_SESSION['skip_coppa'])) {
Utils::redirectexit('action=coppa;member=' . $member_id);
}
// Basic template variable setup.
- elseif (!empty(Config::$modSettings['registration_method']))
- {
+ elseif (!empty(Config::$modSettings['registration_method'])) {
Theme::loadTemplate('Register');
- Utils::$context += array(
+ Utils::$context += [
'page_title' => Lang::$txt['register'],
'title' => Lang::$txt['registration_successful'],
'sub_template' => 'after',
- 'description' => Config::$modSettings['registration_method'] == 2 ? Lang::$txt['approval_after_registration'] : Lang::$txt['activate_after_registration']
- );
- }
- else
- {
- IntegrationHook::call('integrate_activate', array($reg_options['username']));
+ 'description' => Config::$modSettings['registration_method'] == 2 ? Lang::$txt['approval_after_registration'] : Lang::$txt['activate_after_registration'],
+ ];
+ } else {
+ IntegrationHook::call('integrate_activate', [$reg_options['username']]);
Cookie::setLoginCookie(60 * Config::$modSettings['cookieTime'], $member_id, Cookie::encrypt($reg_options['register_vars']['passwd'], $reg_options['register_vars']['password_salt']));
@@ -480,8 +461,9 @@ function (&$value, $key)
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -514,143 +496,139 @@ public static function registerMember(&$reg_options, $return_errors = false)
Lang::load('Login');
// Put any errors in here.
- $reg_errors = array();
+ $reg_errors = [];
// Registration from the admin center, let them sweat a little more.
- if ($reg_options['interface'] == 'admin')
- {
+ if ($reg_options['interface'] == 'admin') {
User::$me->kickIfGuest();
User::$me->isAllowedTo('moderate_forum');
}
// If you're an admin, you're special ;).
- elseif ($reg_options['interface'] == 'guest')
- {
+ elseif ($reg_options['interface'] == 'guest') {
// You cannot register twice...
- if (empty(User::$me->is_guest))
+ if (empty(User::$me->is_guest)) {
Utils::redirectexit();
+ }
// Make sure they didn't just register with this session.
- if (!empty($_SESSION['just_registered']) && empty(Config::$modSettings['disableRegisterCheck']))
+ if (!empty($_SESSION['just_registered']) && empty(Config::$modSettings['disableRegisterCheck'])) {
ErrorHandler::fatalLang('register_only_once', false);
+ }
}
// Spaces and other odd characters are evil...
- $reg_options['username'] = trim(Utils::normalizeSpaces(Utils::sanitizeChars($reg_options['username'], 1, ' '), true, true, array('no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true)));
+ $reg_options['username'] = trim(Utils::normalizeSpaces(Utils::sanitizeChars($reg_options['username'], 1, ' '), true, true, ['no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true]));
// Convert character encoding for non-utf8mb4 database
$reg_options['username'] = Utils::htmlspecialchars($reg_options['username']);
// @todo Separate the sprintf?
- if (empty($reg_options['email']) || !filter_var($reg_options['email'], FILTER_VALIDATE_EMAIL) || strlen($reg_options['email']) > 255)
- {
- $reg_errors[] = array('lang', 'profile_error_bad_email');
+ if (empty($reg_options['email']) || !filter_var($reg_options['email'], FILTER_VALIDATE_EMAIL) || strlen($reg_options['email']) > 255) {
+ $reg_errors[] = ['lang', 'profile_error_bad_email'];
}
$username_validation_errors = User::validateUsername(0, $reg_options['username'], true, !empty($reg_options['check_reserved_name']));
- if (!empty($username_validation_errors))
+ if (!empty($username_validation_errors)) {
$reg_errors = array_merge($reg_errors, $username_validation_errors);
+ }
// Generate a validation code if it's supposed to be emailed.
$validation_code = '';
- if ($reg_options['require'] == 'activation')
+ if ($reg_options['require'] == 'activation') {
$validation_code = User::generateValidationCode();
+ }
// If you haven't put in a password generate one.
- if ($reg_options['interface'] == 'admin' && $reg_options['password'] == '')
- {
+ if ($reg_options['interface'] == 'admin' && $reg_options['password'] == '') {
$reg_options['password'] = User::generateValidationCode();
$reg_options['password_check'] = $reg_options['password'];
}
// Does the first password match the second?
- elseif ($reg_options['password'] != $reg_options['password_check'])
- {
- $reg_errors[] = array('lang', 'passwords_dont_match');
+ elseif ($reg_options['password'] != $reg_options['password_check']) {
+ $reg_errors[] = ['lang', 'passwords_dont_match'];
}
// That's kind of easy to guess...
- if ($reg_options['password'] == '')
- {
- $reg_errors[] = array('lang', 'no_password');
+ if ($reg_options['password'] == '') {
+ $reg_errors[] = ['lang', 'no_password'];
}
// Now perform hard password validation as required.
- if (!empty($reg_options['check_password_strength']) && $reg_options['password'] != '')
- {
- $password_error = User::validatePassword($reg_options['password'], $reg_options['username'], array($reg_options['email']));
+ if (!empty($reg_options['check_password_strength']) && $reg_options['password'] != '') {
+ $password_error = User::validatePassword($reg_options['password'], $reg_options['username'], [$reg_options['email']]);
// Password isn't legal?
- if ($password_error != null)
- {
- $error_code = array('lang', 'profile_error_password_' . $password_error, false);
+ if ($password_error != null) {
+ $error_code = ['lang', 'profile_error_password_' . $password_error, false];
- if ($password_error == 'short')
- $error_code[] = array(empty(Config::$modSettings['password_strength']) ? 4 : 8);
+ if ($password_error == 'short') {
+ $error_code[] = [empty(Config::$modSettings['password_strength']) ? 4 : 8];
+ }
$reg_errors[] = $error_code;
}
}
// You may not be allowed to register this email.
- if (!empty($reg_options['check_email_ban']))
- {
+ if (!empty($reg_options['check_email_ban'])) {
User::isBannedEmail($reg_options['email'], 'cannot_register', Lang::$txt['ban_register_prohibited']);
}
// Check if the email address is in use.
- $request = Db::$db->query('', '
- SELECT id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}members
WHERE email_address = {string:email_address}
OR email_address = {string:username}
LIMIT 1',
- array(
+ [
'email_address' => $reg_options['email'],
'username' => $reg_options['username'],
- )
+ ],
);
- if (Db::$db->num_rows($request) != 0)
- {
- $reg_errors[] = array('lang', 'email_in_use', false, array(Utils::htmlspecialchars($reg_options['email'])));
+
+ if (Db::$db->num_rows($request) != 0) {
+ $reg_errors[] = ['lang', 'email_in_use', false, [Utils::htmlspecialchars($reg_options['email'])]];
}
Db::$db->free_result($request);
// Perhaps someone else wants to check this user.
- IntegrationHook::call('integrate_register_check', array(&$reg_options, &$reg_errors));
+ IntegrationHook::call('integrate_register_check', [&$reg_options, &$reg_errors]);
// If we found any errors we need to do something about it right away!
- foreach ($reg_errors as $key => $error)
- {
+ foreach ($reg_errors as $key => $error) {
/* Note for each error:
0 = 'lang' if it's an index, 'done' if it's clear text.
1 = The text/index.
2 = Whether to log.
3 = sprintf data if necessary. */
- if ($error[0] == 'lang')
+ if ($error[0] == 'lang') {
Lang::load('Errors');
+ }
$message = $error[0] == 'lang' ? (empty($error[3]) ? Lang::$txt[$error[1]] : vsprintf(Lang::$txt[$error[1]], (array) $error[3])) : $error[1];
// What to do, what to do, what to do.
- if ($return_errors)
- {
- if (!empty($error[2]))
+ if ($return_errors) {
+ if (!empty($error[2])) {
ErrorHandler::log($message, $error[2]);
+ }
$reg_errors[$key] = $message;
- }
- else
- {
+ } else {
ErrorHandler::fatal($message, empty($error[2]) ? false : $error[2]);
}
}
// If there's any errors left return them at once!
- if (!empty($reg_errors))
+ if (!empty($reg_errors)) {
return $reg_errors;
+ }
- $reserved_vars = array(
+ $reserved_vars = [
'actual_theme_url',
'actual_images_url',
'base_theme_dir',
@@ -667,16 +645,15 @@ public static function registerMember(&$reg_options, $return_errors = false)
'theme_layers',
'theme_templates',
'theme_url',
- );
+ ];
// Can't change reserved vars.
- if (isset($reg_options['theme_vars']) && count(array_intersect(array_keys($reg_options['theme_vars']), $reserved_vars)) != 0)
- {
+ if (isset($reg_options['theme_vars']) && count(array_intersect(array_keys($reg_options['theme_vars']), $reserved_vars)) != 0) {
ErrorHandler::fatalLang('no_theme');
}
// Some of these might be overwritten. (the lower ones that are in the arrays below.)
- $reg_options['register_vars'] = array(
+ $reg_options['register_vars'] = [
'member_name' => $reg_options['username'],
'email_address' => $reg_options['email'],
'passwd' => Security::hashPassword($reg_options['username'], $reg_options['password']),
@@ -705,35 +682,30 @@ public static function registerMember(&$reg_options, $return_errors = false)
'ignore_boards' => '',
'smiley_set' => '',
'timezone' => empty(Config::$modSettings['default_timezone']) || !array_key_exists(Config::$modSettings['default_timezone'], TimeZone::list()) ? 'UTC' : Config::$modSettings['default_timezone'],
- );
+ ];
// Setup the activation status on this new account so it is correct - firstly is it an under age account?
- if ($reg_options['require'] == 'coppa')
- {
+ if ($reg_options['require'] == 'coppa') {
$reg_options['register_vars']['is_activated'] = 5;
// @todo This should be changed. To what should be it be changed??
$reg_options['register_vars']['validation_code'] = '';
}
// Maybe it can be activated right away?
- elseif ($reg_options['require'] == 'nothing')
- {
+ elseif ($reg_options['require'] == 'nothing') {
$reg_options['register_vars']['is_activated'] = 1;
}
// Maybe it must be activated by email?
- elseif ($reg_options['require'] == 'activation')
- {
+ elseif ($reg_options['require'] == 'activation') {
$reg_options['register_vars']['is_activated'] = 0;
}
// Otherwise it must be awaiting approval!
- else
- {
+ else {
$reg_options['register_vars']['is_activated'] = 3;
}
// Check if this group is assignable.
- if (isset($reg_options['memberGroup']))
- {
+ if (isset($reg_options['memberGroup'])) {
$reg_options['register_vars']['id_group'] = in_array($reg_options['memberGroup'], Group::getUnassignable()) ? Group::REGULAR : $reg_options['memberGroup'];
}
@@ -742,64 +714,55 @@ public static function registerMember(&$reg_options, $return_errors = false)
!empty($reg_options['extra_register_vars'])
&& !empty($reg_options['extra_register_vars']['timezone'])
&& !array_key_exists($reg_options['extra_register_vars']['timezone'], TimeZone::list())
- )
- {
+ ) {
unset($reg_options['extra_register_vars']['timezone']);
}
// Integrate optional member settings to be set.
- if (!empty($reg_options['extra_register_vars']))
- {
- foreach ($reg_options['extra_register_vars'] as $var => $value)
+ if (!empty($reg_options['extra_register_vars'])) {
+ foreach ($reg_options['extra_register_vars'] as $var => $value) {
$reg_options['register_vars'][$var] = $value;
+ }
}
// Integrate optional user theme options to be set.
- $theme_vars = array();
+ $theme_vars = [];
- if (!empty($reg_options['theme_vars']))
- {
- foreach ($reg_options['theme_vars'] as $var => $value)
+ if (!empty($reg_options['theme_vars'])) {
+ foreach ($reg_options['theme_vars'] as $var => $value) {
$theme_vars[$var] = $value;
+ }
}
// Right, now let's prepare for insertion.
- $known_ints = array(
+ $known_ints = [
'date_registered', 'posts', 'id_group', 'last_login', 'instant_messages', 'unread_messages',
'new_pm', 'pm_prefs', 'show_online',
'id_theme', 'is_activated', 'id_msg_last_visit', 'id_post_group', 'total_time_logged_in', 'warning',
- );
- $known_floats = array(
+ ];
+ $known_floats = [
'time_offset',
- );
- $known_inets = array(
+ ];
+ $known_inets = [
'member_ip', 'member_ip2',
- );
+ ];
// Call an optional function to validate the users' input.
- IntegrationHook::call('integrate_register', array(&$reg_options, &$theme_vars, &$known_ints, &$known_floats));
+ IntegrationHook::call('integrate_register', [&$reg_options, &$theme_vars, &$known_ints, &$known_floats]);
- $column_names = array();
- $values = array();
+ $column_names = [];
+ $values = [];
- foreach ($reg_options['register_vars'] as $var => $val)
- {
+ foreach ($reg_options['register_vars'] as $var => $val) {
$type = 'string';
- if (in_array($var, $known_ints))
- {
+ if (in_array($var, $known_ints)) {
$type = 'int';
- }
- elseif (in_array($var, $known_floats))
- {
+ } elseif (in_array($var, $known_floats)) {
$type = 'float';
- }
- elseif (in_array($var, $known_inets))
- {
+ } elseif (in_array($var, $known_inets)) {
$type = 'inet';
- }
- elseif ($var == 'birthdate')
- {
+ } elseif ($var == 'birthdate') {
$type = 'date';
}
@@ -808,70 +771,62 @@ public static function registerMember(&$reg_options, $return_errors = false)
}
// Register them into the database.
- $member_id = Db::$db->insert('',
+ $member_id = Db::$db->insert(
+ '',
'{db_prefix}members',
$column_names,
$values,
- array('id_member'),
- 1
+ ['id_member'],
+ 1,
);
// Call an optional function as notification of registration.
- IntegrationHook::call('integrate_post_register', array(&$reg_options, &$theme_vars, &$member_id));
+ IntegrationHook::call('integrate_post_register', [&$reg_options, &$theme_vars, &$member_id]);
// Update the number of members and latest member's info - and pass the name, but remove the 's.
- if ($reg_options['register_vars']['is_activated'] == 1)
- {
+ if ($reg_options['register_vars']['is_activated'] == 1) {
Logging::updateStats('member', $member_id, $reg_options['register_vars']['real_name']);
- }
- else
- {
+ } else {
Logging::updateStats('member');
}
// Theme variables too?
- if (!empty($theme_vars))
- {
- $inserts = array();
+ if (!empty($theme_vars)) {
+ $inserts = [];
- foreach ($theme_vars as $var => $val)
- $inserts[] = array($member_id, $var, $val);
+ foreach ($theme_vars as $var => $val) {
+ $inserts[] = [$member_id, $var, $val];
+ }
- Db::$db->insert('insert',
+ Db::$db->insert(
+ 'insert',
'{db_prefix}themes',
- array('id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
+ ['id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'],
$inserts,
- array('id_member', 'variable')
+ ['id_member', 'variable'],
);
}
// Log their acceptance of the agreement and privacy policy, for future reference.
- foreach (array('agreement_accepted', 'policy_accepted') as $key)
- {
- if (!empty($theme_vars[$key]))
- {
- Logging::logAction($key, array('member_affected' => $member_id, 'applicator' => $member_id), 'user');
+ foreach (['agreement_accepted', 'policy_accepted'] as $key) {
+ if (!empty($theme_vars[$key])) {
+ Logging::logAction($key, ['member_affected' => $member_id, 'applicator' => $member_id], 'user');
}
}
// If it's enabled, increase the registrations for today.
- Logging::trackStats(array('registers' => '+'));
+ Logging::trackStats(['registers' => '+']);
// Administrative registrations are a bit different...
- if ($reg_options['interface'] == 'admin')
- {
- if ($reg_options['require'] == 'activation')
- {
+ if ($reg_options['interface'] == 'admin') {
+ if ($reg_options['require'] == 'activation') {
$email_message = 'admin_register_activate';
- }
- elseif (!empty($reg_options['send_welcome_email']))
- {
+ } elseif (!empty($reg_options['send_welcome_email'])) {
$email_message = 'admin_register_immediate';
}
- if (isset($email_message))
- {
- $replacements = array(
+ if (isset($email_message)) {
+ $replacements = [
'REALNAME' => $reg_options['register_vars']['real_name'],
'USERNAME' => $reg_options['username'],
'PASSWORD' => $reg_options['password'],
@@ -879,7 +834,7 @@ public static function registerMember(&$reg_options, $return_errors = false)
'ACTIVATIONLINK' => Config::$scripturl . '?action=activate;u=' . $member_id . ';code=' . $validation_code,
'ACTIVATIONLINKWITHOUTCODE' => Config::$scripturl . '?action=activate;u=' . $member_id,
'ACTIVATIONCODE' => $validation_code,
- );
+ ];
$emaildata = Mail::loadEmailTemplate($email_message, $replacements);
@@ -891,16 +846,14 @@ public static function registerMember(&$reg_options, $return_errors = false)
}
// Can post straight away - welcome them to your fantastic community...
- if ($reg_options['require'] == 'nothing')
- {
- if (!empty($reg_options['send_welcome_email']))
- {
- $replacements = array(
+ if ($reg_options['require'] == 'nothing') {
+ if (!empty($reg_options['send_welcome_email'])) {
+ $replacements = [
'REALNAME' => $reg_options['register_vars']['real_name'],
'USERNAME' => $reg_options['username'],
'PASSWORD' => $reg_options['password'],
'FORGOTPASSWORDLINK' => Config::$scripturl . '?action=reminder',
- );
+ ];
$emaildata = Mail::loadEmailTemplate('register_immediate', $replacements);
@@ -911,28 +864,24 @@ public static function registerMember(&$reg_options, $return_errors = false)
Mail::adminNotify('standard', $member_id, $reg_options['username']);
}
// Need to activate their account - or fall under COPPA.
- elseif ($reg_options['require'] == 'activation' || $reg_options['require'] == 'coppa')
- {
- $replacements = array(
+ elseif ($reg_options['require'] == 'activation' || $reg_options['require'] == 'coppa') {
+ $replacements = [
'REALNAME' => $reg_options['register_vars']['real_name'],
'USERNAME' => $reg_options['username'],
'PASSWORD' => $reg_options['password'],
'FORGOTPASSWORDLINK' => Config::$scripturl . '?action=reminder',
- );
+ ];
- if ($reg_options['require'] == 'activation')
- {
- $replacements += array(
+ if ($reg_options['require'] == 'activation') {
+ $replacements += [
'ACTIVATIONLINK' => Config::$scripturl . '?action=activate;u=' . $member_id . ';code=' . $validation_code,
'ACTIVATIONLINKWITHOUTCODE' => Config::$scripturl . '?action=activate;u=' . $member_id,
'ACTIVATIONCODE' => $validation_code,
- );
- }
- else
- {
- $replacements += array(
+ ];
+ } else {
+ $replacements += [
'COPPALINK' => Config::$scripturl . '?action=coppa;member=' . $member_id,
- );
+ ];
}
$emaildata = Mail::loadEmailTemplate('register_' . ($reg_options['require'] == 'activation' ? 'activate' : 'coppa'), $replacements);
@@ -940,14 +889,13 @@ public static function registerMember(&$reg_options, $return_errors = false)
Mail::send($reg_options['email'], $emaildata['subject'], $emaildata['body'], null, 'reg_' . $reg_options['require'] . $member_id, $emaildata['is_html'], 0);
}
// Must be awaiting approval.
- else
- {
- $replacements = array(
+ else {
+ $replacements = [
'REALNAME' => $reg_options['register_vars']['real_name'],
'USERNAME' => $reg_options['username'],
'PASSWORD' => $reg_options['password'],
'FORGOTPASSWORDLINK' => Config::$scripturl . '?action=reminder',
- );
+ ];
$emaildata = Mail::loadEmailTemplate('register_pending', $replacements);
@@ -961,7 +909,7 @@ public static function registerMember(&$reg_options, $return_errors = false)
$_SESSION['just_registered'] = 1;
// If they are for sure registered, let other people to know about it
- IntegrationHook::call('integrate_register_after', array($reg_options, $member_id));
+ IntegrationHook::call('integrate_register_after', [$reg_options, $member_id]);
return $member_id;
}
@@ -975,12 +923,12 @@ public static function registerMember(&$reg_options, $return_errors = false)
*/
protected function __construct()
{
-
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Register2::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Register2::exportStatic')) {
Register2::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Reminder.php b/Sources/Actions/Reminder.php
index 9d62ebf9cf..35f02e2cc0 100644
--- a/Sources/Actions/Reminder.php
+++ b/Sources/Actions/Reminder.php
@@ -14,7 +14,6 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
@@ -25,7 +24,6 @@
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Handle sending out reminders, and checking the secret answer and question.
@@ -39,12 +37,11 @@ class Reminder implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'RemindMe',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -78,13 +75,13 @@ class Reminder implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'main' => 'main',
'picktype' => 'pickType',
'secret2' => 'secretAnswer2',
'setpassword' => 'setPassword',
- 'setpassword2' => 'setPassword2'
- );
+ 'setpassword2' => 'setPassword2',
+ ];
/****************************
* Internal static properties
@@ -107,10 +104,11 @@ class Reminder 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);
+ }
}
/**
@@ -132,51 +130,47 @@ public function pickType()
// Make sure we are not being slammed
// Don't call this if you're coming from the "Choose a reminder type" page - otherwise you'll likely get an error
- if (!in_array($_POST['reminder_type'] ?? null, array('email', 'secret')))
+ if (!in_array($_POST['reminder_type'] ?? null, ['email', 'secret'])) {
Security::spamProtection('remind');
+ }
$this->loadMember();
// If the user isn't activated/approved, give them some feedback on what to do next.
- if ($this->member->is_activated != 1)
- {
+ if ($this->member->is_activated != 1) {
// Awaiting approval...
- if (trim($this->member->validation_code) == '')
- {
+ if (trim($this->member->validation_code) == '') {
ErrorHandler::fatal(sprintf(Lang::$txt['registration_not_approved'], Config::$scripturl . '?action=activate;user=' . $_POST['user']), false);
- }
- else
- {
+ } else {
ErrorHandler::fatal(sprintf(Lang::$txt['registration_not_activated'], Config::$scripturl . '?action=activate;user=' . $_POST['user']), false);
}
}
// You can't get emailed if you have no email address.
$this->member->email = trim($this->member->email);
- if ($this->member->email == '')
- {
+
+ if ($this->member->email == '') {
ErrorHandler::fatal(Lang::$txt['no_reminder_email'] . ' ' . Lang::$txt['send_email_to'] . ' ' . Lang::$txt['webmaster'] . ' ' . Lang::$txt['to_ask_password']);
}
// If they have no secret question then they can only get emailed the item, or they are requesting the email, send them an email.
- if (empty($this->member->secret_question) || (isset($_POST['reminder_type']) && $_POST['reminder_type'] == 'email'))
- {
+ if (empty($this->member->secret_question) || (isset($_POST['reminder_type']) && $_POST['reminder_type'] == 'email')) {
// Randomly generate a validation code with a max length of 10 chars.
$code = User::generateValidationCode();
- $replacements = array(
+ $replacements = [
'REALNAME' => $this->member->name,
'REMINDLINK' => Config::$scripturl . '?action=reminder;sa=setpassword;u=' . $this->member->id . ';code=' . $code,
'IP' => User::$me->ip,
'MEMBERNAME' => $this->member->username,
- );
+ ];
$emaildata = Mail::loadEmailTemplate('forgot_password', $replacements, empty($this->member->lngfile) || empty(Config::$modSettings['userLanguage']) ? Lang::$default : $this->member->lngfile);
Mail::send($this->member->email, $emaildata['subject'], $emaildata['body'], null, 'reminder', $emaildata['is_html'], 1);
// Set the validation code in the database.
- User::updateMemberData($this->member->id, array('validation_code' => substr(md5($code), 0, 10)));
+ User::updateMemberData($this->member->id, ['validation_code' => substr(md5($code), 0, 10)]);
// Set up the template.
Utils::$context['description'] = Lang::$txt['reminder_sent'];
@@ -185,18 +179,18 @@ public function pickType()
// Don't really.
return;
}
+
// Otherwise are ready to answer the question?
- elseif (isset($_POST['reminder_type']) && $_POST['reminder_type'] == 'secret')
- {
+ if (isset($_POST['reminder_type']) && $_POST['reminder_type'] == 'secret') {
return self::secretAnswerInput();
}
// Now we're here setup the context for template number 2!
Utils::$context['sub_template'] = 'reminder_pick';
- Utils::$context['current_member'] = array(
+ Utils::$context['current_member'] = [
'id' => $this->member->id,
'name' => $this->member->username,
- );
+ ];
}
/**
@@ -207,18 +201,19 @@ public function setPassword()
Lang::load('Login');
// You need a code!
- if (!isset($_REQUEST['code']))
+ if (!isset($_REQUEST['code'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
// Fill the context array.
- Utils::$context += array(
+ Utils::$context += [
'page_title' => Lang::$txt['reminder_set_password'],
'sub_template' => 'set_password',
'code' => $_REQUEST['code'],
- 'memID' => (int) $_REQUEST['u']
- );
+ 'memID' => (int) $_REQUEST['u'],
+ ];
- Theme::loadJavaScriptFile('register.js', array('defer' => false, 'minimize' => true), 'smf_register');
+ Theme::loadJavaScriptFile('register.js', ['defer' => false, 'minimize' => true], 'smf_register');
// Tokens!
SecurityToken::create('remind-sp');
@@ -232,40 +227,38 @@ public function setPassword2()
User::$me->checkSession();
SecurityToken::validate('remind-sp');
- if (empty($_POST['u']) || !isset($_POST['passwrd1']) || !isset($_POST['passwrd2']))
+ if (empty($_POST['u']) || !isset($_POST['passwrd1']) || !isset($_POST['passwrd2'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
$_POST['u'] = (int) $_POST['u'];
- if ($_POST['passwrd1'] != $_POST['passwrd2'])
+ if ($_POST['passwrd1'] != $_POST['passwrd2']) {
ErrorHandler::fatalLang('passwords_dont_match', false);
+ }
- if ($_POST['passwrd1'] == '')
+ if ($_POST['passwrd1'] == '') {
ErrorHandler::fatalLang('no_password', false);
+ }
Lang::load('Login');
$this->loadMember();
// Is the password actually valid?
- $passwordError = User::validatePassword($_POST['passwrd1'], $this->member->username, array($this->member->email));
+ $passwordError = User::validatePassword($_POST['passwrd1'], $this->member->username, [$this->member->email]);
// What - it's not?
- if ($passwordError != null)
- {
- if ($passwordError == 'short')
- {
- ErrorHandler::fatalLang('profile_error_password_' . $passwordError, false, array(empty(Config::$modSettings['password_strength']) ? 4 : 8));
- }
- else
- {
+ if ($passwordError != null) {
+ if ($passwordError == 'short') {
+ ErrorHandler::fatalLang('profile_error_password_' . $passwordError, false, [empty(Config::$modSettings['password_strength']) ? 4 : 8]);
+ } else {
ErrorHandler::fatalLang('profile_error_password_' . $passwordError, false);
}
}
// Quit if this code is not right.
- if (empty($_POST['code']) || substr($this->member->validation_code, 0, 10) !== substr(md5($_POST['code']), 0, 10))
- {
+ if (empty($_POST['code']) || substr($this->member->validation_code, 0, 10) !== substr(md5($_POST['code']), 0, 10)) {
// Stop brute force attacks like this.
Login2::validatePasswordFlood($this->member->id, $this->member->username, $this->member->passwd_flood, false);
@@ -276,19 +269,19 @@ public function setPassword2()
Login2::validatePasswordFlood($this->member->id, $this->member->username, $this->member->passwd_flood, true);
// User validated. Update the database!
- User::updateMemberData($this->member->id, array('validation_code' => '', 'passwd' => Security::hashPassword($this->member->username, $_POST['passwrd1'])));
+ User::updateMemberData($this->member->id, ['validation_code' => '', 'passwd' => Security::hashPassword($this->member->username, $_POST['passwrd1'])]);
- IntegrationHook::call('integrate_reset_pass', array($this->member->username, $this->member->username, $_POST['passwrd1']));
+ IntegrationHook::call('integrate_reset_pass', [$this->member->username, $this->member->username, $_POST['passwrd1']]);
Theme::loadTemplate('Login');
- Utils::$context += array(
+ Utils::$context += [
'page_title' => Lang::$txt['reminder_password_set'],
'sub_template' => 'login',
'default_username' => $this->member->username,
'default_password' => $_POST['passwrd1'],
'never_expire' => false,
- 'description' => Lang::$txt['reminder_password_set']
- );
+ 'description' => Lang::$txt['reminder_password_set'],
+ ];
SecurityToken::create('login');
}
@@ -304,12 +297,14 @@ public function secretAnswerInput()
Lang::load('Login');
// This should never happen, but just in case...
- if (!isset($this->member))
+ if (!isset($this->member)) {
$this->loadMember();
+ }
// If there is NO secret question - then throw an error.
- if (trim($this->member->secret_question) == '')
+ if (trim($this->member->secret_question) == '') {
ErrorHandler::fatalLang('registration_no_secret_question', false);
+ }
// Ask for the answer...
Utils::$context['remind_user'] = $this->member->id_member;
@@ -318,7 +313,7 @@ public function secretAnswerInput()
Utils::$context['sub_template'] = 'ask';
SecurityToken::create('remind-sai');
- Theme::loadJavaScriptFile('register.js', array('defer' => false, 'minimize' => true), 'smf_register');
+ Theme::loadJavaScriptFile('register.js', ['defer' => false, 'minimize' => true], 'smf_register');
}
/**
@@ -330,8 +325,9 @@ public function secretAnswer2()
SecurityToken::validate('remind-sai');
// Hacker? How did you get this far without an email or username?
- if (empty($_REQUEST['uid']))
+ if (empty($_REQUEST['uid'])) {
ErrorHandler::fatalLang('username_no_exist', false);
+ }
Lang::load('Login');
@@ -357,57 +353,53 @@ public function secretAnswer2()
!Security::hashVerifyPassword($this->member->username, $_POST['secret_answer'], $this->member->secret_answer)
&& md5($_POST['secret_answer']) != $this->member->secret_answer
)
- )
- {
+ ) {
ErrorHandler::log(sprintf(Lang::$txt['reminder_error'], $this->member->username), 'user');
ErrorHandler::fatalLang('incorrect_answer', false);
}
// If the secret answer was right, but stored using md5, upgrade it now.
- if (md5($_POST['secret_answer']) === $this->member->secret_answer)
- {
- User::updateMemberData($this->member->id_member, array('secret_answer' => Security::hashPassword($this->member->username, $_POST['secret_answer'])));
+ if (md5($_POST['secret_answer']) === $this->member->secret_answer) {
+ User::updateMemberData($this->member->id_member, ['secret_answer' => Security::hashPassword($this->member->username, $_POST['secret_answer'])]);
}
// You can't use a blank one!
- if (strlen(trim($_POST['passwrd1'])) === 0)
+ if (strlen(trim($_POST['passwrd1'])) === 0) {
ErrorHandler::fatalLang('no_password', false);
+ }
// They have to be the same too.
- if ($_POST['passwrd1'] != $_POST['passwrd2'])
+ if ($_POST['passwrd1'] != $_POST['passwrd2']) {
ErrorHandler::fatalLang('passwords_dont_match', false);
+ }
// Make sure they have a strong enough password.
- $passwordError = User::validatePassword($_POST['passwrd1'], $this->member->username, array($this->member->email));
+ $passwordError = User::validatePassword($_POST['passwrd1'], $this->member->username, [$this->member->email]);
// Invalid?
- if ($passwordError != null)
- {
- if ($passwordError == 'short')
- {
- ErrorHandler::fatalLang('profile_error_password_' . $passwordError, false, array(empty(Config::$modSettings['password_strength']) ? 4 : 8));
- }
- else
- {
+ if ($passwordError != null) {
+ if ($passwordError == 'short') {
+ ErrorHandler::fatalLang('profile_error_password_' . $passwordError, false, [empty(Config::$modSettings['password_strength']) ? 4 : 8]);
+ } else {
ErrorHandler::fatalLang('profile_error_password_' . $passwordError, false);
}
}
// Alright, so long as 'yer sure.
- User::updateMemberData($this->member->id_member, array('passwd' => Security::hashPassword($this->member->username, $_POST['passwrd1'])));
+ User::updateMemberData($this->member->id_member, ['passwd' => Security::hashPassword($this->member->username, $_POST['passwrd1'])]);
- IntegrationHook::call('integrate_reset_pass', array($this->member->username, $this->member->username, $_POST['passwrd1']));
+ IntegrationHook::call('integrate_reset_pass', [$this->member->username, $this->member->username, $_POST['passwrd1']]);
// Tell them it went fine.
Theme::loadTemplate('Login');
- Utils::$context += array(
+ Utils::$context += [
'page_title' => Lang::$txt['reminder_password_set'],
'sub_template' => 'login',
'default_username' => $this->member->username,
'default_password' => $_POST['passwrd1'],
'never_expire' => false,
- 'description' => Lang::$txt['reminder_password_set']
- );
+ 'description' => Lang::$txt['reminder_password_set'],
+ ];
SecurityToken::create('login');
}
@@ -423,8 +415,9 @@ public function secretAnswer2()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -452,8 +445,9 @@ protected function __construct()
Utils::$context['page_title'] = Lang::$txt['authentication_reminder'];
Utils::$context['robot_no_index'] = true;
- if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
+ if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
+ }
}
/**
@@ -461,41 +455,43 @@ protected function __construct()
*/
protected function loadMember()
{
- $loaded = array();
+ $loaded = [];
$err_msg = 'username_no_exist';
// Coming with a known ID?
$uid = intval(!empty($_REQUEST['uid']) ? $_REQUEST['uid'] : (!empty($_POST['u']) ? $_POST['u'] : 0));
// If given a name or email, clean it up like we do during registration.
- if (isset($_POST['user']))
- $_POST['user'] = Utils::htmlTrim(Utils::normalizeSpaces(Utils::sanitizeChars($_POST['user'], 1, ' '), true, true, array('no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true)));
+ if (isset($_POST['user'])) {
+ $_POST['user'] = Utils::htmlTrim(Utils::normalizeSpaces(Utils::sanitizeChars($_POST['user'], 1, ' '), true, true, ['no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true]));
+ }
// Load by ID.
- if (!empty($uid))
- {
+ if (!empty($uid)) {
$err_msg = 'invalid_userid';
$loaded = User::load($uid, User::LOAD_BY_ID, 'minimal');
}
// Load by name or email.
- elseif (isset($_POST['user']) && $_POST['user'] != '')
- {
+ elseif (isset($_POST['user']) && $_POST['user'] != '') {
$loaded = User::load($_POST['user'], User::LOAD_BY_NAME, 'minimal');
- if (empty($loaded))
+ if (empty($loaded)) {
$loaded = User::load($_POST['user'], User::LOAD_BY_EMAIL, 'minimal');
+ }
}
// Nothing found.
- if (empty($loaded))
+ if (empty($loaded)) {
ErrorHandler::fatalLang($err_msg, false);
+ }
$this->member = reset($loaded);
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Reminder::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Reminder::exportStatic')) {
Reminder::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/ReportToMod.php b/Sources/Actions/ReportToMod.php
index 2c766f0edf..77f2af0afc 100644
--- a/Sources/Actions/ReportToMod.php
+++ b/Sources/Actions/ReportToMod.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\Lang;
use SMF\Msg;
@@ -24,7 +24,6 @@
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Deals with reporting posts or profiles to mods and admins.
@@ -38,12 +37,14 @@ class ReportToMod implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ReportToModerator',
- ),
- );
+ 'ReportToModerator2' => 'ReportToModerator2',
+ 'reportPost' => 'reportPost',
+ 'reportUser' => 'reportUser',
+ ],
+ ];
/*****************
* Class constants
@@ -72,10 +73,10 @@ class ReportToMod implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'show' => 'show',
'submit' => 'submit',
- );
+ ];
/*********************
* Internal properties
@@ -135,19 +136,17 @@ public function execute(): void
// You can't use this if it's off or you are not allowed to do it.
// If we don't have the ID of something to report, we'll die with a no_access error below
- if (isset($_REQUEST['msg']))
- {
+ if (isset($_REQUEST['msg'])) {
User::$me->isAllowedTo('report_any');
- }
- elseif (isset($_REQUEST['u']))
- {
+ } elseif (isset($_REQUEST['u'])) {
User::$me->isAllowedTo('report_user');
}
- $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);
+ }
}
/**
@@ -160,47 +159,49 @@ public function execute(): void
public function show(): void
{
// Previewing or modifying?
- if ($this->previewing)
+ if ($this->previewing) {
$this->setPreview();
+ }
// We need a message ID or user ID to check!
- if (empty($_REQUEST['msg']) && empty($_REQUEST['mid']) && empty($_REQUEST['u']))
+ if (empty($_REQUEST['msg']) && empty($_REQUEST['mid']) && empty($_REQUEST['u'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
// For compatibility, accept mid, but we should be using msg. (not the flavor kind!)
- if (!empty($_REQUEST['msg']) || !empty($_REQUEST['mid']))
- {
+ if (!empty($_REQUEST['msg']) || !empty($_REQUEST['mid'])) {
$_REQUEST['msg'] = empty($_REQUEST['msg']) ? (int) $_REQUEST['mid'] : (int) $_REQUEST['msg'];
}
// msg and mid empty - assume we're reporting a user
- elseif (!empty($_REQUEST['u']))
- {
+ elseif (!empty($_REQUEST['u'])) {
$_REQUEST['u'] = (int) $_REQUEST['u'];
}
// Set up some form values
Utils::$context['report_type'] = isset($_REQUEST['msg']) ? 'msg' : 'u';
- Utils::$context['reported_item'] = isset($_REQUEST['msg']) ? $_REQUEST['msg'] : $_REQUEST['u'];
+ Utils::$context['reported_item'] = $_REQUEST['msg'] ?? $_REQUEST['u'];
- if (isset($_REQUEST['msg']))
- {
+ if (isset($_REQUEST['msg'])) {
// Check the message's ID - don't want anyone reporting a post they can't even see!
- $result = Db::$db->query('', '
- SELECT m.id_msg, m.id_member, t.id_member_started
+ $result = Db::$db->query(
+ '',
+ 'SELECT m.id_msg, m.id_member, t.id_member_started
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})
WHERE m.id_msg = {int:id_msg}
AND m.id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
'id_msg' => $_REQUEST['msg'],
- )
+ ],
);
- if (Db::$db->num_rows($result) == 0)
+
+ if (Db::$db->num_rows($result) == 0) {
ErrorHandler::fatalLang('no_board', false);
+ }
- list ($_REQUEST['msg'], $member, $starter) = Db::$db->fetch_row($result);
+ list($_REQUEST['msg'], $member, $starter) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
// This is here so that the user could, in theory, be redirected back to the topic.
@@ -209,21 +210,21 @@ public function show(): void
// The submit URL is different for users than it is for posts
Utils::$context['submit_url'] = Config::$scripturl . '?action=reporttm;msg=' . $_REQUEST['msg'] . ';topic=' . Topic::$topic_id;
- }
- else
- {
+ } else {
// Check the user's ID
- $result = Db::$db->query('', '
- SELECT id_member, real_name, member_name
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name, member_name
FROM {db_prefix}members
WHERE id_member = {int:current_user}',
- array(
+ [
'current_user' => $_REQUEST['u'],
- )
+ ],
);
- if (Db::$db->num_rows($result) == 0)
+ if (Db::$db->num_rows($result) == 0) {
ErrorHandler::fatalLang('no_user', false);
+ }
list($_REQUEST['u'], $display_name, $username) = Db::$db->fetch_row($result);
@@ -276,39 +277,41 @@ public function submit(): void
Security::checkSubmitOnce('check');
// No errors, yet.
- $post_errors = array();
+ $post_errors = [];
// Check their session.
- if (User::$me->checkSession('post', '', false) != '')
+ if (User::$me->checkSession('post', '', false) != '') {
$post_errors[] = 'session_timeout';
+ }
// Make sure we have a comment and it's clean.
- if ($this->comment === '')
+ if ($this->comment === '') {
$post_errors[] = 'no_comment';
+ }
- if (Utils::entityStrlen(Utils::htmlspecialchars($this->comment)) > 254)
+ if (Utils::entityStrlen(Utils::htmlspecialchars($this->comment)) > 254) {
$post_errors[] = 'post_too_long';
+ }
// Any errors?
- if (!empty($post_errors))
- {
+ if (!empty($post_errors)) {
Lang::load('Errors');
- Utils::$context['post_errors'] = array();
- foreach ($post_errors as $post_error)
+ Utils::$context['post_errors'] = [];
+
+ foreach ($post_errors as $post_error) {
Utils::$context['post_errors'][$post_error] = Lang::$txt['error_' . $post_error];
+ }
$this->previewing = false;
$this->show();
+
return;
}
- if (isset($_POST['msg']))
- {
+ if (isset($_POST['msg'])) {
$this->reportMsg($_POST['msg']);
- }
- else
- {
+ } else {
$this->reportMember($_POST['u']);
}
}
@@ -324,8 +327,9 @@ public function submit(): void
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -389,15 +393,17 @@ protected function __construct()
Utils::$context['robot_no_index'] = true;
Utils::$context['comment_body'] = '';
- if (isset($_POST['comment']))
+ if (isset($_POST['comment'])) {
$this->comment = trim(Utils::normalizeSpaces(Utils::sanitizeChars(Utils::normalize($_POST['comment']), 0), true, true));
+ }
$this->previewing = isset($_POST['preview']) && $this->comment !== '';
$this->submitting = isset($_POST['save']);
$this->can_submit = isset($_POST[Utils::$context['session_var']]);
- if ($this->submitting && $this->can_submit && !$this->previewing)
+ if ($this->submitting && $this->can_submit && !$this->previewing) {
$this->subaction = 'submit';
+ }
}
/**
@@ -421,114 +427,133 @@ protected function setPreview()
protected function reportMsg(int $msg)
{
// Get the basic topic information, and make sure they can see it.
- $request = Db::$db->query('', '
- SELECT m.id_topic, m.id_board, m.subject, m.body, m.id_member AS id_poster, m.poster_name, mem.real_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_topic, m.id_board, m.subject, m.body, m.id_member AS id_poster, m.poster_name, mem.real_name
FROM {db_prefix}messages AS m
LEFT JOIN {db_prefix}members AS mem ON (m.id_member = mem.id_member)
WHERE m.id_msg = {int:id_msg}
AND m.id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
'id_msg' => $msg,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
+
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('no_board', false);
+ }
$message = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
- $request = Db::$db->query('', '
- SELECT id_report, ignore_all
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_report, ignore_all
FROM {db_prefix}log_reported
WHERE id_msg = {int:id_msg}
AND (closed = {int:not_closed} OR ignore_all = {int:ignored})
ORDER BY ignore_all DESC',
- array(
+ [
'id_msg' => $msg,
'not_closed' => 0,
'ignored' => 1,
- )
+ ],
);
- if (Db::$db->num_rows($request) != 0)
- list ($id_report, $ignore) = Db::$db->fetch_row($request);
+
+ if (Db::$db->num_rows($request) != 0) {
+ list($id_report, $ignore) = Db::$db->fetch_row($request);
+ }
Db::$db->free_result($request);
// If we're just going to ignore these, then who gives a monkeys...
- if (!empty($ignore))
+ if (!empty($ignore)) {
Utils::redirectexit('topic=' . Topic::$topic_id . '.msg' . $msg . '#msg' . $msg);
+ }
// Already reported? My god, we could be dealing with a real rogue here...
- if (!empty($id_report))
- Db::$db->query('', '
- UPDATE {db_prefix}log_reported
+ if (!empty($id_report)) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_reported
SET num_reports = num_reports + 1, time_updated = {int:current_time}
WHERE id_report = {int:id_report}',
- array(
+ [
'current_time' => time(),
'id_report' => $id_report,
- )
+ ],
);
+ }
// Otherwise, we shall make one!
- else
- {
- if (empty($message['real_name']))
+ else {
+ if (empty($message['real_name'])) {
$message['real_name'] = $message['poster_name'];
+ }
- $id_report = Db::$db->insert('',
+ $id_report = Db::$db->insert(
+ '',
'{db_prefix}log_reported',
- array(
+ [
'id_msg' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'id_member' => 'int', 'membername' => 'string',
'subject' => 'string', 'body' => 'string', 'time_started' => 'int', 'time_updated' => 'int',
'num_reports' => 'int', 'closed' => 'int',
- ),
- array(
+ ],
+ [
$msg, $message['id_topic'], $message['id_board'], $message['id_poster'], $message['real_name'],
$message['subject'], $message['body'], time(), time(), 1, 0,
- ),
- array('id_report'),
- 1
+ ],
+ ['id_report'],
+ 1,
);
}
// Now just add our report...
- if ($id_report)
- {
- $id_comment = Db::$db->insert('',
+ if ($id_report) {
+ $id_comment = Db::$db->insert(
+ '',
'{db_prefix}log_reported_comments',
- array(
+ [
'id_report' => 'int', 'id_member' => 'int', 'membername' => 'string',
'member_ip' => 'inet', 'comment' => 'string', 'time_sent' => 'int',
- ),
- array(
+ ],
+ [
$id_report, User::$me->id, User::$me->name,
User::$me->ip, Utils::htmlspecialchars($this->comment), time(),
- ),
- array('id_comment'),
- 1
+ ],
+ ['id_comment'],
+ 1,
);
// And get ready to notify people.
- Db::$db->insert('insert',
+ Db::$db->insert(
+ 'insert',
'{db_prefix}background_tasks',
- array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
- array('$sourcedir/tasks/MsgReport_Notify.php', 'SMF\Tasks\MsgReport_Notify', Utils::jsonEncode(array(
- 'report_id' => $id_report,
- 'msg_id' => $msg,
- 'topic_id' => $message['id_topic'],
- 'board_id' => $message['id_board'],
- 'sender_id' => User::$me->id,
- 'sender_name' => User::$me->name,
- 'time' => time(),
- 'comment_id' => $id_comment,
- )), 0),
- array('id_task')
+ [
+ 'task_class' => 'string',
+ 'task_data' => 'string',
+ 'claimed_time' => 'int',
+ ],
+ [
+ 'SMF\\Tasks\\MsgReport_Notify',
+ Utils::jsonEncode([
+ 'report_id' => $id_report,
+ 'msg_id' => $msg,
+ 'topic_id' => $message['id_topic'],
+ 'board_id' => $message['id_board'],
+ 'sender_id' => User::$me->id,
+ 'sender_name' => User::$me->name,
+ 'time' => time(),
+ 'comment_id' => $id_comment,
+ ]),
+ 0,
+ ],
+ ['id_task'],
);
}
// Keep track of when the mod reports get updated, that way we know when we need to look again.
- Config::updateModSettings(array('last_mod_report_action' => time()));
+ Config::updateModSettings(['last_mod_report_action' => time()]);
// Back to the post we reported!
Utils::redirectexit('reportsent;topic=' . Topic::$topic_id . '.msg' . $msg . '#msg' . $msg);
@@ -544,109 +569,127 @@ protected function reportMember($id_member)
// Get the basic topic information, and make sure they can see it.
$_POST['u'] = (int) $id_member;
- $request = Db::$db->query('', '
- SELECT id_member, real_name, member_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name, member_name
FROM {db_prefix}members
WHERE id_member = {int:id_member}',
- array(
- 'id_member' => $_POST['u']
- )
+ [
+ 'id_member' => $_POST['u'],
+ ],
);
- if (Db::$db->num_rows($request) == 0)
+
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('no_user', false);
+ }
$user = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
$user_name = Utils::htmlspecialcharsDecode($user['real_name']) . ($user['real_name'] != $user['member_name'] ? ' (' . $user['member_name'] . ')' : '');
- $request = Db::$db->query('', '
- SELECT id_report, ignore_all
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_report, ignore_all
FROM {db_prefix}log_reported
WHERE id_member = {int:id_member}
AND id_msg = {int:not_a_reported_post}
AND (closed = {int:not_closed} OR ignore_all = {int:ignored})
ORDER BY ignore_all DESC',
- array(
+ [
'id_member' => $_POST['u'],
'not_a_reported_post' => 0,
'not_closed' => 0,
'ignored' => 1,
- )
+ ],
);
- if (Db::$db->num_rows($request) != 0)
- list ($id_report, $ignore) = Db::$db->fetch_row($request);
+
+ if (Db::$db->num_rows($request) != 0) {
+ list($id_report, $ignore) = Db::$db->fetch_row($request);
+ }
Db::$db->free_result($request);
// If we're just going to ignore these, then who gives a monkeys...
- if (!empty($ignore))
+ if (!empty($ignore)) {
Utils::redirectexit('action=profile;u=' . $_POST['u']);
+ }
// Already reported? My god, we could be dealing with a real rogue here...
- if (!empty($id_report))
- Db::$db->query('', '
- UPDATE {db_prefix}log_reported
+ if (!empty($id_report)) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_reported
SET num_reports = num_reports + 1, time_updated = {int:current_time}
WHERE id_report = {int:id_report}',
- array(
+ [
'current_time' => time(),
'id_report' => $id_report,
- )
+ ],
);
+ }
// Otherwise, we shall make one!
- else
- {
- $id_report = Db::$db->insert('',
+ else {
+ $id_report = Db::$db->insert(
+ '',
'{db_prefix}log_reported',
- array(
+ [
'id_msg' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'id_member' => 'int', 'membername' => 'string',
'subject' => 'string', 'body' => 'string', 'time_started' => 'int', 'time_updated' => 'int',
'num_reports' => 'int', 'closed' => 'int',
- ),
- array(
+ ],
+ [
0, 0, 0, $user['id_member'], $user_name,
'', '', time(), time(), 1, 0,
- ),
- array('id_report'),
- 1
+ ],
+ ['id_report'],
+ 1,
);
}
// Now just add our report...
- if ($id_report)
- {
- Db::$db->insert('',
+ if ($id_report) {
+ Db::$db->insert(
+ '',
'{db_prefix}log_reported_comments',
- array(
+ [
'id_report' => 'int', 'id_member' => 'int', 'membername' => 'string',
'member_ip' => 'inet', 'comment' => 'string', 'time_sent' => 'int',
- ),
- array(
+ ],
+ [
$id_report, User::$me->id, User::$me->name,
User::$me->ip, Utils::htmlspecialchars($this->comment), time(),
- ),
- array('id_comment')
+ ],
+ ['id_comment'],
);
// And get ready to notify people.
- Db::$db->insert('insert',
+ Db::$db->insert(
+ 'insert',
'{db_prefix}background_tasks',
- array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
- array('$sourcedir/tasks/MemberReport_Notify.php', 'SMF\Tasks\MemberReport_Notify', Utils::jsonEncode(array(
- 'report_id' => $id_report,
- 'user_id' => $user['id_member'],
- 'user_name' => $user_name,
- 'sender_id' => User::$me->id,
- 'sender_name' => User::$me->name,
- 'comment' => Utils::htmlspecialchars($this->comment),
- 'time' => time(),
- )), 0),
- array('id_task')
+ [
+ 'task_class' => 'string',
+ 'task_data' => 'string',
+ 'claimed_time' => 'int',
+ ],
+ [
+ 'SMF\\Tasks\\MemberReport_Notify',
+ Utils::jsonEncode([
+ 'report_id' => $id_report,
+ 'user_id' => $user['id_member'],
+ 'user_name' => $user_name,
+ 'sender_id' => User::$me->id,
+ 'sender_name' => User::$me->name,
+ 'comment' => Utils::htmlspecialchars($this->comment),
+ 'time' => time(),
+ ]),
+ 0,
+ ],
+ ['id_task'],
);
}
// Keep track of when the mod reports get updated, that way we know when we need to look again.
- Config::updateModSettings(array('last_mod_report_action' => time()));
+ Config::updateModSettings(['last_mod_report_action' => time()]);
// Back to the profile we reported!
Utils::redirectexit('reportsent;action=profile;u=' . $id_member);
@@ -654,7 +697,8 @@ protected function reportMember($id_member)
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ReportToMod::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ReportToMod::exportStatic')) {
ReportToMod::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/RequestMembers.php b/Sources/Actions/RequestMembers.php
index 6e614bfd37..a7ae71351c 100644
--- a/Sources/Actions/RequestMembers.php
+++ b/Sources/Actions/RequestMembers.php
@@ -14,10 +14,9 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
+use SMF\Db\DatabaseApi as Db;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Outputs each member name on its own line.
@@ -36,12 +35,11 @@ class RequestMembers implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'RequestMembers',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -77,31 +75,33 @@ public function execute(): void
{
User::$me->checkSession('get');
- if (Utils::$context['utf8'] || function_exists('mb_convert_encoding'))
+ if (Utils::$context['utf8'] || function_exists('mb_convert_encoding')) {
header('content-type: text/plain; charset=UTF-8');
+ }
- $request = Db::$db->query('', '
- SELECT real_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT real_name
FROM {db_prefix}members
WHERE {raw:real_name} LIKE {string:search}' . (isset($_REQUEST['buddies']) ? '
AND id_member IN ({array_int:buddy_list})' : '') . '
AND is_activated IN (1, 11)
LIMIT ' . (Utils::entityStrlen($this->search) <= 2 ? '100' : '800'),
- array(
+ [
'real_name' => Db::$db->case_sensitive ? 'LOWER(real_name)' : 'real_name',
'buddy_list' => User::$me->buddies,
'search' => $this->search,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (!Utils::$context['utf8'])
- {
- if (($temp = @mb_convert_encoding($row['real_name'], 'UTF-8', Utils::$context['character_set'])) !== false)
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (!Utils::$context['utf8']) {
+ if (($temp = @mb_convert_encoding($row['real_name'], 'UTF-8', Utils::$context['character_set'])) !== false) {
$row['real_name'] = $temp;
+ }
}
- $row['real_name'] = strtr($row['real_name'], array('&' => '&', '<' => '<', '>' => '>', '"' => '"'));
+ $row['real_name'] = strtr($row['real_name'], ['&' => '&', '<' => '<', '>' => '>', '"' => '"']);
$row['real_name'] = Utils::entityDecode($row['real_name'], true);
@@ -123,8 +123,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;
}
@@ -150,12 +151,13 @@ protected function __construct()
$this->search = Utils::htmlspecialchars($this->search);
$this->search = trim(Utils::strtolower($this->search)) . '*';
- $this->search = strtr($this->search, array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '&' => '&'));
+ $this->search = strtr($this->search, ['%' => '\\%', '_' => '\\_', '*' => '%', '?' => '_', '&' => '&']);
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\RequestMembers::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\RequestMembers::exportStatic')) {
RequestMembers::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Search.php b/Sources/Actions/Search.php
index 761d1cdb7c..84657a0681 100644
--- a/Sources/Actions/Search.php
+++ b/Sources/Actions/Search.php
@@ -14,18 +14,17 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Category;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
+use SMF\Search\SearchApi;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
use SMF\Verifier;
-use SMF\Db\DatabaseApi as Db;
-use SMF\Search\SearchApi;
/**
* Shows the search form.
@@ -39,12 +38,11 @@ class Search implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'PlushSearch1',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -76,94 +74,94 @@ class Search implements ActionInterface
public function execute(): void
{
// Is the load average too high to allow searching just now?
- if (!empty(Utils::$context['load_average']) && !empty(Config::$modSettings['loadavg_search']) && Utils::$context['load_average'] >= Config::$modSettings['loadavg_search'])
- {
+ if (!empty(Utils::$context['load_average']) && !empty(Config::$modSettings['loadavg_search']) && Utils::$context['load_average'] >= Config::$modSettings['loadavg_search']) {
ErrorHandler::fatalLang('loadavg_search_disabled', false);
}
Lang::load('Search');
// Don't load this in XML mode.
- if (!isset($_REQUEST['xml']))
- {
+ if (!isset($_REQUEST['xml'])) {
Theme::loadTemplate('Search');
- Theme::loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
+ Theme::loadJavaScriptFile('suggest.js', ['defer' => false, 'minimize' => true], 'smf_suggest');
}
// Check the user's permissions.
User::$me->isAllowedTo('search_posts');
// Link tree....
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=search',
- 'name' => Lang::$txt['search']
- );
+ 'name' => Lang::$txt['search'],
+ ];
Utils::$context['search_string_limit'] = SearchApi::MAX_LENGTH;
Utils::$context['require_verification'] = User::$me->is_guest && !empty(Config::$modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']);
- if (Utils::$context['require_verification'])
- $verifier = new Verifier(array('id' => 'search'));
+ if (Utils::$context['require_verification']) {
+ $verifier = new Verifier(['id' => 'search']);
+ }
// If you got back from search2 by using the linktree, you get your original search parameters back.
- if (isset($_REQUEST['params']))
- {
+ if (isset($_REQUEST['params'])) {
// Due to IE's 2083 character limit, we have to compress long search strings
- $temp_params = base64_decode(str_replace(array('-', '_', '.'), array('+', '/', '='), $_REQUEST['params']));
+ $temp_params = base64_decode(str_replace(['-', '_', '.'], ['+', '/', '='], $_REQUEST['params']));
// Test for gzuncompress failing
$temp_params2 = @gzuncompress($temp_params);
$temp_params = explode('|"|', !empty($temp_params2) ? $temp_params2 : $temp_params);
- Utils::$context['search_params'] = array();
+ Utils::$context['search_params'] = [];
- foreach ($temp_params as $i => $data)
- {
- @list ($k, $v) = explode('|\'|', $data);
+ foreach ($temp_params as $i => $data) {
+ @list($k, $v) = explode('|\'|', $data);
Utils::$context['search_params'][$k] = $v;
}
- if (isset(Utils::$context['search_params']['brd']))
- {
- Utils::$context['search_params']['brd'] = Utils::$context['search_params']['brd'] == '' ? array() : explode(',', Utils::$context['search_params']['brd']);
+ if (isset(Utils::$context['search_params']['brd'])) {
+ Utils::$context['search_params']['brd'] = Utils::$context['search_params']['brd'] == '' ? [] : explode(',', Utils::$context['search_params']['brd']);
}
}
- if (isset($_REQUEST['search']))
+ if (isset($_REQUEST['search'])) {
Utils::$context['search_params']['search'] = Utils::htmlspecialcharsDecode($_REQUEST['search']);
+ }
- if (isset(Utils::$context['search_params']['search']))
+ if (isset(Utils::$context['search_params']['search'])) {
Utils::$context['search_params']['search'] = Utils::htmlspecialchars(Utils::$context['search_params']['search']);
+ }
- if (isset(Utils::$context['search_params']['userspec']))
+ if (isset(Utils::$context['search_params']['userspec'])) {
Utils::$context['search_params']['userspec'] = Utils::htmlspecialchars(Utils::$context['search_params']['userspec']);
+ }
- if (!empty(Utils::$context['search_params']['searchtype']))
+ if (!empty(Utils::$context['search_params']['searchtype'])) {
Utils::$context['search_params']['searchtype'] = 2;
+ }
- if (!empty(Utils::$context['search_params']['minage']))
+ if (!empty(Utils::$context['search_params']['minage'])) {
Utils::$context['search_params']['minage'] = (int) Utils::$context['search_params']['minage'];
+ }
- if (!empty(Utils::$context['search_params']['maxage']))
+ if (!empty(Utils::$context['search_params']['maxage'])) {
Utils::$context['search_params']['maxage'] = (int) Utils::$context['search_params']['maxage'];
+ }
Utils::$context['search_params']['show_complete'] = !empty(Utils::$context['search_params']['show_complete']);
Utils::$context['search_params']['subject_only'] = !empty(Utils::$context['search_params']['subject_only']);
// Load the error text strings if there were errors in the search.
- if (!empty(Utils::$context['search_errors']))
- {
+ if (!empty(Utils::$context['search_errors'])) {
Lang::load('Errors');
- Utils::$context['search_errors']['messages'] = array();
+ Utils::$context['search_errors']['messages'] = [];
- foreach (Utils::$context['search_errors'] as $search_error => $dummy)
- {
- if ($search_error === 'messages')
+ foreach (Utils::$context['search_errors'] as $search_error => $dummy) {
+ if ($search_error === 'messages') {
continue;
+ }
- if ($search_error == 'string_too_long')
- {
+ if ($search_error == 'string_too_long') {
Lang::$txt['error_string_too_long'] = sprintf(Lang::$txt['error_string_too_long'], SearchApi::MAX_LENGTH);
}
@@ -172,54 +170,51 @@ public function execute(): void
}
// Find all the boards this user is allowed to see.
- $request = Db::$db->query('order_by_board_order', '
- SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level
+ $request = Db::$db->query(
+ 'order_by_board_order',
+ 'SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level
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:empty_string}',
- array(
+ [
'empty_string' => '',
- )
+ ],
);
Utils::$context['num_boards'] = Db::$db->num_rows($request);
Utils::$context['boards_check_all'] = true;
- Utils::$context['categories'] = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ Utils::$context['categories'] = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// This category hasn't been set up yet..
- if (!isset(Utils::$context['categories'][$row['id_cat']]))
- {
- Utils::$context['categories'][$row['id_cat']] = array(
+ if (!isset(Utils::$context['categories'][$row['id_cat']])) {
+ Utils::$context['categories'][$row['id_cat']] = [
'id' => $row['id_cat'],
'name' => $row['cat_name'],
- 'boards' => array()
- );
+ 'boards' => [],
+ ];
}
$is_recycle_board = !empty(Config::$modSettings['recycle_enable']) && $row['id_board'] == Config::$modSettings['recycle_board'];
// Set this board up, and let the template know when it's a child. (indent them..)
- 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'],
- );
+ ];
// If user selected some particular boards, is this one of them?
- if (!empty(Utils::$context['search_params']['brd']))
- {
+ if (!empty(Utils::$context['search_params']['brd'])) {
Utils::$context['categories'][$row['id_cat']]['boards'][$row['id_board']]['selected'] = in_array($row['id_board'], Utils::$context['search_params']['brd']);
}
// User didn't select any boards, so select all except ignored and recycle boards.
- else
- {
+ else {
Utils::$context['categories'][$row['id_cat']]['boards'][$row['id_board']]['selected'] = !$is_recycle_board && !in_array($row['id_board'], User::$me->ignoreboards);
}
// If a board wasn't checked that probably should have been ensure the board selection is selected, yo!
- if (!Utils::$context['categories'][$row['id_cat']]['boards'][$row['id_board']]['selected'] && !$is_recycle_board)
- {
+ if (!Utils::$context['categories'][$row['id_cat']]['boards'][$row['id_board']]['selected'] && !$is_recycle_board) {
Utils::$context['boards_check_all'] = false;
}
}
@@ -228,13 +223,13 @@ public function execute(): void
Category::sort(Utils::$context['categories']);
// Now, let's sort the list of categories into the boards for templates that like that.
- $temp_boards = array();
- foreach (Utils::$context['categories'] as $category)
- {
- $temp_boards[] = array(
+ $temp_boards = [];
+
+ foreach (Utils::$context['categories'] as $category) {
+ $temp_boards[] = [
'name' => $category['name'],
- 'child_ids' => array_keys($category['boards'])
- );
+ 'child_ids' => array_keys($category['boards']),
+ ];
$temp_boards = array_merge($temp_boards, array_values($category['boards']));
// Include a list of boards per category for easy toggling.
@@ -243,54 +238,56 @@ public function execute(): void
$max_boards = ceil(count($temp_boards) / 2);
- if ($max_boards == 1)
+ if ($max_boards == 1) {
$max_boards = 2;
+ }
// Now, alternate them so they can be shown left and right ;).
- Utils::$context['board_columns'] = array();
- for ($i = 0; $i < $max_boards; $i++)
- {
+ Utils::$context['board_columns'] = [];
+
+ for ($i = 0; $i < $max_boards; $i++) {
Utils::$context['board_columns'][] = $temp_boards[$i];
- if (isset($temp_boards[$i + $max_boards]))
+ if (isset($temp_boards[$i + $max_boards])) {
Utils::$context['board_columns'][] = $temp_boards[$i + $max_boards];
- else
- Utils::$context['board_columns'][] = array();
+ } else {
+ Utils::$context['board_columns'][] = [];
+ }
}
- if (!empty($_REQUEST['topic']))
- {
+ if (!empty($_REQUEST['topic'])) {
Utils::$context['search_params']['topic'] = (int) $_REQUEST['topic'];
Utils::$context['search_params']['show_complete'] = true;
}
- if (!empty(Utils::$context['search_params']['topic']))
- {
+ if (!empty(Utils::$context['search_params']['topic'])) {
Utils::$context['search_params']['topic'] = (int) Utils::$context['search_params']['topic'];
- Utils::$context['search_topic'] = array(
+ Utils::$context['search_topic'] = [
'id' => Utils::$context['search_params']['topic'],
'href' => Config::$scripturl . '?topic=' . Utils::$context['search_params']['topic'] . '.0',
- );
+ ];
- $request = Db::$db->query('', '
- SELECT subject
+ $request = Db::$db->query(
+ '',
+ 'SELECT subject
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
WHERE t.id_topic = {int:search_topic_id}
AND {query_see_message_board} ' . (Config::$modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved_true}' : '') . '
LIMIT 1',
- array(
+ [
'is_approved_true' => 1,
'search_topic_id' => Utils::$context['search_params']['topic'],
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('topic_gone', false);
+ }
- list (Utils::$context['search_topic']['subject']) = Db::$db->fetch_row($request);
+ list(Utils::$context['search_topic']['subject']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
Utils::$context['search_topic']['link'] = ' ' . Utils::$context['search_topic']['subject'] . '';
@@ -312,8 +309,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;
}
@@ -339,7 +337,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Search::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Search::exportStatic')) {
Search::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Search2.php b/Sources/Actions/Search2.php
index 526a5111fa..4c65de61f6 100644
--- a/Sources/Actions/Search2.php
+++ b/Sources/Actions/Search2.php
@@ -14,22 +14,19 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
-use SMF\Category;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\PageIndex;
+use SMF\Search\SearchApi;
+use SMF\Search\SearchResult;
use SMF\Security;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
use SMF\Verifier;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
-use SMF\Search\SearchApi;
-use SMF\Search\SearchResult;
/**
* Shows the search form.
@@ -43,12 +40,11 @@ class Search2 implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'PlushSearch2',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -66,14 +62,14 @@ class Search2 implements ActionInterface
*
* ID numbers of messages in the search results.
*/
- public array $messages = array();
+ public array $messages = [];
/**
* @var array
*
* ID numbers of the authors of the $messages.
*/
- public array $posters = array();
+ public array $posters = [];
/****************************
* Internal static properties
@@ -115,8 +111,9 @@ public function execute(): void
$this->setupVerification();
// Did we encounter any errors?
- if ($this->errorCheck())
+ if ($this->errorCheck()) {
return;
+ }
// Spam me not, Spam-a-lot?
$this->spamCheck();
@@ -133,7 +130,7 @@ public function execute(): void
SearchApi::$loadedApi->searchWords,
SearchApi::$loadedApi->excludedIndexWords,
SearchApi::$loadedApi->participants,
- SearchApi::$loadedApi->searchArray
+ SearchApi::$loadedApi->searchArray,
);
$this->initSearchContext();
@@ -155,39 +152,43 @@ public function prepareSearchContext($reset = false)
static $recycle_board = null;
static $counter = null;
- if ($recycle_board === null)
+ if ($recycle_board === null) {
$recycle_board = !empty(Config::$modSettings['recycle_enable']) && !empty(Config::$modSettings['recycle_board']) ? (int) Config::$modSettings['recycle_board'] : 0;
+ }
// Remember which message this is. (ie. reply #83)
- if ($counter == null || $reset)
+ if ($counter == null || $reset) {
$counter = ((int) $_REQUEST['start']) + 1;
+ }
// Start from the beginning...
- if ($reset)
+ if ($reset) {
return @Db::$db->data_seek(SearchResult::$messages_request, 0);
+ }
- if (!isset(SearchResult::$getter))
+ if (!isset(SearchResult::$getter)) {
return false;
+ }
$message = SearchResult::$getter->current();
SearchResult::$getter->next();
- if (!$message)
+ if (!$message) {
return false;
+ }
$output = $message->format($counter);
- if (!empty(Theme::$current->options['display_quick_mod']))
- {
+ if (!empty(Theme::$current->options['display_quick_mod'])) {
$started = $output['first_post']['member']['id'] == User::$me->id;
- $output['quick_mod'] = array(
+ $output['quick_mod'] = [
'lock' => in_array(0, SearchResult::$boards_can['lock_any']) || in_array($output['board']['id'], SearchResult::$boards_can['lock_any']) || ($started && (in_array(0, SearchResult::$boards_can['lock_own']) || in_array($output['board']['id'], SearchResult::$boards_can['lock_own']))),
'sticky' => (in_array(0, SearchResult::$boards_can['make_sticky']) || in_array($output['board']['id'], SearchResult::$boards_can['make_sticky'])),
'move' => in_array(0, SearchResult::$boards_can['move_any']) || in_array($output['board']['id'], SearchResult::$boards_can['move_any']) || ($started && (in_array(0, SearchResult::$boards_can['move_own']) || in_array($output['board']['id'], SearchResult::$boards_can['move_own']))),
'remove' => in_array(0, SearchResult::$boards_can['remove_any']) || in_array($output['board']['id'], SearchResult::$boards_can['remove_any']) || ($started && (in_array(0, SearchResult::$boards_can['remove_own']) || in_array($output['board']['id'], SearchResult::$boards_can['remove_own']))),
'restore' => Utils::$context['can_restore_perm'] && (Config::$modSettings['recycle_board'] == $output['board']['id']),
- );
+ ];
Utils::$context['can_lock'] |= $output['quick_mod']['lock'];
Utils::$context['can_sticky'] |= $output['quick_mod']['sticky'];
@@ -204,7 +205,7 @@ public function prepareSearchContext($reset = false)
$counter++;
- IntegrationHook::call('integrate_search_message_context', array(&$output, &$message, $counter));
+ IntegrationHook::call('integrate_search_message_context', [&$output, &$message, $counter]);
return $output;
}
@@ -220,8 +221,9 @@ public function prepareSearchContext($reset = false)
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -249,8 +251,7 @@ protected function __construct()
// Number of pages hard maximum - normally not set at all.
Config::$modSettings['search_max_results'] = empty(Config::$modSettings['search_max_results']) ? 200 * Config::$modSettings['search_results_per_page'] : (int) Config::$modSettings['search_max_results'];
- if (isset($_REQUEST['start']))
- $_REQUEST['start'] = (int) $_REQUEST['start'];
+ $_REQUEST['start'] = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] - ((int) $_REQUEST['start'] % Config::$modSettings['search_results_per_page']) : 0;
Lang::load('Search');
@@ -263,8 +264,7 @@ protected function __construct()
*/
protected function redirectToMemberSearch(): void
{
- if (isset($_REQUEST['search_selection']) && $_REQUEST['search_selection'] === 'members')
- {
+ if (isset($_REQUEST['search_selection']) && $_REQUEST['search_selection'] === 'members') {
Utils::redirectexit(Config::$scripturl . '?action=mlist;sa=search;fields=name,email;search=' . urlencode($_REQUEST['search']));
}
}
@@ -274,8 +274,7 @@ protected function redirectToMemberSearch(): void
*/
protected function checkLoadAverage(): void
{
- if (!empty(Utils::$context['load_average']) && !empty(Config::$modSettings['loadavg_search']) && Utils::$context['load_average'] >= Config::$modSettings['loadavg_search'])
- {
+ if (!empty(Utils::$context['load_average']) && !empty(Config::$modSettings['loadavg_search']) && Utils::$context['load_average'] >= Config::$modSettings['loadavg_search']) {
ErrorHandler::fatalLang('loadavg_search_disabled', false);
}
}
@@ -286,10 +285,10 @@ protected function checkLoadAverage(): void
protected function preventPrefetch(): void
{
// No, no, no... this is a bit hard on the server, so don't you go prefetching it!
- if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
- {
+ if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
ob_end_clean();
Utils::sendHttpStatus(403);
+
die;
}
}
@@ -302,10 +301,10 @@ protected function errorCheck(): bool
IntegrationHook::call('integrate_search_errors');
// One or more search errors? Go back to the first search screen.
- if (!empty(Utils::$context['search_errors']))
- {
+ if (!empty(Utils::$context['search_errors'])) {
$_REQUEST['params'] = SearchApi::$loadedApi->compressParams();
Search::call();
+
return true;
}
@@ -317,8 +316,9 @@ protected function errorCheck(): bool
*/
protected function spamCheck(): void
{
- if (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != SearchApi::$loadedApi->params['search'])
+ if (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != SearchApi::$loadedApi->params['search']) {
Security::spamProtection('search');
+ }
// Store the last search string to allow pages of results to be browsed.
$_SESSION['last_ss'] = SearchApi::$loadedApi->params['search'];
@@ -329,8 +329,9 @@ protected function spamCheck(): void
*/
protected function setupTemplate(): void
{
- if (!isset($_REQUEST['xml']))
+ if (!isset($_REQUEST['xml'])) {
Theme::loadTemplate('Search');
+ }
// If we're doing XML we need to use the results template regardless really.
Utils::$context['sub_template'] = 'results';
@@ -346,23 +347,25 @@ protected function setupTemplate(): void
// Let the user adjust the search query, should they wish?
Utils::$context['search_params'] = SearchApi::$loadedApi->params;
- if (isset(Utils::$context['search_params']['search']))
+ if (isset(Utils::$context['search_params']['search'])) {
Utils::$context['search_params']['search'] = Utils::htmlspecialchars(Utils::$context['search_params']['search']);
+ }
- if (isset(Utils::$context['search_params']['userspec']))
+ if (isset(Utils::$context['search_params']['userspec'])) {
Utils::$context['search_params']['userspec'] = Utils::htmlspecialchars(Utils::$context['search_params']['userspec']);
+ }
Utils::$context['params'] = SearchApi::$loadedApi->compressParams();
// ... and add the links to the link tree.
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=search;params=' . SearchApi::$loadedApi->compressParams(),
- 'name' => Lang::$txt['search']
- );
- Utils::$context['linktree'][] = array(
+ 'name' => Lang::$txt['search'],
+ ];
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=search2;params=' . SearchApi::$loadedApi->compressParams(),
- 'name' => Lang::$txt['search_results']
- );
+ 'name' => Lang::$txt['search_results'],
+ ];
// Now that we know how many results to expect we can start calculating the page numbers.
Utils::$context['page_index'] = new PageIndex(Config::$scripturl . '?action=search2;params=' . SearchApi::$loadedApi->compressParams(), $_REQUEST['start'], $this->num_results, Config::$modSettings['search_results_per_page'], false);
@@ -370,19 +373,21 @@ protected function setupTemplate(): void
Utils::$context['key_words'] = SearchApi::$loadedApi->searchArray;
// Setup the default topic icons... for checking they exist and the like!
- Utils::$context['icon_sources'] = array();
- foreach (Utils::$context['stable_icons'] as $icon)
+ Utils::$context['icon_sources'] = [];
+
+ foreach (Utils::$context['stable_icons'] as $icon) {
Utils::$context['icon_sources'][$icon] = 'images_url';
+ }
Utils::$context['page_title'] = Lang::$txt['search_results'];
- Utils::$context['get_topics'] = array($this, 'prepareSearchContext');
+ Utils::$context['get_topics'] = [$this, 'prepareSearchContext'];
Utils::$context['can_restore_perm'] = User::$me->allowedTo('move_any') && !empty(Config::$modSettings['recycle_enable']);
Utils::$context['can_restore'] = false; // We won't know until we handle the context later whether we can actually restore...
- Utils::$context['jump_to'] = array(
+ Utils::$context['jump_to'] = [
'label' => addslashes(Utils::htmlspecialcharsDecode(Lang::$txt['jump_to'])),
'board_name' => addslashes(Utils::htmlspecialcharsDecode(Lang::$txt['select_destination'])),
- );
+ ];
}
/**
@@ -391,18 +396,16 @@ protected function setupTemplate(): void
protected function setupVerification(): void
{
// Do we have captcha enabled?
- if (User::$me->is_guest && !empty(Config::$modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']) && (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != SearchApi::$loadedApi->params['search']))
- {
- $verifier = new Verifier(array('id' => 'search'));
+ if (User::$me->is_guest && !empty(Config::$modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']) && (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != SearchApi::$loadedApi->params['search'])) {
+ $verifier = new Verifier(['id' => 'search']);
- if (!empty($verifier->errors))
- {
- foreach ($verifier->errors as $error)
+ if (!empty($verifier->errors)) {
+ foreach ($verifier->errors as $error) {
Utils::$context['search_errors'][$error] = true;
+ }
}
// Don't keep asking for it - they've proven themselves worthy.
- else
- {
+ else {
$_SESSION['ss_vv_passed'] = true;
}
}
@@ -413,20 +416,21 @@ protected function setupVerification(): void
*/
protected function getPosters()
{
- $request = Db::$db->query('', '
- SELECT id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}messages
WHERE id_member != {int:no_member}
AND id_msg IN ({array_int:message_list})
LIMIT {int:limit}',
- array(
+ [
'message_list' => $this->messages,
'no_member' => 0,
'limit' => count(SearchApi::$loadedApi->results),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$this->posters[] = $row['id_member'];
}
Db::$db->free_result($request);
@@ -437,80 +441,76 @@ protected function getPosters()
*/
protected function spellCheck()
{
- if (Utils::$context['show_spellchecking'])
- {
+ if (Utils::$context['show_spellchecking']) {
// Don't hardcode spellchecking functions!
$link = SearchResult::spell_init();
- $did_you_mean = array('search' => array(), 'display' => array());
+ $did_you_mean = ['search' => [], 'display' => []];
$found_misspelling = false;
- foreach (SearchApi::$loadedApi->searchArray as $word)
- {
- if (empty($link))
+
+ foreach (SearchApi::$loadedApi->searchArray as $word) {
+ if (empty($link)) {
continue;
+ }
// Don't check phrases.
- if (preg_match('~^\w+$~', $word) === 0)
- {
+ if (preg_match('~^\w+$~', $word) === 0) {
$did_you_mean['search'][] = '"' . $word . '"';
$did_you_mean['display'][] = '"' . Utils::htmlspecialchars($word) . '"';
+
continue;
}
+
// For some strange reason spell check can crash PHP on decimals.
- elseif (preg_match('~\d~', $word) === 1)
- {
+ if (preg_match('~\d~', $word) === 1) {
$did_you_mean['search'][] = $word;
$did_you_mean['display'][] = Utils::htmlspecialchars($word);
+
continue;
}
- elseif (SearchResult::spell_check($link, $word))
- {
+
+ if (SearchResult::spell_check($link, $word)) {
$did_you_mean['search'][] = $word;
$did_you_mean['display'][] = Utils::htmlspecialchars($word);
+
continue;
}
$suggestions = SearchResult::spell_suggest($link, $word);
- foreach ($suggestions as $i => $s)
- {
+
+ foreach ($suggestions as $i => $s) {
// Search is case insensitive.
- if (Utils::strtolower($s) == Utils::strtolower($word))
+ if (Utils::strtolower($s) == Utils::strtolower($word)) {
unset($suggestions[$i]);
+ }
// Plus, don't suggest something the user thinks is rude!
- elseif ($suggestions[$i] != Lang::censorText($s))
+ elseif ($suggestions[$i] != Lang::censorText($s)) {
unset($suggestions[$i]);
+ }
}
// Anything found? If so, correct it!
- if (!empty($suggestions))
- {
+ if (!empty($suggestions)) {
$suggestions = array_values($suggestions);
$did_you_mean['search'][] = $suggestions[0];
$did_you_mean['display'][] = ' ' . Utils::htmlspecialchars($suggestions[0]) . '';
$found_misspelling = true;
- }
- else
- {
+ } else {
$did_you_mean['search'][] = $word;
$did_you_mean['display'][] = Utils::htmlspecialchars($word);
}
}
- if ($found_misspelling)
- {
+ if ($found_misspelling) {
// Don't spell check excluded words, but add them still...
- $temp_excluded = array('search' => array(), 'display' => array());
+ $temp_excluded = ['search' => [], 'display' => []];
- foreach (SearchApi::$loadedApi->excludedWords as $word)
- {
- if (preg_match('~^\w+$~', $word) == 0)
- {
+ foreach (SearchApi::$loadedApi->excludedWords as $word) {
+ if (preg_match('~^\w+$~', $word) == 0) {
$temp_excluded['search'][] = '-"' . $word . '"';
$temp_excluded['display'][] = '-"' . Utils::htmlspecialchars($word) . '"';
- }
- else
- {
+ } else {
$temp_excluded['search'][] = '-' . $word;
$temp_excluded['display'][] = '-' . Utils::htmlspecialchars($word);
}
@@ -522,13 +522,15 @@ protected function spellCheck()
$temp_params = SearchApi::$loadedApi->params;
$temp_params['search'] = implode(' ', $did_you_mean['search']);
- if (isset($temp_params['brd']))
+ if (isset($temp_params['brd'])) {
$temp_params['brd'] = implode(',', $temp_params['brd']);
+ }
- Utils::$context['params'] = array();
+ Utils::$context['params'] = [];
- foreach ($temp_params as $k => $v)
+ foreach ($temp_params as $k => $v) {
Utils::$context['did_you_mean_params'][] = $k . '|\'|' . $v;
+ }
Utils::$context['did_you_mean_params'] = base64_encode(implode('|"|', Utils::$context['did_you_mean_params']));
Utils::$context['did_you_mean'] = implode(' ', $did_you_mean['display']);
@@ -541,8 +543,9 @@ protected function spellCheck()
*/
protected function initSearchContext()
{
- if (empty(SearchApi::$loadedApi->results))
+ if (empty(SearchApi::$loadedApi->results)) {
return;
+ }
SearchResult::setBoardsCan();
@@ -552,10 +555,11 @@ protected function initSearchContext()
// Load the posters...
$this->getPosters();
- IntegrationHook::call('integrate_search_message_list', array(&$this->messages, &$this->posters));
+ IntegrationHook::call('integrate_search_message_list', [&$this->messages, &$this->posters]);
- if (!empty($this->posters))
+ if (!empty($this->posters)) {
User::load(array_unique($this->posters));
+ }
SearchResult::$getter = SearchResult::get($this->messages);
@@ -563,9 +567,9 @@ protected function initSearchContext()
$this->num_results = !empty($_SESSION['search_cache']['num_results']) ? $_SESSION['search_cache']['num_results'] : SearchResult::getNumResults();
// If there are no results that means the things in the cache got deleted, so pretend we have no topics anymore.
- if ($this->num_results == 0)
- {
- SearchApi::$loadedApi->results = array();
+ if ($this->num_results == 0) {
+ SearchApi::$loadedApi->results = [];
+
return;
}
@@ -574,7 +578,8 @@ protected function initSearchContext()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Search2::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Search2::exportStatic')) {
Search2::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/SendActivation.php b/Sources/Actions/SendActivation.php
index cf2784d214..668d5a3a7b 100644
--- a/Sources/Actions/SendActivation.php
+++ b/Sources/Actions/SendActivation.php
@@ -14,7 +14,6 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Lang;
use SMF\Theme;
use SMF\User;
@@ -33,12 +32,11 @@ class SendActivation implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'SendActivation',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -86,8 +84,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;
}
@@ -109,12 +108,12 @@ public static function call(): void
*/
protected function __construct()
{
-
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\SendActivation::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\SendActivation::exportStatic')) {
SendActivation::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/SmStats.php b/Sources/Actions/SmStats.php
index a54f0d5921..c919170f50 100644
--- a/Sources/Actions/SmStats.php
+++ b/Sources/Actions/SmStats.php
@@ -13,11 +13,10 @@
namespace SMF\Actions;
+use SMF\Actions\Admin\ACP;
use SMF\BackwardCompatibility;
-
use SMF\Config;
use SMF\User;
-use SMF\Actions\Admin\ACP;
/**
* Lets simplemachines.org gather statistics if, and only if, the admin allows.
@@ -31,12 +30,11 @@ class SmStats implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'SMStats',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -69,26 +67,29 @@ class SmStats implements ActionInterface
public function execute(): void
{
// First, is it disabled?
- if (empty(Config::$modSettings['enable_sm_stats']) || empty(Config::$modSettings['sm_stats_key']))
+ if (empty(Config::$modSettings['enable_sm_stats']) || empty(Config::$modSettings['sm_stats_key'])) {
die();
+ }
// Are we saying who we are, and are we right? (OR an admin)
- if (!User::$me->is_admin && (!isset($_GET['sid']) || $_GET['sid'] != Config::$modSettings['sm_stats_key']))
+ if (!User::$me->is_admin && (!isset($_GET['sid']) || $_GET['sid'] != Config::$modSettings['sm_stats_key'])) {
die();
+ }
// Verify the referer...
- if (!User::$me->is_admin && (!isset($_SERVER['HTTP_REFERER']) || md5($_SERVER['HTTP_REFERER']) != '746cb59a1a0d5cf4bd240e5a67c73085'))
+ if (!User::$me->is_admin && (!isset($_SERVER['HTTP_REFERER']) || md5($_SERVER['HTTP_REFERER']) != '746cb59a1a0d5cf4bd240e5a67c73085')) {
die();
+ }
// Get some server versions.
- $checkFor = array(
+ $checkFor = [
'php',
'db_server',
- );
+ ];
$serverVersions = ACP::getServerVersions($checkFor);
// Get the actual stats.
- $stats_to_send = array(
+ $stats_to_send = [
'UID' => Config::$modSettings['sm_stats_key'],
'time_added' => time(),
'members' => Config::$modSettings['totalMembers'],
@@ -100,30 +101,28 @@ public function execute(): void
'database_version' => $serverVersions['db_server']['version'],
'smf_version' => SMF_FULL_VERSION,
'smfd_version' => Config::$modSettings['smfVersion'],
- );
+ ];
// Encode all the data, for security.
- foreach ($stats_to_send as $k => $v)
+ foreach ($stats_to_send as $k => $v) {
$stats_to_send[$k] = urlencode($k) . '=' . urlencode($v);
+ }
// Turn this into the query string!
$stats_to_send = implode('&', $stats_to_send);
// If we're an admin, just plonk them out.
- if (User::$me->is_admin)
- {
+ if (User::$me->is_admin) {
echo $stats_to_send;
- }
- else
- {
+ } else {
// Connect to the collection script.
$fp = @fsockopen('www.simplemachines.org', 443, $errno, $errstr);
- if (!$fp)
+ if (!$fp) {
$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
+ }
- if ($fp)
- {
+ if ($fp) {
$length = strlen($stats_to_send);
$out = 'POST /smf/stats/collect_stats.php HTTP/1.1' . "\r\n";
@@ -153,8 +152,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;
}
@@ -180,7 +180,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\SmStats::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\SmStats::exportStatic')) {
SmStats::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Stats.php b/Sources/Actions/Stats.php
index b645888d09..49fdf37675 100644
--- a/Sources/Actions/Stats.php
+++ b/Sources/Actions/Stats.php
@@ -14,8 +14,9 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -23,8 +24,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* Provides a display for forum statistics.
@@ -38,12 +37,11 @@ class Stats implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'DisplayStats',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -74,74 +72,76 @@ public function execute(): void
User::$me->isAllowedTo('view_stats');
// Page disabled - redirect them out
- if (empty(Config::$modSettings['trackStats']))
+ if (empty(Config::$modSettings['trackStats'])) {
ErrorHandler::fatalLang('feature_disabled', true);
+ }
- if (!empty($_REQUEST['expand']))
- {
+ if (!empty($_REQUEST['expand'])) {
Utils::$context['robot_no_index'] = true;
$month = (int) substr($_REQUEST['expand'], 4);
$year = (int) substr($_REQUEST['expand'], 0, 4);
- if ($year > 1900 && $year < 2200 && $month >= 1 && $month <= 12)
+ if ($year > 1900 && $year < 2200 && $month >= 1 && $month <= 12) {
$_SESSION['expanded_stats'][$year][] = $month;
- }
- elseif (!empty($_REQUEST['collapse']))
- {
+ }
+ } elseif (!empty($_REQUEST['collapse'])) {
Utils::$context['robot_no_index'] = true;
$month = (int) substr($_REQUEST['collapse'], 4);
$year = (int) substr($_REQUEST['collapse'], 0, 4);
- if (!empty($_SESSION['expanded_stats'][$year]))
- $_SESSION['expanded_stats'][$year] = array_diff($_SESSION['expanded_stats'][$year], array($month));
+ if (!empty($_SESSION['expanded_stats'][$year])) {
+ $_SESSION['expanded_stats'][$year] = array_diff($_SESSION['expanded_stats'][$year], [$month]);
+ }
}
// Handle the XMLHttpRequest.
- if (isset($_REQUEST['xml']))
- {
+ if (isset($_REQUEST['xml'])) {
// Collapsing stats only needs adjustments of the session variables.
- if (!empty($_REQUEST['collapse']))
+ if (!empty($_REQUEST['collapse'])) {
Utils::obExit(false);
+ }
Utils::$context['sub_template'] = 'stats';
- Utils::$context['yearly'] = array();
+ Utils::$context['yearly'] = [];
- if (empty($month) || empty($year))
+ if (empty($month) || empty($year)) {
return;
+ }
- $this->getDailyStats('YEAR(date) = {int:year} AND MONTH(date) = {int:month}', array('year' => $year, 'month' => $month));
+ $this->getDailyStats('YEAR(date) = {int:year} AND MONTH(date) = {int:month}', ['year' => $year, 'month' => $month]);
- Utils::$context['yearly'][$year]['months'][$month]['date'] = array(
+ Utils::$context['yearly'][$year]['months'][$month]['date'] = [
'month' => sprintf('%02d', $month),
'year' => $year,
- );
+ ];
return;
}
Lang::load('Stats');
Theme::loadTemplate('Stats');
- Theme::loadJavaScriptFile('stats.js', array('default_theme' => true, 'defer' => false, 'minimize' => true), 'smf_stats');
+ Theme::loadJavaScriptFile('stats.js', ['default_theme' => true, 'defer' => false, 'minimize' => true], 'smf_stats');
// Build the link tree......
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=stats',
- 'name' => Lang::$txt['stats_center']
- );
+ 'name' => Lang::$txt['stats_center'],
+ ];
Utils::$context['page_title'] = Utils::$context['forum_name'] . ' - ' . Lang::$txt['stats_center'];
Utils::$context['show_member_list'] = User::$me->allowedTo('view_mlist');
// Get averages...
- $result = Db::$db->query('', '
- SELECT
+ $result = Db::$db->query(
+ '',
+ 'SELECT
SUM(posts) AS posts, SUM(topics) AS topics, SUM(registers) AS registers,
SUM(most_on) AS most_on, MIN(date) AS date, SUM(hits) AS hits
FROM {db_prefix}log_activity',
- array(
- )
+ [
+ ],
);
$row = Db::$db->fetch_assoc($result);
Db::$db->free_result($result);
@@ -158,34 +158,37 @@ public function execute(): void
Utils::$context['num_hits'] = Lang::numberFormat($row['hits'], 0);
// How many users are online now.
- $result = Db::$db->query('', '
- SELECT COUNT(*)
+ $result = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_online',
- array(
- )
+ [
+ ],
);
- list (Utils::$context['users_online']) = Db::$db->fetch_row($result);
+ list(Utils::$context['users_online']) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
// Statistics such as number of boards, categories, etc.
- $result = Db::$db->query('', '
- SELECT COUNT(*)
+ $result = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}boards AS b
WHERE b.redirect = {string:blank_redirect}',
- array(
+ [
'blank_redirect' => '',
- )
+ ],
);
- list (Utils::$context['num_boards']) = Db::$db->fetch_row($result);
+ list(Utils::$context['num_boards']) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
- $result = Db::$db->query('', '
- SELECT COUNT(*)
+ $result = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}categories AS c',
- array(
- )
+ [
+ ],
);
- list (Utils::$context['num_categories']) = Db::$db->fetch_row($result);
+ list(Utils::$context['num_categories']) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
// Format the numbers nicely.
@@ -196,33 +199,33 @@ public function execute(): void
Utils::$context['num_members'] = Lang::numberFormat(Config::$modSettings['totalMembers']);
Utils::$context['num_posts'] = Lang::numberFormat(Config::$modSettings['totalMessages']);
Utils::$context['num_topics'] = Lang::numberFormat(Config::$modSettings['totalTopics']);
- Utils::$context['most_members_online'] = array(
+ Utils::$context['most_members_online'] = [
'number' => Lang::numberFormat(Config::$modSettings['mostOnline']),
'date' => Time::create('@' . Config::$modSettings['mostDate'])->format(),
- );
+ ];
Utils::$context['latest_member'] = &Utils::$context['common_stats']['latest_member'];
// Let's calculate gender stats only every four minutes.
- $disabled_fields = isset(Config::$modSettings['disabled_profile_fields']) ? explode(',', Config::$modSettings['disabled_profile_fields']) : array();
-
- if (!in_array('gender', $disabled_fields))
- {
- if ((Utils::$context['gender'] = CacheApi::get('stats_gender', 240)) == null)
- {
- $result = Db::$db->query('', '
- SELECT default_value
+ $disabled_fields = isset(Config::$modSettings['disabled_profile_fields']) ? explode(',', Config::$modSettings['disabled_profile_fields']) : [];
+
+ if (!in_array('gender', $disabled_fields)) {
+ if ((Utils::$context['gender'] = CacheApi::get('stats_gender', 240)) == null) {
+ $result = Db::$db->query(
+ '',
+ 'SELECT default_value
FROM {db_prefix}custom_fields
WHERE col_name= {string:gender_var}',
- array(
+ [
'gender_var' => 'cust_gender',
- )
+ ],
);
$row = Db::$db->fetch_assoc($result);
$default_gender = !empty($row['default_value']) ? $row['default_value'] : '{gender_0}';
Db::$db->free_result($result);
- $result = Db::$db->query('', '
- SELECT COUNT(*) AS total_members, value AS gender
+ $result = Db::$db->query(
+ '',
+ 'SELECT COUNT(*) AS total_members, value AS gender
FROM {db_prefix}members AS mem
INNER JOIN {db_prefix}themes AS t ON (
t.id_member = mem.id_member
@@ -231,16 +234,16 @@ public function execute(): void
)
WHERE is_activated = {int:is_activated}
GROUP BY value',
- array(
+ [
'gender_var' => 'cust_gender',
'default_theme' => 1,
'is_activated' => 1,
'default_gender' => $default_gender,
- )
+ ],
);
- Utils::$context['gender'] = array($default_gender => 0);
- while ($row = Db::$db->fetch_assoc($result))
- {
+ Utils::$context['gender'] = [$default_gender => 0];
+
+ while ($row = Db::$db->fetch_assoc($result)) {
Utils::$context['gender'][$row['gender']] = $row['total_members'];
}
Db::$db->free_result($result);
@@ -254,119 +257,123 @@ public function execute(): void
$date = Time::strftime('%Y-%m-%d', time());
// Members online so far today.
- $result = Db::$db->query('', '
- SELECT most_on
+ $result = Db::$db->query(
+ '',
+ 'SELECT most_on
FROM {db_prefix}log_activity
WHERE date = {date:today_date}
LIMIT 1',
- array(
+ [
'today_date' => $date,
- )
+ ],
);
- list (Utils::$context['online_today']) = Db::$db->fetch_row($result);
+ list(Utils::$context['online_today']) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
Utils::$context['online_today'] = Lang::numberFormat((int) Utils::$context['online_today']);
// Poster top 10.
- $members_result = Db::$db->query('', '
- SELECT id_member, real_name, posts
+ $members_result = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name, posts
FROM {db_prefix}members
WHERE posts > {int:no_posts}
ORDER BY posts DESC
LIMIT 10',
- array(
+ [
'no_posts' => 0,
- )
+ ],
);
- Utils::$context['stats_blocks']['posters'] = array();
+ Utils::$context['stats_blocks']['posters'] = [];
$max_num_posts = 1;
- while ($row_members = Db::$db->fetch_assoc($members_result))
- {
- Utils::$context['stats_blocks']['posters'][] = array(
+
+ while ($row_members = Db::$db->fetch_assoc($members_result)) {
+ Utils::$context['stats_blocks']['posters'][] = [
'name' => $row_members['real_name'],
'id' => $row_members['id_member'],
'num' => $row_members['posts'],
'href' => Config::$scripturl . '?action=profile;u=' . $row_members['id_member'],
- 'link' => ' ' . $row_members['real_name'] . ''
- );
+ 'link' => ' ' . $row_members['real_name'] . '',
+ ];
- if ($max_num_posts < $row_members['posts'])
+ if ($max_num_posts < $row_members['posts']) {
$max_num_posts = $row_members['posts'];
+ }
}
Db::$db->free_result($members_result);
- foreach (Utils::$context['stats_blocks']['posters'] as $i => $poster)
- {
+ foreach (Utils::$context['stats_blocks']['posters'] as $i => $poster) {
Utils::$context['stats_blocks']['posters'][$i]['percent'] = round(($poster['num'] * 100) / $max_num_posts);
Utils::$context['stats_blocks']['posters'][$i]['num'] = Lang::numberFormat(Utils::$context['stats_blocks']['posters'][$i]['num']);
}
// Board top 10.
- $boards_result = Db::$db->query('', '
- SELECT id_board, name, num_posts
+ $boards_result = Db::$db->query(
+ '',
+ 'SELECT id_board, name, num_posts
FROM {db_prefix}boards AS b
WHERE {query_see_board}' . (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0 ? '
AND b.id_board != {int:recycle_board}' : '') . '
AND b.redirect = {string:blank_redirect}
ORDER BY num_posts DESC
LIMIT 10',
- array(
+ [
'recycle_board' => Config::$modSettings['recycle_board'],
'blank_redirect' => '',
- )
+ ],
);
- Utils::$context['stats_blocks']['boards'] = array();
+ Utils::$context['stats_blocks']['boards'] = [];
$max_num_posts = 1;
- while ($row_board = Db::$db->fetch_assoc($boards_result))
- {
- Utils::$context['stats_blocks']['boards'][] = array(
+
+ while ($row_board = Db::$db->fetch_assoc($boards_result)) {
+ Utils::$context['stats_blocks']['boards'][] = [
'id' => $row_board['id_board'],
'name' => $row_board['name'],
'num' => $row_board['num_posts'],
'href' => Config::$scripturl . '?board=' . $row_board['id_board'] . '.0',
- 'link' => ' ' . $row_board['name'] . ''
- );
+ 'link' => ' ' . $row_board['name'] . '',
+ ];
- if ($max_num_posts < $row_board['num_posts'])
+ if ($max_num_posts < $row_board['num_posts']) {
$max_num_posts = $row_board['num_posts'];
+ }
}
Db::$db->free_result($boards_result);
- foreach (Utils::$context['stats_blocks']['boards'] as $i => $board)
- {
+ foreach (Utils::$context['stats_blocks']['boards'] as $i => $board) {
Utils::$context['stats_blocks']['boards'][$i]['percent'] = round(($board['num'] * 100) / $max_num_posts);
Utils::$context['stats_blocks']['boards'][$i]['num'] = Lang::numberFormat(Utils::$context['stats_blocks']['boards'][$i]['num']);
}
// Are you on a larger forum? If so, let's try to limit the number of topics we search through.
- if (Config::$modSettings['totalMessages'] > 100000)
- {
- $request = Db::$db->query('', '
- SELECT id_topic
+ if (Config::$modSettings['totalMessages'] > 100000) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic
FROM {db_prefix}topics
WHERE num_replies != {int:no_replies}' . (Config::$modSettings['postmod_active'] ? '
AND approved = {int:is_approved}' : '') . '
ORDER BY num_replies DESC
LIMIT 100',
- array(
+ [
'no_replies' => 0,
'is_approved' => 1,
- )
+ ],
);
- $topic_ids = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $topic_ids = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$topic_ids[] = $row['id_topic'];
}
Db::$db->free_result($request);
+ } else {
+ $topic_ids = [];
}
- else
- $topic_ids = array();
// Topic replies top 10.
- $topic_reply_result = Db::$db->query('', '
- SELECT m.subject, t.num_replies, t.id_board, t.id_topic, b.name
+ $topic_reply_result = Db::$db->query(
+ '',
+ 'SELECT m.subject, t.num_replies, t.id_board, t.id_topic, b.name
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board' . (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0 ? '
@@ -376,70 +383,70 @@ public function execute(): void
AND t.approved = {int:is_approved}' : '')) . '
ORDER BY t.num_replies DESC
LIMIT 10',
- array(
+ [
'topic_list' => $topic_ids,
'recycle_board' => Config::$modSettings['recycle_board'],
'is_approved' => 1,
- )
+ ],
);
- Utils::$context['stats_blocks']['topics_replies'] = array();
+ Utils::$context['stats_blocks']['topics_replies'] = [];
$max_num_replies = 1;
- while ($row_topic_reply = Db::$db->fetch_assoc($topic_reply_result))
- {
+ while ($row_topic_reply = Db::$db->fetch_assoc($topic_reply_result)) {
Lang::censorText($row_topic_reply['subject']);
- Utils::$context['stats_blocks']['topics_replies'][] = array(
+ Utils::$context['stats_blocks']['topics_replies'][] = [
'id' => $row_topic_reply['id_topic'],
- 'board' => array(
+ 'board' => [
'id' => $row_topic_reply['id_board'],
'name' => $row_topic_reply['name'],
'href' => Config::$scripturl . '?board=' . $row_topic_reply['id_board'] . '.0',
- 'link' => ' ' . $row_topic_reply['name'] . ''
- ),
+ 'link' => ' ' . $row_topic_reply['name'] . '',
+ ],
'subject' => $row_topic_reply['subject'],
'num' => $row_topic_reply['num_replies'],
'href' => Config::$scripturl . '?topic=' . $row_topic_reply['id_topic'] . '.0',
- 'link' => ' ' . $row_topic_reply['subject'] . ''
- );
+ 'link' => ' ' . $row_topic_reply['subject'] . '',
+ ];
- if ($max_num_replies < $row_topic_reply['num_replies'])
+ if ($max_num_replies < $row_topic_reply['num_replies']) {
$max_num_replies = $row_topic_reply['num_replies'];
+ }
}
Db::$db->free_result($topic_reply_result);
- foreach (Utils::$context['stats_blocks']['topics_replies'] as $i => $topic)
- {
+ foreach (Utils::$context['stats_blocks']['topics_replies'] as $i => $topic) {
Utils::$context['stats_blocks']['topics_replies'][$i]['percent'] = round(($topic['num'] * 100) / $max_num_replies);
Utils::$context['stats_blocks']['topics_replies'][$i]['num'] = Lang::numberFormat(Utils::$context['stats_blocks']['topics_replies'][$i]['num']);
}
// Large forums may need a bit more prodding...
- if (Config::$modSettings['totalMessages'] > 100000)
- {
- $request = Db::$db->query('', '
- SELECT id_topic
+ if (Config::$modSettings['totalMessages'] > 100000) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic
FROM {db_prefix}topics
WHERE num_views != {int:no_views}
ORDER BY num_views DESC
LIMIT 100',
- array(
+ [
'no_views' => 0,
- )
+ ],
);
- $topic_ids = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $topic_ids = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$topic_ids[] = $row['id_topic'];
}
Db::$db->free_result($request);
+ } else {
+ $topic_ids = [];
}
- else
- $topic_ids = array();
// Topic views top 10.
- $topic_view_result = Db::$db->query('', '
- SELECT m.subject, t.num_views, t.id_board, t.id_topic, b.name
+ $topic_view_result = Db::$db->query(
+ '',
+ 'SELECT m.subject, t.num_views, t.id_board, t.id_topic, b.name
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board' . (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0 ? '
@@ -449,60 +456,60 @@ public function execute(): void
AND t.approved = {int:is_approved}' : '')) . '
ORDER BY t.num_views DESC
LIMIT 10',
- array(
+ [
'topic_list' => $topic_ids,
'recycle_board' => Config::$modSettings['recycle_board'],
'is_approved' => 1,
- )
+ ],
);
- Utils::$context['stats_blocks']['topics_views'] = array();
+ Utils::$context['stats_blocks']['topics_views'] = [];
$max_num = 1;
- while ($row_topic_views = Db::$db->fetch_assoc($topic_view_result))
- {
+
+ while ($row_topic_views = Db::$db->fetch_assoc($topic_view_result)) {
Lang::censorText($row_topic_views['subject']);
- Utils::$context['stats_blocks']['topics_views'][] = array(
+ Utils::$context['stats_blocks']['topics_views'][] = [
'id' => $row_topic_views['id_topic'],
- 'board' => array(
+ 'board' => [
'id' => $row_topic_views['id_board'],
'name' => $row_topic_views['name'],
'href' => Config::$scripturl . '?board=' . $row_topic_views['id_board'] . '.0',
- 'link' => ' ' . $row_topic_views['name'] . ''
- ),
+ 'link' => ' ' . $row_topic_views['name'] . '',
+ ],
'subject' => $row_topic_views['subject'],
'num' => $row_topic_views['num_views'],
'href' => Config::$scripturl . '?topic=' . $row_topic_views['id_topic'] . '.0',
- 'link' => ' ' . $row_topic_views['subject'] . ''
- );
+ 'link' => ' ' . $row_topic_views['subject'] . '',
+ ];
- if ($max_num < $row_topic_views['num_views'])
+ if ($max_num < $row_topic_views['num_views']) {
$max_num = $row_topic_views['num_views'];
+ }
}
Db::$db->free_result($topic_view_result);
- foreach (Utils::$context['stats_blocks']['topics_views'] as $i => $topic)
- {
+ foreach (Utils::$context['stats_blocks']['topics_views'] as $i => $topic) {
Utils::$context['stats_blocks']['topics_views'][$i]['percent'] = round(($topic['num'] * 100) / $max_num);
Utils::$context['stats_blocks']['topics_views'][$i]['num'] = Lang::numberFormat(Utils::$context['stats_blocks']['topics_views'][$i]['num']);
}
// Try to cache this when possible, because it's a little unavoidably slow.
- if (($members = CacheApi::get('stats_top_starters', 360)) == null)
- {
- $request = Db::$db->query('', '
- SELECT id_member_started, COUNT(*) AS hits
+ if (($members = CacheApi::get('stats_top_starters', 360)) == null) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member_started, COUNT(*) AS hits
FROM {db_prefix}topics' . (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0 ? '
WHERE id_board != {int:recycle_board}' : '') . '
GROUP BY id_member_started
ORDER BY hits DESC
LIMIT 20',
- array(
+ [
'recycle_board' => Config::$modSettings['recycle_board'],
- )
+ ],
);
- $members = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $members = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$members[$row['id_member_started']] = $row['hits'];
}
Db::$db->free_result($request);
@@ -510,70 +517,76 @@ public function execute(): void
CacheApi::put('stats_top_starters', $members, 360);
}
- if (empty($members))
- $members = array(0 => 0);
+ if (empty($members)) {
+ $members = [0 => 0];
+ }
// Topic poster top 10.
- $members_result = Db::$db->query('', '
- SELECT id_member, real_name
+ $members_result = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name
FROM {db_prefix}members
WHERE id_member IN ({array_int:member_list})',
- array(
+ [
'member_list' => array_keys($members),
- )
+ ],
);
- Utils::$context['stats_blocks']['starters'] = array();
+ Utils::$context['stats_blocks']['starters'] = [];
$max_num = 1;
- while ($row_members = Db::$db->fetch_assoc($members_result))
- {
+
+ while ($row_members = Db::$db->fetch_assoc($members_result)) {
$i = array_search($row_members['id_member'], array_keys($members));
// skip all not top 10
- if ($i > 10)
+ if ($i > 10) {
continue;
+ }
- Utils::$context['stats_blocks']['starters'][$i] = array(
+ Utils::$context['stats_blocks']['starters'][$i] = [
'name' => $row_members['real_name'],
'id' => $row_members['id_member'],
'num' => $members[$row_members['id_member']],
'href' => Config::$scripturl . '?action=profile;u=' . $row_members['id_member'],
- 'link' => ' ' . $row_members['real_name'] . ''
- );
+ 'link' => ' ' . $row_members['real_name'] . '',
+ ];
- if ($max_num < $members[$row_members['id_member']])
+ if ($max_num < $members[$row_members['id_member']]) {
$max_num = $members[$row_members['id_member']];
+ }
}
ksort(Utils::$context['stats_blocks']['starters']);
Db::$db->free_result($members_result);
- foreach (Utils::$context['stats_blocks']['starters'] as $i => $topic)
- {
+ foreach (Utils::$context['stats_blocks']['starters'] as $i => $topic) {
Utils::$context['stats_blocks']['starters'][$i]['percent'] = round(($topic['num'] * 100) / $max_num);
Utils::$context['stats_blocks']['starters'][$i]['num'] = Lang::numberFormat(Utils::$context['stats_blocks']['starters'][$i]['num']);
}
// Time online top 10.
$temp = CacheApi::get('stats_total_time_members', 600);
- $members_result = Db::$db->query('', '
- SELECT id_member, real_name, total_time_logged_in
+ $members_result = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name, total_time_logged_in
FROM {db_prefix}members
WHERE is_activated = {int:is_activated}' .
(!empty($temp) ? ' AND id_member IN ({array_int:member_list_cached})' : '') . '
ORDER BY total_time_logged_in DESC
LIMIT 20',
- array(
+ [
'member_list_cached' => $temp,
'is_activated' => 1,
- )
+ ],
);
- Utils::$context['stats_blocks']['time_online'] = array();
- $temp2 = array();
+ Utils::$context['stats_blocks']['time_online'] = [];
+ $temp2 = [];
$max_time_online = 1;
- while ($row_members = Db::$db->fetch_assoc($members_result))
- {
+
+ while ($row_members = Db::$db->fetch_assoc($members_result)) {
$temp2[] = (int) $row_members['id_member'];
- if (count(Utils::$context['stats_blocks']['time_online']) >= 10)
+
+ if (count(Utils::$context['stats_blocks']['time_online']) >= 10) {
continue;
+ }
// Figure out the days, hours and minutes.
$timeDays = floor($row_members['total_time_logged_in'] / 86400);
@@ -581,43 +594,48 @@ public function execute(): void
// Figure out which things to show... (days, hours, minutes, etc.)
$timelogged = '';
- if ($timeDays > 0)
+
+ if ($timeDays > 0) {
$timelogged .= $timeDays . Lang::$txt['total_time_logged_d'];
- if ($timeHours > 0)
+ }
+
+ if ($timeHours > 0) {
$timelogged .= $timeHours . Lang::$txt['total_time_logged_h'];
+ }
$timelogged .= floor(($row_members['total_time_logged_in'] % 3600) / 60) . Lang::$txt['total_time_logged_m'];
- Utils::$context['stats_blocks']['time_online'][] = array(
+ Utils::$context['stats_blocks']['time_online'][] = [
'id' => $row_members['id_member'],
'name' => $row_members['real_name'],
'num' => $timelogged,
'seconds_online' => $row_members['total_time_logged_in'],
'href' => Config::$scripturl . '?action=profile;u=' . $row_members['id_member'],
- 'link' => ' ' . $row_members['real_name'] . ''
- );
+ 'link' => ' ' . $row_members['real_name'] . '',
+ ];
- if ($max_time_online < $row_members['total_time_logged_in'])
+ if ($max_time_online < $row_members['total_time_logged_in']) {
$max_time_online = $row_members['total_time_logged_in'];
+ }
}
Db::$db->free_result($members_result);
- foreach (Utils::$context['stats_blocks']['time_online'] as $i => $member)
- {
+ foreach (Utils::$context['stats_blocks']['time_online'] as $i => $member) {
Utils::$context['stats_blocks']['time_online'][$i]['percent'] = round(($member['seconds_online'] * 100) / $max_time_online);
}
// Cache the ones we found for a bit, just so we don't have to look again.
- if ($temp !== $temp2)
+ if ($temp !== $temp2) {
CacheApi::put('stats_total_time_members', $temp2, 480);
+ }
// Likes.
- if (!empty(Config::$modSettings['enable_likes']))
- {
+ if (!empty(Config::$modSettings['enable_likes'])) {
// Liked messages top 10.
- Utils::$context['stats_blocks']['liked_messages'] = array();
+ Utils::$context['stats_blocks']['liked_messages'] = [];
$max_liked_message = 1;
- $liked_messages = Db::$db->query('', '
- SELECT m.id_msg, m.subject, m.likes, m.id_board, m.id_topic, t.approved
+ $liked_messages = Db::$db->query(
+ '',
+ 'SELECT m.id_msg, m.subject, m.likes, m.id_board, m.id_topic, t.approved
FROM (
SELECT n.id_msg, n.subject, n.likes, n.id_board, n.id_topic
FROM {db_prefix}messages as n
@@ -631,39 +649,39 @@ public function execute(): void
AND t.approved = {int:is_approved}' : '') . '
ORDER BY m.likes DESC
LIMIT 10',
- array(
+ [
'recycle_board' => Config::$modSettings['recycle_board'],
'is_approved' => 1,
- )
+ ],
);
- while ($row_liked_message = Db::$db->fetch_assoc($liked_messages))
- {
+ while ($row_liked_message = Db::$db->fetch_assoc($liked_messages)) {
Lang::censorText($row_liked_message['subject']);
- Utils::$context['stats_blocks']['liked_messages'][] = array(
+ Utils::$context['stats_blocks']['liked_messages'][] = [
'id' => $row_liked_message['id_topic'],
'subject' => $row_liked_message['subject'],
'num' => $row_liked_message['likes'],
'href' => Config::$scripturl . '?msg=' . $row_liked_message['id_msg'],
- 'link' => ' ' . $row_liked_message['subject'] . ''
- );
+ 'link' => ' ' . $row_liked_message['subject'] . '',
+ ];
- if ($max_liked_message < $row_liked_message['likes'])
+ if ($max_liked_message < $row_liked_message['likes']) {
$max_liked_message = $row_liked_message['likes'];
+ }
}
Db::$db->free_result($liked_messages);
- foreach (Utils::$context['stats_blocks']['liked_messages'] as $i => $liked_messages)
- {
+ foreach (Utils::$context['stats_blocks']['liked_messages'] as $i => $liked_messages) {
Utils::$context['stats_blocks']['liked_messages'][$i]['percent'] = round(($liked_messages['num'] * 100) / $max_liked_message);
}
// Liked users top 10.
- Utils::$context['stats_blocks']['liked_users'] = array();
+ Utils::$context['stats_blocks']['liked_users'] = [];
$max_liked_users = 1;
- $liked_users = Db::$db->query('', '
- SELECT m.id_member AS liked_user, COUNT(l.content_id) AS count, mem.real_name
+ $liked_users = Db::$db->query(
+ '',
+ 'SELECT m.id_member AS liked_user, COUNT(l.content_id) AS count, mem.real_name
FROM {db_prefix}user_likes AS l
INNER JOIN {db_prefix}messages AS m ON (l.content_id = m.id_msg)
INNER JOIN {db_prefix}members AS mem ON (m.id_member = mem.id_member)
@@ -672,51 +690,51 @@ public function execute(): void
GROUP BY m.id_member, mem.real_name
ORDER BY count DESC
LIMIT 10',
- array(
+ [
'no_posts' => 0,
'zero' => 0,
- )
+ ],
);
- while ($row_liked_users = Db::$db->fetch_assoc($liked_users))
- {
- Utils::$context['stats_blocks']['liked_users'][] = array(
+ while ($row_liked_users = Db::$db->fetch_assoc($liked_users)) {
+ Utils::$context['stats_blocks']['liked_users'][] = [
'id' => $row_liked_users['liked_user'],
'num' => $row_liked_users['count'],
'href' => Config::$scripturl . '?action=profile;u=' . $row_liked_users['liked_user'],
'name' => $row_liked_users['real_name'],
'link' => ' ' . $row_liked_users['real_name'] . '',
- );
+ ];
- if ($max_liked_users < $row_liked_users['count'])
+ if ($max_liked_users < $row_liked_users['count']) {
$max_liked_users = $row_liked_users['count'];
+ }
}
Db::$db->free_result($liked_users);
- foreach (Utils::$context['stats_blocks']['liked_users'] as $i => $liked_users)
- {
+ foreach (Utils::$context['stats_blocks']['liked_users'] as $i => $liked_users) {
Utils::$context['stats_blocks']['liked_users'][$i]['percent'] = round(($liked_users['num'] * 100) / $max_liked_users);
}
}
// Activity by month.
- $months_result = Db::$db->query('', '
- SELECT
+ $months_result = Db::$db->query(
+ '',
+ 'SELECT
YEAR(date) AS stats_year, MONTH(date) AS stats_month, SUM(hits) AS hits, SUM(registers) AS registers, SUM(topics) AS topics, SUM(posts) AS posts, MAX(most_on) AS most_on, COUNT(*) AS num_days
FROM {db_prefix}log_activity
GROUP BY stats_year, stats_month',
- array()
+ [],
);
- Utils::$context['yearly'] = array();
- while ($row_months = Db::$db->fetch_assoc($months_result))
- {
+ Utils::$context['yearly'] = [];
+
+ while ($row_months = Db::$db->fetch_assoc($months_result)) {
$ID_MONTH = $row_months['stats_year'] . sprintf('%02d', $row_months['stats_month']);
$expanded = !empty($_SESSION['expanded_stats'][$row_months['stats_year']]) && in_array($row_months['stats_month'], $_SESSION['expanded_stats'][$row_months['stats_year']]);
- if (!isset(Utils::$context['yearly'][$row_months['stats_year']]))
- Utils::$context['yearly'][$row_months['stats_year']] = array(
+ if (!isset(Utils::$context['yearly'][$row_months['stats_year']])) {
+ Utils::$context['yearly'][$row_months['stats_year']] = [
'year' => $row_months['stats_year'],
'new_topics' => 0,
'new_posts' => 0,
@@ -724,17 +742,18 @@ public function execute(): void
'most_members_online' => 0,
'hits' => 0,
'num_months' => 0,
- 'months' => array(),
+ 'months' => [],
'expanded' => false,
'current_year' => $row_months['stats_year'] == date('Y'),
- );
+ ];
+ }
- Utils::$context['yearly'][$row_months['stats_year']]['months'][(int) $row_months['stats_month']] = array(
+ Utils::$context['yearly'][$row_months['stats_year']]['months'][(int) $row_months['stats_month']] = [
'id' => $ID_MONTH,
- 'date' => array(
+ 'date' => [
'month' => sprintf('%02d', $row_months['stats_month']),
- 'year' => $row_months['stats_year']
- ),
+ 'year' => $row_months['stats_year'],
+ ],
'href' => Config::$scripturl . '?action=stats;' . ($expanded ? 'collapse' : 'expand') . '=' . $ID_MONTH . '#m' . $ID_MONTH,
'link' => ' ' . Lang::$txt['months_titles'][(int) $row_months['stats_month']] . ' ' . $row_months['stats_year'] . '',
'month' => Lang::$txt['months_titles'][(int) $row_months['stats_month']],
@@ -745,9 +764,9 @@ public function execute(): void
'most_members_online' => Lang::numberFormat($row_months['most_on']),
'hits' => Lang::numberFormat($row_months['hits']),
'num_days' => $row_months['num_days'],
- 'days' => array(),
- 'expanded' => $expanded
- );
+ 'days' => [],
+ 'expanded' => $expanded,
+ ];
Utils::$context['yearly'][$row_months['stats_year']]['new_topics'] += $row_months['topics'];
Utils::$context['yearly'][$row_months['stats_year']]['new_posts'] += $row_months['posts'];
@@ -760,9 +779,9 @@ public function execute(): void
krsort(Utils::$context['yearly']);
- Utils::$context['collapsed_years'] = array();
- foreach (Utils::$context['yearly'] as $year => $data)
- {
+ Utils::$context['collapsed_years'] = [];
+
+ foreach (Utils::$context['yearly'] as $year => $data) {
// This gets rid of the filesort on the query ;).
krsort(Utils::$context['yearly'][$year]['months']);
@@ -773,22 +792,23 @@ public function execute(): void
Utils::$context['yearly'][$year]['hits'] = Lang::numberFormat($data['hits']);
// Keep a list of collapsed years.
- if (!$data['expanded'] && !$data['current_year'])
+ if (!$data['expanded'] && !$data['current_year']) {
Utils::$context['collapsed_years'][] = $year;
+ }
}
// Custom stats (just add a template_layer to add it to the template!)
IntegrationHook::call('integrate_forum_stats');
- if (empty($_SESSION['expanded_stats']))
+ if (empty($_SESSION['expanded_stats'])) {
return;
+ }
- $condition_text = array();
- $condition_params = array();
- foreach ($_SESSION['expanded_stats'] as $year => $months)
- {
- if (!empty($months))
- {
+ $condition_text = [];
+ $condition_params = [];
+
+ foreach ($_SESSION['expanded_stats'] as $year => $months) {
+ if (!empty($months)) {
$condition_text[] = 'YEAR(date) = {int:year_' . $year . '} AND MONTH(date) IN ({array_int:months_' . $year . '})';
$condition_params['year_' . $year] = $year;
$condition_params['months_' . $year] = $months;
@@ -796,8 +816,9 @@ public function execute(): void
}
// No daily stats to even look at?
- if (empty($condition_text))
+ if (empty($condition_text)) {
return;
+ }
$this->getDailyStats(implode(' OR ', $condition_text), $condition_params);
}
@@ -813,8 +834,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;
}
@@ -845,19 +867,20 @@ protected function __construct()
* @param string $condition_string An SQL condition string
* @param array $condition_parameters Parameters for $condition_string
*/
- protected function getDailyStats($condition_string, $condition_parameters = array())
+ protected function getDailyStats($condition_string, $condition_parameters = [])
{
// Activity by day.
- $days_result = Db::$db->query('', '
- SELECT YEAR(date) AS stats_year, MONTH(date) AS stats_month, DAYOFMONTH(date) AS stats_day, topics, posts, registers, most_on, hits
+ $days_result = Db::$db->query(
+ '',
+ 'SELECT YEAR(date) AS stats_year, MONTH(date) AS stats_month, DAYOFMONTH(date) AS stats_day, topics, posts, registers, most_on, hits
FROM {db_prefix}log_activity
WHERE ' . $condition_string . '
ORDER BY stats_day ASC',
- $condition_parameters
+ $condition_parameters,
);
- while ($row_days = Db::$db->fetch_assoc($days_result))
- {
- Utils::$context['yearly'][$row_days['stats_year']]['months'][(int) $row_days['stats_month']]['days'][] = array(
+
+ while ($row_days = Db::$db->fetch_assoc($days_result)) {
+ Utils::$context['yearly'][$row_days['stats_year']]['months'][(int) $row_days['stats_month']]['days'][] = [
'day' => sprintf('%02d', $row_days['stats_day']),
'month' => sprintf('%02d', $row_days['stats_month']),
'year' => $row_days['stats_year'],
@@ -865,15 +888,16 @@ protected function getDailyStats($condition_string, $condition_parameters = arra
'new_posts' => Lang::numberFormat($row_days['posts']),
'new_members' => Lang::numberFormat($row_days['registers']),
'most_members_online' => Lang::numberFormat($row_days['most_on']),
- 'hits' => Lang::numberFormat($row_days['hits'])
- );
+ 'hits' => Lang::numberFormat($row_days['hits']),
+ ];
}
Db::$db->free_result($days_result);
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Stats::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Stats::exportStatic')) {
Stats::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/TopicMerge.php b/Sources/Actions/TopicMerge.php
index b575687ffe..f0d5242ecf 100644
--- a/Sources/Actions/TopicMerge.php
+++ b/Sources/Actions/TopicMerge.php
@@ -16,25 +16,23 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
-use SMF\BBCodeParser;
use SMF\Board;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Logging;
-use SMF\Msg;
use SMF\Mail;
+use SMF\Msg;
use SMF\PageIndex;
+use SMF\Search\SearchApi;
use SMF\Theme;
use SMF\Time;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
-use SMF\Search\SearchApi;
/**
* Handles merging of topics.
@@ -48,14 +46,14 @@ class TopicMerge implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'MergeTopics',
- 'initiate' => false,
+ 'mergeIndex' => 'MergeIndex',
'mergeExecute' => 'MergeExecute',
- ),
- );
+ 'mergeDone' => 'MergeDone',
+ ],
+ ];
/*******************
* Public properties
@@ -74,7 +72,7 @@ class TopicMerge implements ActionInterface
*
* IDs of the topics to merge.
*/
- public array $topics = array();
+ public array $topics = [];
/**************************
* Public static properties
@@ -85,12 +83,12 @@ class TopicMerge implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'index' => 'index',
'done' => 'done',
'merge' => 'merge',
'options' => 'options',
- );
+ ];
/*********************
* Internal properties
@@ -101,7 +99,7 @@ class TopicMerge implements ActionInterface
*
*
*/
- protected array $topic_data = array();
+ protected array $topic_data = [];
/**
* @var int
@@ -122,21 +120,21 @@ class TopicMerge implements ActionInterface
*
*
*/
- protected array $boardTotals = array();
+ protected array $boardTotals = [];
/**
* @var array
*
*
*/
- protected array $boards = array();
+ protected array $boards = [];
/**
* @var array
*
*
*/
- protected array $polls = array();
+ protected array $polls = [];
/**
* @var int
@@ -171,14 +169,14 @@ class TopicMerge implements ActionInterface
*
*
*/
- protected array $can_approve_boards = array();
+ protected array $can_approve_boards = [];
/**
* @var array
*
*
*/
- protected array $merge_boards = array();
+ protected array $merge_boards = [];
/****************************
* Internal static properties
@@ -209,10 +207,11 @@ public function execute(): void
// Load the template....
Theme::loadTemplate('MoveTopic');
- $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);
+ }
}
/**
@@ -226,8 +225,9 @@ public function execute(): void
*/
public function index()
{
- if (!isset($_GET['from']))
+ if (!isset($_GET['from'])) {
ErrorHandler::fatalLang('no_access', false);
+ }
$_GET['from'] = (int) $_GET['from'];
@@ -235,26 +235,24 @@ public function index()
Utils::$context['target_board'] = $_REQUEST['targetboard'];
// Prepare a handy query bit for approval...
- if (Config::$modSettings['postmod_active'])
- {
+ if (Config::$modSettings['postmod_active']) {
$can_approve_boards = User::$me->boardsAllowedTo('approve_posts');
- $onlyApproved = $can_approve_boards !== array(0) && !in_array($_REQUEST['targetboard'], $can_approve_boards);
- }
- else
- {
+ $onlyApproved = $can_approve_boards !== [0] && !in_array($_REQUEST['targetboard'], $can_approve_boards);
+ } else {
$onlyApproved = false;
}
// How many topics are on this board? (used for paging.)
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}topics AS t
WHERE t.id_board = {int:id_board}' . ($onlyApproved ? '
AND t.approved = {int:is_approved}' : ''),
- array(
+ [
'id_board' => $_REQUEST['targetboard'],
'is_approved' => 1,
- )
+ ],
);
list($topiccount) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -263,22 +261,23 @@ public function index()
Utils::$context['page_index'] = new PageIndex(Config::$scripturl . '?action=mergetopics;from=' . $_GET['from'] . ';targetboard=' . $_REQUEST['targetboard'] . ';board=' . Board::$info->id . '.%1$d', $_REQUEST['start'], $topiccount, Config::$modSettings['defaultMaxTopics'], true);
// Get the topic's subject.
- $request = Db::$db->query('', '
- SELECT m.subject
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.subject
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
WHERE t.id_topic = {int:id_topic}
AND t.id_board = {int:current_board}' . ($onlyApproved ? '
AND t.approved = {int:is_approved}' : '') . '
LIMIT 1',
- array(
+ [
'current_board' => Board::$info->id,
'id_topic' => $_GET['from'],
'is_approved' => 1,
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('no_board');
}
list($subject) = Db::$db->fetch_row($request);
@@ -293,30 +292,32 @@ public function index()
// Check which boards you have merge permissions on.
$this->merge_boards = User::$me->boardsAllowedTo('merge_any');
- if (empty($this->merge_boards))
+ if (empty($this->merge_boards)) {
ErrorHandler::fatalLang('cannot_merge_any', 'user');
+ }
// No sense in loading this if you can only merge on this board
- if (count($this->merge_boards) > 1 || in_array(0, $this->merge_boards))
- {
+ if (count($this->merge_boards) > 1 || in_array(0, $this->merge_boards)) {
// Set up a couple of options for our board list
- $options = array(
+ $options = [
'not_redirection' => true,
'selected_board' => Utils::$context['target_board'],
- );
+ ];
// Only include these boards in the list (0 means you're an admin')
- if (!in_array(0, $this->merge_boards))
+ if (!in_array(0, $this->merge_boards)) {
$options['included_boards'] = $this->merge_boards;
+ }
Utils::$context['merge_categories'] = MessageIndex::getBoardList($options);
}
// Get some topics to merge it with.
- Utils::$context['topics'] = array();
+ Utils::$context['topics'] = [];
- $request = Db::$db->query('', '
- SELECT t.id_topic, m.subject, m.id_member, COALESCE(mem.real_name, m.poster_name) AS poster_name
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_topic, m.subject, m.id_member, COALESCE(mem.real_name, m.poster_name) AS poster_name
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
@@ -326,7 +327,7 @@ public function index()
AND t.approved = {int:is_approved}' : '') . '
ORDER BY {raw:sort}
LIMIT {int:offset}, {int:limit}',
- array(
+ [
'id_board' => $_REQUEST['targetboard'],
'id_topic' => $_GET['from'],
'sort' => 't.is_sticky DESC, t.id_last_msg DESC',
@@ -334,28 +335,27 @@ public function index()
'limit' => Config::$modSettings['defaultMaxTopics'],
'is_approved' => 1,
'not_redirect' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Lang::censorText($row['subject']);
- Utils::$context['topics'][] = array(
+ Utils::$context['topics'][] = [
'id' => $row['id_topic'],
- 'poster' => array(
+ 'poster' => [
'id' => $row['id_member'],
'name' => $row['poster_name'],
'href' => empty($row['id_member']) ? '' : Config::$scripturl . '?action=profile;u=' . $row['id_member'],
- 'link' => empty($row['id_member']) ? $row['poster_name'] : ' ' . $row['poster_name'] . ''
- ),
+ 'link' => empty($row['id_member']) ? $row['poster_name'] : ' ' . $row['poster_name'] . '',
+ ],
'subject' => $row['subject'],
- 'js_subject' => addcslashes(addslashes($row['subject']), '/')
- );
+ 'js_subject' => addcslashes(addslashes($row['subject']), '/'),
+ ];
}
Db::$db->free_result($request);
- if (empty(Utils::$context['topics']) && count($this->merge_boards) <= 1 && !in_array(0, $this->merge_boards))
- {
+ if (empty(Utils::$context['topics']) && count($this->merge_boards) <= 1 && !in_array(0, $this->merge_boards)) {
ErrorHandler::fatalLang('merge_need_more_topics');
}
@@ -374,63 +374,64 @@ public function options(): void
{
$this->initOptionsAndMerge();
- if (count($this->polls) > 1)
- {
- $request = Db::$db->query('', '
- SELECT t.id_topic, t.id_poll, m.subject, p.question
+ if (count($this->polls) > 1) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_topic, t.id_poll, m.subject, p.question
FROM {db_prefix}polls AS p
INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll)
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
WHERE p.id_poll IN ({array_int:polls})
LIMIT {int:limit}',
- array(
+ [
'polls' => $this->polls,
'limit' => count($this->polls),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- Utils::$context['polls'][] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ Utils::$context['polls'][] = [
'id' => $row['id_poll'],
- 'topic' => array(
+ 'topic' => [
'id' => $row['id_topic'],
- 'subject' => $row['subject']
- ),
+ 'subject' => $row['subject'],
+ ],
'question' => $row['question'],
- 'selected' => $row['id_topic'] == $this->firstTopic
- );
+ 'selected' => $row['id_topic'] == $this->firstTopic,
+ ];
}
Db::$db->free_result($request);
}
- if (count($this->boards) > 1)
- {
- $request = Db::$db->query('', '
- SELECT id_board, name
+ if (count($this->boards) > 1) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board, name
FROM {db_prefix}boards
WHERE id_board IN ({array_int:boards})
ORDER BY name
LIMIT {int:limit}',
- array(
+ [
'boards' => $this->boards,
'limit' => count($this->boards),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- Utils::$context['boards'][] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ Utils::$context['boards'][] = [
'id' => $row['id_board'],
'name' => $row['name'],
- 'selected' => $row['id_board'] == $this->topic_data[$this->firstTopic]['board']
- );
+ 'selected' => $row['id_board'] == $this->topic_data[$this->firstTopic]['board'],
+ ];
}
Db::$db->free_result($request);
}
Utils::$context['topics'] = $this->topic_data;
- foreach ($this->topic_data as $id => $topic)
+ foreach ($this->topic_data as $id => $topic) {
Utils::$context['topics'][$id]['selected'] = $topic['id'] == $this->firstTopic;
+ }
Utils::$context['page_title'] = Lang::$txt['merge'];
Utils::$context['sub_template'] = 'merge_extra_options';
@@ -452,38 +453,39 @@ public function merge(): void
// Determine target board.
$target_board = count($this->boards) > 1 ? (int) $_REQUEST['board'] : $this->boards[0];
- if (!in_array($target_board, $this->boards))
+ if (!in_array($target_board, $this->boards)) {
ErrorHandler::fatalLang('no_board');
+ }
// Determine which poll will survive and which polls won't.
$target_poll = count($this->polls) > 1 ? (int) $_POST['poll'] : (count($this->polls) == 1 ? $this->polls[0] : 0);
- if ($target_poll > 0 && !in_array($target_poll, $this->polls))
+ if ($target_poll > 0 && !in_array($target_poll, $this->polls)) {
ErrorHandler::fatalLang('no_access', false);
+ }
- $deleted_polls = empty($target_poll) ? $this->polls : array_diff($this->polls, array($target_poll));
+ $deleted_polls = empty($target_poll) ? $this->polls : array_diff($this->polls, [$target_poll]);
// Determine the subject of the newly merged topic - was a custom subject specified?
- if (empty($_POST['subject']) && isset($_POST['custom_subject']) && $_POST['custom_subject'] != '')
- {
- $target_subject = strtr(Utils::htmlTrim(Utils::htmlspecialchars($_POST['custom_subject'])), array("\r" => '', "\n" => '', "\t" => ''));
+ if (empty($_POST['subject']) && isset($_POST['custom_subject']) && $_POST['custom_subject'] != '') {
+ $target_subject = strtr(Utils::htmlTrim(Utils::htmlspecialchars($_POST['custom_subject'])), ["\r" => '', "\n" => '', "\t" => '']);
// Keep checking the length.
- if (Utils::entityStrlen($target_subject) > 100)
+ if (Utils::entityStrlen($target_subject) > 100) {
$target_subject = Utils::entitySubstr($target_subject, 0, 100);
+ }
// Nothing left - odd but pick the first topics subject.
- if ($target_subject == '')
+ if ($target_subject == '') {
$target_subject = $this->topic_data[$this->firstTopic]['subject'];
+ }
}
// A subject was selected from the list.
- elseif (!empty($this->topic_data[(int) $_POST['subject']]['subject']))
- {
+ elseif (!empty($this->topic_data[(int) $_POST['subject']]['subject'])) {
$target_subject = $this->topic_data[(int) $_POST['subject']]['subject'];
}
// Nothing worked? Just take the subject of the first message.
- else
- {
+ else {
$target_subject = $this->topic_data[$this->firstTopic]['subject'];
}
@@ -491,41 +493,35 @@ public function merge(): void
$topic_approved = 1;
$first_msg = 0;
- $request = Db::$db->query('', '
- SELECT approved, MIN(id_msg) AS first_msg, MAX(id_msg) AS last_msg, COUNT(*) AS message_count
+ $request = Db::$db->query(
+ '',
+ 'SELECT approved, MIN(id_msg) AS first_msg, MAX(id_msg) AS last_msg, COUNT(*) AS message_count
FROM {db_prefix}messages
WHERE id_topic IN ({array_int:topics})
GROUP BY approved
ORDER BY approved DESC',
- array(
+ [
'topics' => $this->topics,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// If this is approved, or is fully unapproved.
- if ($row['approved'] || !empty($first_msg))
- {
+ if ($row['approved'] || !empty($first_msg)) {
$first_msg = $row['first_msg'];
$last_msg = $row['last_msg'];
- if ($row['approved'])
- {
+ if ($row['approved']) {
$num_replies = $row['message_count'] - 1;
$num_unapproved = 0;
- }
- else
- {
+ } else {
$topic_approved = 0;
$num_replies = 0;
$num_unapproved = $row['message_count'];
}
- }
- else
- {
+ } else {
// If this has a lower first_msg then the first post is not approved and hence the number of replies was wrong!
- if ($first_msg > $row['first_msg'])
- {
+ if ($first_msg > $row['first_msg']) {
$first_msg = $row['first_msg'];
$num_replies++;
$topic_approved = 0;
@@ -537,14 +533,13 @@ public function merge(): void
Db::$db->free_result($request);
// Ensure we have a board stat for the target board.
- if (!isset($this->boardTotals[$target_board]))
- {
- $this->boardTotals[$target_board] = array(
+ if (!isset($this->boardTotals[$target_board])) {
+ $this->boardTotals[$target_board] = [
'posts' => 0,
'topics' => 0,
'unapproved_posts' => 0,
- 'unapproved_topics' => 0
- );
+ 'unapproved_topics' => 0,
+ ];
}
// Fix the topic count stuff depending on what the new one counts as.
@@ -555,33 +550,36 @@ public function merge(): void
$this->boardTotals[$target_board]['posts'] -= $topic_approved ? $num_replies + 1 : $num_replies;
// Get the member ID of the first and last message.
- $request = Db::$db->query('', '
- SELECT id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}messages
WHERE id_msg IN ({int:first_msg}, {int:last_msg})
ORDER BY id_msg
LIMIT 2',
- array(
+ [
'first_msg' => $first_msg,
'last_msg' => $last_msg,
- )
+ ],
);
list($member_started) = Db::$db->fetch_row($request);
list($member_updated) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// First and last message are the same, so only row was returned.
- if ($member_updated === null)
+ if ($member_updated === null) {
$member_updated = $member_started;
+ }
// Obtain all the message ids we are going to affect.
- $request = Db::$db->query('', '
- SELECT id_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_msg
FROM {db_prefix}messages
WHERE id_topic IN ({array_int:topic_list})',
- array(
+ [
'topic_list' => $this->topics,
- )
+ ],
);
$affected_msgs = Db::$db->fetch_all($request);
Db::$db->free_result($request);
@@ -589,44 +587,42 @@ public function merge(): void
// Assign the first topic ID to be the merged topic.
$id_topic = min($this->topics);
- $deleted_topics = array_diff($this->topics, array($id_topic));
- $updated_topics = array();
+ $deleted_topics = array_diff($this->topics, [$id_topic]);
+ $updated_topics = [];
// Create stub topics out of the remaining topics.
// We don't want the search index data though (For non-redirect merges).
- if (!isset($_POST['postRedirect']))
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_search_subjects
+ if (!isset($_POST['postRedirect'])) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_search_subjects
WHERE id_topic IN ({array_int:deleted_topics})',
- array(
+ [
'deleted_topics' => $deleted_topics,
- )
+ ],
);
}
- $posterOptions = array(
+ $posterOptions = [
'id' => User::$me->id,
'update_post_count' => false,
- );
+ ];
// We only need to do this if we're posting redirection topics...
- if (isset($_POST['postRedirect']))
- {
+ if (isset($_POST['postRedirect'])) {
// Replace tokens with links in the reason.
- $reason_replacements = array(
+ $reason_replacements = [
Lang::$txt['movetopic_auto_topic'] => '[iurl="' . Config::$scripturl . '?topic=' . $id_topic . '.0"]' . $target_subject . '[/iurl]',
- );
+ ];
// Should be in the boardwide language.
- if (User::$me->language != Lang::$default)
- {
+ if (User::$me->language != Lang::$default) {
Lang::load('index', Lang::$default);
// Make sure we catch both languages in the reason.
- $reason_replacements += array(
+ $reason_replacements += [
Lang::$txt['movetopic_auto_topic'] => '[iurl="' . Config::$scripturl . '?topic=' . $id_topic . '.0"]' . $target_subject . '[/iurl]',
- );
+ ];
}
$_POST['reason'] = Utils::htmlspecialchars($_POST['reason'], ENT_QUOTES);
@@ -641,29 +637,27 @@ public function merge(): void
// Redirect to the MERGED topic from topic list?
$redirect_topic = isset($_POST['redirect_topic']) ? $id_topic : 0;
- foreach ($deleted_topics as $this_old_topic)
- {
+ foreach ($deleted_topics as $this_old_topic) {
$redirect_subject = sprintf(Lang::$txt['merged_subject'], $this->topic_data[$this_old_topic]['subject']);
- $msgOptions = array(
+ $msgOptions = [
'icon' => 'moved',
'subject' => $redirect_subject,
'body' => $reason,
'approved' => 1,
- );
+ ];
- $topicOptions = array(
+ $topicOptions = [
'id' => $this_old_topic,
'is_approved' => true,
'lock_mode' => 1,
'board' => $this->topic_data[$this_old_topic]['board'],
'mark_as_read' => true,
- );
+ ];
// So we have to make the post. We need to do *this* here so we don't foul up indexes later
// and we have to fix them up later once everything else has happened.
- if (Msg::create($msgOptions, $topicOptions, $posterOptions))
- {
+ if (Msg::create($msgOptions, $topicOptions, $posterOptions)) {
$updated_topics[$this_old_topic] = $msgOptions['id'];
}
@@ -672,19 +666,16 @@ public function merge(): void
}
// Restore language strings to normal.
- if (User::$me->language != Lang::$default)
+ if (User::$me->language != Lang::$default) {
Lang::load('index');
+ }
}
// Grab the response prefix (like 'Re: ') in the default forum language.
- if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix')))
- {
- if (Lang::$default === User::$me->language)
- {
+ if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix'))) {
+ if (Lang::$default === User::$me->language) {
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
- }
- else
- {
+ } else {
Lang::load('index', Lang::$default, false);
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
Lang::load('index');
@@ -694,215 +685,226 @@ public function merge(): void
}
// Change the topic IDs of all messages that will be merged. Also adjust subjects if 'enforce subject' was checked.
- Db::$db->query('', '
- UPDATE {db_prefix}messages
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}messages
SET
id_topic = {int:id_topic},
id_board = {int:target_board}' . (empty($_POST['enforce_subject']) ? '' : ',
subject = {string:subject}') . '
WHERE id_topic IN ({array_int:topic_list})' . (!empty($updated_topics) ? '
AND id_msg NOT IN ({array_int:merge_msg})' : ''),
- array(
+ [
'topic_list' => $this->topics,
'id_topic' => $id_topic,
'merge_msg' => $updated_topics,
'target_board' => $target_board,
'subject' => Utils::$context['response_prefix'] . $target_subject,
- )
+ ],
);
// Any reported posts should reflect the new board.
- Db::$db->query('', '
- UPDATE {db_prefix}log_reported
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_reported
SET
id_topic = {int:id_topic},
id_board = {int:target_board}
WHERE id_topic IN ({array_int:topics_list})',
- array(
+ [
'topics_list' => $this->topics,
'id_topic' => $id_topic,
'target_board' => $target_board,
- )
+ ],
);
// Change the subject of the first message...
- Db::$db->query('', '
- UPDATE {db_prefix}messages
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}messages
SET subject = {string:target_subject}
WHERE id_msg = {int:first_msg}',
- array(
+ [
'first_msg' => $first_msg,
'target_subject' => $target_subject,
- )
+ ],
);
// Adjust all calendar events to point to the new topic.
- Db::$db->query('', '
- UPDATE {db_prefix}calendar
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}calendar
SET
id_topic = {int:id_topic},
id_board = {int:target_board}
WHERE id_topic IN ({array_int:deleted_topics})',
- array(
+ [
'deleted_topics' => $deleted_topics,
'id_topic' => $id_topic,
'target_board' => $target_board,
- )
+ ],
);
// Merge log topic entries.
// The unwatch setting comes from the oldest topic
- $request = Db::$db->query('', '
- SELECT id_member, MIN(id_msg) AS new_id_msg, unwatched
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, MIN(id_msg) AS new_id_msg, unwatched
FROM {db_prefix}log_topics
WHERE id_topic IN ({array_int:topics})
GROUP BY id_member, unwatched',
- array(
+ [
'topics' => $this->topics,
- )
+ ],
);
- if (Db::$db->num_rows($request) > 0)
- {
- $replaceEntries = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
- $replaceEntries[] = array($row['id_member'], $id_topic, $row['new_id_msg'], $row['unwatched']);
+ if (Db::$db->num_rows($request) > 0) {
+ $replaceEntries = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $replaceEntries[] = [$row['id_member'], $id_topic, $row['new_id_msg'], $row['unwatched']];
}
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_topics',
- array('id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int'),
+ ['id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int'],
$replaceEntries,
- array('id_member', 'id_topic')
+ ['id_member', 'id_topic'],
);
unset($replaceEntries);
// Get rid of the old log entries.
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_topics
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_topics
WHERE id_topic IN ({array_int:deleted_topics})',
- array(
+ [
'deleted_topics' => $deleted_topics,
- )
+ ],
);
}
Db::$db->free_result($request);
// Merge topic notifications.
- $notifications = isset($_POST['notifications']) && is_array($_POST['notifications']) ? array_intersect($this->topics, $_POST['notifications']) : array();
+ $notifications = isset($_POST['notifications']) && is_array($_POST['notifications']) ? array_intersect($this->topics, $_POST['notifications']) : [];
- if (!empty($notifications))
- {
- $request = Db::$db->query('', '
- SELECT id_member, MAX(sent) AS sent
+ if (!empty($notifications)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, MAX(sent) AS sent
FROM {db_prefix}log_notify
WHERE id_topic IN ({array_int:topics_list})
GROUP BY id_member',
- array(
+ [
'topics_list' => $notifications,
- )
+ ],
);
- if (Db::$db->num_rows($request) > 0)
- {
- $replaceEntries = array();
- while ($row = Db::$db->fetch_assoc($request))
- $replaceEntries[] = array($row['id_member'], $id_topic, 0, $row['sent']);
+ if (Db::$db->num_rows($request) > 0) {
+ $replaceEntries = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $replaceEntries[] = [$row['id_member'], $id_topic, 0, $row['sent']];
+ }
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_notify',
- array('id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'sent' => 'int'),
+ ['id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'sent' => 'int'],
$replaceEntries,
- array('id_member', 'id_topic', 'id_board')
+ ['id_member', 'id_topic', 'id_board'],
);
unset($replaceEntries);
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_topics
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_topics
WHERE id_topic IN ({array_int:deleted_topics})',
- array(
+ [
'deleted_topics' => $deleted_topics,
- )
+ ],
);
}
Db::$db->free_result($request);
}
// Get rid of the redundant polls.
- if (!empty($deleted_polls))
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}polls
+ if (!empty($deleted_polls)) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}polls
WHERE id_poll IN ({array_int:deleted_polls})',
- array(
+ [
'deleted_polls' => $deleted_polls,
- )
+ ],
);
- Db::$db->query('', '
- DELETE FROM {db_prefix}poll_choices
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}poll_choices
WHERE id_poll IN ({array_int:deleted_polls})',
- array(
+ [
'deleted_polls' => $deleted_polls,
- )
+ ],
);
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_polls
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_polls
WHERE id_poll IN ({array_int:deleted_polls})',
- array(
+ [
'deleted_polls' => $deleted_polls,
- )
+ ],
);
}
// Cycle through each board...
- foreach ($this->boardTotals as $id_board => $stats)
- {
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ foreach ($this->boardTotals as $id_board => $stats) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET
num_topics = CASE WHEN {int:topics} > num_topics THEN 0 ELSE num_topics - {int:topics} END,
unapproved_topics = CASE WHEN {int:unapproved_topics} > unapproved_topics THEN 0 ELSE unapproved_topics - {int:unapproved_topics} END,
num_posts = CASE WHEN {int:posts} > num_posts THEN 0 ELSE num_posts - {int:posts} END,
unapproved_posts = CASE WHEN {int:unapproved_posts} > unapproved_posts THEN 0 ELSE unapproved_posts - {int:unapproved_posts} END
WHERE id_board = {int:id_board}',
- array(
+ [
'id_board' => $id_board,
'topics' => $stats['topics'],
'unapproved_topics' => $stats['unapproved_topics'],
'posts' => $stats['posts'],
'unapproved_posts' => $stats['unapproved_posts'],
- )
+ ],
);
}
// Determine the board the final topic resides in
- $request = Db::$db->query('', '
- SELECT id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board
FROM {db_prefix}topics
WHERE id_topic = {int:id_topic}
LIMIT 1',
- array(
+ [
'id_topic' => $id_topic,
- )
+ ],
);
list($id_board) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Again, only do this if we're redirecting - otherwise delete
- if (isset($_POST['postRedirect']))
- {
+ if (isset($_POST['postRedirect'])) {
// Having done all that, now make sure we fix the merge/redirect topics upp before we
// leave here. Specifically: that there are no replies, no unapproved stuff, that the first
// and last posts are the same and so on and so forth.
- foreach ($updated_topics as $old_topic => $id_msg)
- {
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ foreach ($updated_topics as $old_topic => $id_msg) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET id_first_msg = id_last_msg,
id_member_started = {int:current_user},
id_member_updated = {int:current_user},
@@ -913,37 +915,38 @@ public function merge(): void
id_redirect_topic = {int:redirect_topic},
redirect_expires = {int:redirect_expires}
WHERE id_topic = {int:old_topic}',
- array(
+ [
'current_user' => User::$me->id,
'old_topic' => $old_topic,
'redirect_topic' => $redirect_topic,
- 'redirect_expires' => $redirect_expires
- )
+ 'redirect_expires' => $redirect_expires,
+ ],
);
}
}
// Ensure we don't accidentally delete the poll we want to keep...
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET id_poll = 0
WHERE id_topic IN ({array_int:deleted_topics})',
- array(
- 'deleted_topics' => $deleted_topics
- )
+ [
+ 'deleted_topics' => $deleted_topics,
+ ],
);
// Delete any remaining data regarding these topics, this is done before changing the properties of the merged topic (else we get duplicate keys)...
- if (!isset($_POST['postRedirect']))
- {
+ if (!isset($_POST['postRedirect'])) {
// Remove any remaining info about these topics...
// We do not need to remove the counts of the deleted topics, as we already removed these.
Topic::remove($deleted_topics, false, true, false);
}
// Assign the properties of the newly merged topic.
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET
id_board = {int:id_board},
id_member_started = {int:id_member_started},
@@ -957,7 +960,7 @@ public function merge(): void
is_sticky = {int:is_sticky},
approved = {int:approved}
WHERE id_topic = {int:id_topic}',
- array(
+ [
'id_board' => $target_board,
'is_sticky' => $this->is_sticky,
'approved' => $topic_approved,
@@ -970,7 +973,7 @@ public function merge(): void
'num_replies' => $num_replies,
'unapproved_posts' => $num_unapproved,
'num_views' => $this->num_views,
- )
+ ],
);
// Update all the statistics.
@@ -978,7 +981,7 @@ public function merge(): void
Logging::updateStats('subject', $id_topic, $target_subject);
Msg::updateLastMessages($this->boards);
- Logging::logAction('merge', array('topic' => $id_topic, 'board' => $id_board));
+ Logging::logAction('merge', ['topic' => $id_topic, 'board' => $id_board]);
// Notify people that these topics have been merged?
Mail::sendNotifications($id_topic, 'merge');
@@ -986,13 +989,12 @@ public function merge(): void
// If there's a search index that needs updating, update it...
$searchAPI = SearchApi::load();
- if (is_callable(array($searchAPI, 'topicMerge')))
- {
- $searchAPI->topicMerge($id_topic, $this->topics, $affected_msgs, empty($_POST['enforce_subject']) ? null : array(Utils::$context['response_prefix'], $target_subject));
+ if (is_callable([$searchAPI, 'topicMerge'])) {
+ $searchAPI->topicMerge($id_topic, $this->topics, $affected_msgs, empty($_POST['enforce_subject']) ? null : [Utils::$context['response_prefix'], $target_subject]);
}
// Merging is the sort of thing an external CMS might want to know about
- $merged_topic = array(
+ $merged_topic = [
'id_board' => $target_board,
'is_sticky' => $this->is_sticky,
'approved' => $topic_approved,
@@ -1006,9 +1008,9 @@ public function merge(): void
'unapproved_posts' => $num_unapproved,
'num_views' => $this->num_views,
'subject' => $target_subject,
- );
+ ];
- IntegrationHook::call('integrate_merge_topic', array($merged_topic, $updated_topics, $deleted_topics, $deleted_polls));
+ IntegrationHook::call('integrate_merge_topic', [$merged_topic, $updated_topics, $deleted_topics, $deleted_polls]);
// Send them to the all done page.
Utils::redirectexit('action=mergetopics;sa=done;to=' . $id_topic . ';targetboard=' . $target_board);
@@ -1020,7 +1022,7 @@ public function merge(): void
* - Accessed via ?action=mergetopics;sa=done.
* - Uses 'merge_done' sub template of the SplitTopics template.
*/
- function done()
+ public function done()
{
// Make sure the template knows everything...
Utils::$context['target_board'] = (int) $_GET['targetboard'];
@@ -1041,8 +1043,9 @@ function done()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -1062,7 +1065,7 @@ public static function call(): void
*
* @param array $topics The IDs of the topics to merge
*/
- public static function initiate($topics = array())
+ public static function initiate($topics = [])
{
self::load();
self::$obj->subaction = 'options';
@@ -1086,7 +1089,7 @@ public static function mergeIndex(): void
*
* @param array $topics The IDs of the topics to merge
*/
- public function mergeExecute($topics = array())
+ public static function mergeExecute($topics = [])
{
self::load();
self::$obj->subaction = !empty($_GET['sa']) && $_GET['sa'] === 'merge' ? 'merge' : 'options';
@@ -1114,14 +1117,14 @@ public static function mergeDone(): void
protected function __construct()
{
// The 'merge' sub-action used to be called 'execute'.
- if (!empty($_GET['sa']) && $_GET['sa'] === 'execute')
- {
+ if (!empty($_GET['sa']) && $_GET['sa'] === 'execute') {
$_GET['sa'] = 'merge';
$_REQUEST['sa'] = 'merge';
}
- if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
+ if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
+ }
}
/**
@@ -1135,34 +1138,37 @@ protected function initOptionsAndMerge()
$this->getTopics();
// There's nothing to merge with just one topic...
- if (empty($this->topics) || !is_array($this->topics) || count($this->topics) == 1)
+ if (empty($this->topics) || !is_array($this->topics) || count($this->topics) == 1) {
ErrorHandler::fatalLang('merge_need_more_topics');
+ }
// Make sure every topic is numeric, or some nasty things could be done with the DB.
$this->topics = array_map('intval', $this->topics);
// Joy of all joys, make sure they're not messing about with unapproved topics they can't see :P
- if (Config::$modSettings['postmod_active'])
+ if (Config::$modSettings['postmod_active']) {
$this->can_approve_boards = User::$me->boardsAllowedTo('approve_posts');
+ }
$this->getTopicData();
Utils::$context['is_approved'] = &$this->approved;
// If we didn't get any topics then they've been messing with unapproved stuff.
- if (empty($this->topic_data))
+ if (empty($this->topic_data)) {
ErrorHandler::fatalLang('no_topic_id');
+ }
- if (isset($_POST['postRedirect']) && !empty($this->lowestTopicBoard))
+ if (isset($_POST['postRedirect']) && !empty($this->lowestTopicBoard)) {
$this->boardTotals[$this->lowestTopicBoard]['topics']++;
+ }
// Will this be approved?
$this->approved = $this->topic_data[$this->firstTopic]['approved'];
$this->boards = array_values(array_unique($this->boards));
- if (!empty($this->topics))
- {
+ if (!empty($this->topics)) {
User::$me->isAllowedTo('merge_any', $this->boards);
Theme::loadTemplate('MoveTopic');
}
@@ -1176,16 +1182,19 @@ protected function initOptionsAndMerge()
protected function getTopics()
{
// Already set.
- if (count($this->topics) > 1)
+ if (count($this->topics) > 1) {
return;
+ }
// Handle URLs from MergeIndex.
- if (!empty($_GET['from']) && !empty($_GET['to']))
- $this->topics = array((int) $_GET['from'], (int) $_GET['to']);
+ if (!empty($_GET['from']) && !empty($_GET['to'])) {
+ $this->topics = [(int) $_GET['from'], (int) $_GET['to']];
+ }
// If we came from a form, the topic IDs came by post.
- if (!empty($_REQUEST['topics']) && is_array($_REQUEST['topics']))
+ if (!empty($_REQUEST['topics']) && is_array($_REQUEST['topics'])) {
$this->topics = (array) $_REQUEST['topics'];
+ }
}
/**
@@ -1193,8 +1202,9 @@ protected function getTopics()
*/
protected function getTopicData()
{
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
t.id_topic, t.id_board, t.id_poll, t.num_views, t.is_sticky, t.approved, t.num_replies, t.unapproved_posts, t.id_redirect_topic,
m1.subject, m1.poster_time AS time_started, COALESCE(mem1.id_member, 0) AS id_member_started, COALESCE(mem1.real_name, m1.poster_name) AS name_started,
m2.poster_time AS time_updated, COALESCE(mem2.id_member, 0) AS id_member_updated, COALESCE(mem2.real_name, m2.poster_name) AS name_updated
@@ -1206,44 +1216,43 @@ protected function getTopicData()
WHERE t.id_topic IN ({array_int:topic_list})
ORDER BY t.id_first_msg
LIMIT {int:limit}',
- array(
+ [
'topic_list' => $this->topics,
'limit' => count($this->topics),
- )
+ ],
);
- if (Db::$db->num_rows($request) < 2)
- {
+
+ if (Db::$db->num_rows($request) < 2) {
ErrorHandler::fatalLang('no_topic_id');
}
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Sorry, redirection topics can't be merged
- if (!empty($row['id_redirect_topic']))
+ if (!empty($row['id_redirect_topic'])) {
ErrorHandler::fatalLang('cannot_merge_redirect', false);
+ }
// Make a note for the board counts...
- if (!isset($this->boardTotals[$row['id_board']]))
- $this->boardTotals[$row['id_board']] = array(
+ if (!isset($this->boardTotals[$row['id_board']])) {
+ $this->boardTotals[$row['id_board']] = [
'posts' => 0,
'topics' => 0,
'unapproved_posts' => 0,
- 'unapproved_topics' => 0
- );
+ 'unapproved_topics' => 0,
+ ];
+ }
// We can't see unapproved topics here?
- if (Config::$modSettings['postmod_active'] && !$row['approved'] && $this->can_approve_boards != array(0) && in_array($row['id_board'], $this->can_approve_boards))
- {
+ if (Config::$modSettings['postmod_active'] && !$row['approved'] && $this->can_approve_boards != [0] && in_array($row['id_board'], $this->can_approve_boards)) {
// If we can't see it, we should not merge it and not adjust counts! Instead skip it.
unset($this->topics[$row['id_topic']]);
continue;
}
- elseif (!$row['approved'])
- {
+
+ if (!$row['approved']) {
$this->boardTotals[$row['id_board']]['unapproved_topics']++;
- }
- else
- {
+ } else {
$this->boardTotals[$row['id_board']]['topics']++;
}
@@ -1251,44 +1260,46 @@ protected function getTopicData()
$this->boardTotals[$row['id_board']]['posts'] += $row['num_replies'] + ($row['approved'] ? 1 : 0);
// In the case of making a redirect, the topic count goes up by one due to the redirect topic.
- if (isset($_POST['postRedirect']))
+ if (isset($_POST['postRedirect'])) {
$this->boardTotals[$row['id_board']]['topics']--;
+ }
- $this->topic_data[$row['id_topic']] = array(
+ $this->topic_data[$row['id_topic']] = [
'id' => $row['id_topic'],
'board' => $row['id_board'],
'poll' => $row['id_poll'],
'num_views' => $row['num_views'],
'subject' => $row['subject'],
- 'started' => array(
+ 'started' => [
'time' => Time::create('@' . $row['time_started'])->format(),
'timestamp' => $row['time_started'],
'href' => empty($row['id_member_started']) ? '' : Config::$scripturl . '?action=profile;u=' . $row['id_member_started'],
- 'link' => empty($row['id_member_started']) ? $row['name_started'] : ' ' . $row['name_started'] . ''
- ),
- 'updated' => array(
+ 'link' => empty($row['id_member_started']) ? $row['name_started'] : ' ' . $row['name_started'] . '',
+ ],
+ 'updated' => [
'time' => Time::create('@' . $row['time_updated'])->format(),
'timestamp' => $row['time_updated'],
'href' => empty($row['id_member_updated']) ? '' : Config::$scripturl . '?action=profile;u=' . $row['id_member_updated'],
- 'link' => empty($row['id_member_updated']) ? $row['name_updated'] : ' ' . $row['name_updated'] . ''
- ),
+ 'link' => empty($row['id_member_updated']) ? $row['name_updated'] : ' ' . $row['name_updated'] . '',
+ ],
'approved' => $row['approved'],
- );
+ ];
$this->num_views += $row['num_views'];
$this->boards[] = $row['id_board'];
// If there's no poll, id_poll == 0...
- if ($row['id_poll'] > 0)
+ if ($row['id_poll'] > 0) {
$this->polls[] = $row['id_poll'];
+ }
// Store the id_topic with the lowest id_first_msg.
- if (empty($this->firstTopic))
+ if (empty($this->firstTopic)) {
$this->firstTopic = $row['id_topic'];
+ }
// Lowest topic id gets selected as surviving topic id. We need to store this board so we can adjust the topic count (This one will not have a redirect topic)
- if ($row['id_topic'] < $this->lowestTopicId || empty($this->lowestTopicId))
- {
+ if ($row['id_topic'] < $this->lowestTopicId || empty($this->lowestTopicId)) {
$this->lowestTopicId = $row['id_topic'];
$this->lowestTopicBoard = $row['id_board'];
}
@@ -1305,34 +1316,38 @@ protected function getMergeBoards()
{
$this->merge_boards = User::$me->boardsAllowedTo('merge_any');
- if (empty($this->merge_boards))
+ if (empty($this->merge_boards)) {
ErrorHandler::fatalLang('cannot_merge_any', 'user');
+ }
// Make sure they can see all boards....
- $request = Db::$db->query('', '
- SELECT b.id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board
FROM {db_prefix}boards AS b
WHERE b.id_board IN ({array_int:boards})
AND {query_see_board}' . (!in_array(0, $this->merge_boards) ? '
AND b.id_board IN ({array_int:merge_boards})' : '') . '
LIMIT {int:limit}',
- array(
+ [
'boards' => $this->boards,
'merge_boards' => $this->merge_boards,
'limit' => count($this->boards),
- )
+ ],
);
// If the number of boards that's in the output isn't exactly the same as we've put in there, you're in trouble.
- if (Db::$db->num_rows($request) != count($this->boards))
+ if (Db::$db->num_rows($request) != count($this->boards)) {
ErrorHandler::fatalLang('no_board');
+ }
Db::$db->free_result($request);
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TopicMerge::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TopicMerge::exportStatic')) {
TopicMerge::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/TopicMove.php b/Sources/Actions/TopicMove.php
index bcdf4c66e2..e973d20e7f 100644
--- a/Sources/Actions/TopicMove.php
+++ b/Sources/Actions/TopicMove.php
@@ -14,21 +14,16 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
-use SMF\Msg;
-use SMF\Mail;
use SMF\Security;
use SMF\Theme;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
-use SMF\Search\SearchApi;
/**
* This action provides UI to allow topics to be moved from one board to another.
@@ -42,12 +37,11 @@ class TopicMove implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'MoveTopic',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -78,46 +72,46 @@ class TopicMove implements ActionInterface
*/
public function execute(): void
{
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
ErrorHandler::fatalLang('no_access', false);
+ }
- $request = Db::$db->query('', '
- SELECT t.id_member_started, ms.subject, t.approved
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_member_started, ms.subject, t.approved
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
WHERE t.id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
- )
+ ],
);
- list ($id_member_started, Utils::$context['subject'], Utils::$context['is_approved']) = Db::$db->fetch_row($request);
+ list($id_member_started, Utils::$context['subject'], Utils::$context['is_approved']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Can they see it - if not approved?
- if (Config::$modSettings['postmod_active'] && !Utils::$context['is_approved'])
+ if (Config::$modSettings['postmod_active'] && !Utils::$context['is_approved']) {
User::$me->isAllowedTo('approve_posts');
+ }
// Permission check!
// @todo
- if (!User::$me->allowedTo('move_any'))
- {
- if ($id_member_started == User::$me->id)
- {
+ if (!User::$me->allowedTo('move_any')) {
+ if ($id_member_started == User::$me->id) {
User::$me->isAllowedTo('move_own');
- }
- else
+ } else {
User::$me->isAllowedTo('move_any');
+ }
}
Utils::$context['move_any'] = User::$me->is_admin || Config::$modSettings['topic_move_any'];
- $boards = array();
+ $boards = [];
+
+ if (!Utils::$context['move_any']) {
+ $boards = array_diff(User::$me->boardsAllowedTo('post_new', true), [Board::$info->id]);
- if (!Utils::$context['move_any'])
- {
- $boards = array_diff(User::$me->boardsAllowedTo('post_new', true), array(Board::$info->id));
- if (empty($boards))
- {
+ if (empty($boards)) {
// No boards? Too bad...
ErrorHandler::fatalLang('moveto_no_boards');
}
@@ -125,34 +119,35 @@ public function execute(): void
Theme::loadTemplate('MoveTopic');
- $options = array(
+ $options = [
'not_redirection' => true,
'use_permissions' => Utils::$context['move_any'],
- );
+ ];
- if (!empty($_SESSION['move_to_topic']) && $_SESSION['move_to_topic'] != Board::$info->id)
+ if (!empty($_SESSION['move_to_topic']) && $_SESSION['move_to_topic'] != Board::$info->id) {
$options['selected_board'] = $_SESSION['move_to_topic'];
+ }
- if (!Utils::$context['move_any'])
+ if (!Utils::$context['move_any']) {
$options['included_boards'] = $boards;
+ }
Utils::$context['categories'] = MessageIndex::getBoardList($options);
Utils::$context['page_title'] = Lang::$txt['move_topic'];
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?topic=' . Topic::$topic_id . '.0',
'name' => Utils::$context['subject'],
- );
+ ];
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'name' => Lang::$txt['move_topic'],
- );
+ ];
Utils::$context['back_to_topic'] = isset($_REQUEST['goback']);
- if (User::$me->language != Lang::$default)
- {
+ if (User::$me->language != Lang::$default) {
Lang::load('index', Lang::$default);
$temp = Lang::$txt['movetopic_default'];
Lang::load('index');
@@ -166,7 +161,6 @@ public function execute(): void
// Register this form and get a sequence number in Utils::$context.
Security::checkSubmitOnce('register');
-
}
/***********************
@@ -180,8 +174,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 +202,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TopicMove::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TopicMove::exportStatic')) {
TopicMove::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/TopicMove2.php b/Sources/Actions/TopicMove2.php
index a7c5a99864..625a093307 100644
--- a/Sources/Actions/TopicMove2.php
+++ b/Sources/Actions/TopicMove2.php
@@ -14,24 +14,20 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
+use SMF\Cache\CacheApi;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Logging;
-use SMF\MessageIndex;
-use SMF\Msg;
use SMF\Mail;
+use SMF\Msg;
use SMF\Security;
-use SMF\Theme;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
-use SMF\Search\SearchApi;
/**
* This action handles moving topics from one board to another board.
@@ -45,12 +41,12 @@ class TopicMove2 implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'MoveTopic2',
- ),
- );
+ 'moveTopicConcurrence' => 'moveTopicConcurrence',
+ ],
+ ];
/****************************
* Internal static properties
@@ -79,12 +75,12 @@ class TopicMove2 implements ActionInterface
*/
public function execute(): void
{
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
ErrorHandler::fatalLang('no_access', false);
+ }
// You can't choose to have a redirection topic and use an empty reason.
- if (isset($_POST['postRedirect']) && (!isset($_POST['reason']) || trim($_POST['reason']) == ''))
- {
+ if (isset($_POST['postRedirect']) && (!isset($_POST['reason']) || trim($_POST['reason']) == '')) {
ErrorHandler::fatalLang('movetopic_no_reason', false);
}
@@ -93,31 +89,29 @@ public function execute(): void
// Make sure this form hasn't been submitted before.
Security::checkSubmitOnce('check');
- $request = Db::$db->query('', '
- SELECT id_member_started, id_first_msg, approved
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member_started, id_first_msg, approved
FROM {db_prefix}topics
WHERE id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
- )
+ ],
);
list($id_member_started, $id_first_msg, Utils::$context['is_approved']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Can they see it?
- if (!Utils::$context['is_approved'])
+ if (!Utils::$context['is_approved']) {
User::$me->isAllowedTo('approve_posts');
+ }
// Can they move topics on this board?
- if (!User::$me->allowedTo('move_any'))
- {
- if ($id_member_started == User::$me->id)
- {
+ if (!User::$me->allowedTo('move_any')) {
+ if ($id_member_started == User::$me->id) {
User::$me->isAllowedTo('move_own');
- }
- else
- {
+ } else {
User::$me->isAllowedTo('move_any');
}
}
@@ -128,8 +122,9 @@ public function execute(): void
$_POST['toboard'] = (int) $_POST['toboard'];
// Make sure they can see the board they are trying to move to (and get whether posts count in the target board).
- $request = Db::$db->query('', '
- SELECT b.count_posts, b.name, m.subject
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.count_posts, b.name, m.subject
FROM {db_prefix}boards AS b
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
@@ -137,14 +132,14 @@ public function execute(): void
AND b.id_board = {int:to_board}
AND b.redirect = {string:blank_redirect}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
'to_board' => $_POST['toboard'],
'blank_redirect' => '',
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('no_board');
}
list($pcounter, $board_name, $subject) = Db::$db->fetch_row($request);
@@ -154,28 +149,22 @@ public function execute(): void
$_SESSION['move_to_topic'] = $_POST['toboard'];
// Rename the topic...
- if (isset($_POST['reset_subject'], $_POST['custom_subject']) && $_POST['custom_subject'] != '')
- {
- $_POST['custom_subject'] = strtr(Utils::htmlTrim(Utils::htmlspecialchars($_POST['custom_subject'])), array("\r" => '', "\n" => '', "\t" => ''));
+ if (isset($_POST['reset_subject'], $_POST['custom_subject']) && $_POST['custom_subject'] != '') {
+ $_POST['custom_subject'] = strtr(Utils::htmlTrim(Utils::htmlspecialchars($_POST['custom_subject'])), ["\r" => '', "\n" => '', "\t" => '']);
// Keep checking the length.
- if (Utils::entityStrlen($_POST['custom_subject']) > 100)
+ if (Utils::entityStrlen($_POST['custom_subject']) > 100) {
$_POST['custom_subject'] = Utils::entitySubstr($_POST['custom_subject'], 0, 100);
+ }
// If it's still valid move onwards and upwards.
- if ($_POST['custom_subject'] != '')
- {
- if (isset($_POST['enforce_subject']))
- {
+ if ($_POST['custom_subject'] != '') {
+ if (isset($_POST['enforce_subject'])) {
// Get a response prefix, but in the forum's default language.
- if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix')))
- {
- if (Lang::$default === User::$me->language)
- {
+ if (!isset(Utils::$context['response_prefix']) && !(Utils::$context['response_prefix'] = CacheApi::get('response_prefix'))) {
+ if (Lang::$default === User::$me->language) {
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
- }
- else
- {
+ } else {
Lang::load('index', Lang::$default, false);
Utils::$context['response_prefix'] = Lang::$txt['response_prefix'];
Lang::load('index');
@@ -183,25 +172,27 @@ public function execute(): void
CacheApi::put('response_prefix', Utils::$context['response_prefix'], 600);
}
- Db::$db->query('', '
- UPDATE {db_prefix}messages
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}messages
SET subject = {string:subject}
WHERE id_topic = {int:current_topic}',
- array(
+ [
'current_topic' => Topic::$topic_id,
'subject' => Utils::$context['response_prefix'] . $_POST['custom_subject'],
- )
+ ],
);
}
- Db::$db->query('', '
- UPDATE {db_prefix}messages
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}messages
SET subject = {string:custom_subject}
WHERE id_msg = {int:id_first_msg}',
- array(
+ [
'id_first_msg' => $id_first_msg,
'custom_subject' => $_POST['custom_subject'],
- )
+ ],
);
// Fix the subject cache.
@@ -211,24 +202,22 @@ public function execute(): void
// Create a link to this in the old board.
// @todo Does this make sense if the topic was unapproved before? I'd just about say so.
- if (isset($_POST['postRedirect']))
- {
+ if (isset($_POST['postRedirect'])) {
// Replace tokens with links in the reason.
- $reason_replacements = array(
+ $reason_replacements = [
Lang::$txt['movetopic_auto_board'] => '[url="' . Config::$scripturl . '?board=' . $_POST['toboard'] . '.0"]' . $board_name . '[/url]',
Lang::$txt['movetopic_auto_topic'] => '[iurl]' . Config::$scripturl . '?topic=' . Topic::$topic_id . '.0[/iurl]',
- );
+ ];
// Should be in the boardwide language.
- if (User::$me->language != Lang::$default)
- {
+ if (User::$me->language != Lang::$default) {
Lang::load('index', Lang::$default);
// Make sure we catch both languages in the reason.
- $reason_replacements += array(
+ $reason_replacements += [
Lang::$txt['movetopic_auto_board'] => '[url="' . Config::$scripturl . '?board=' . $_POST['toboard'] . '.0"]' . $board_name . '[/url]',
Lang::$txt['movetopic_auto_topic'] => '[iurl]' . Config::$scripturl . '?topic=' . Topic::$topic_id . '.0[/iurl]',
- );
+ ];
}
$_POST['reason'] = Utils::htmlspecialchars($_POST['reason'], ENT_QUOTES);
@@ -243,75 +232,74 @@ public function execute(): void
// redirect to the MOVED topic from topic list?
$redirect_topic = isset($_POST['redirect_topic']) ? Topic::$topic_id : 0;
- $msgOptions = array(
+ $msgOptions = [
'subject' => Lang::$txt['moved'] . ': ' . $subject,
'body' => $_POST['reason'],
'icon' => 'moved',
'smileys_enabled' => 1,
- );
+ ];
- $topicOptions = array(
+ $topicOptions = [
'board' => Board::$info->id,
'lock_mode' => 1,
'mark_as_read' => true,
'redirect_expires' => $redirect_expires,
'redirect_topic' => $redirect_topic,
- );
+ ];
- $posterOptions = array(
+ $posterOptions = [
'id' => User::$me->id,
'update_post_count' => empty($pcounter),
- );
+ ];
Msg::create($msgOptions, $topicOptions, $posterOptions);
}
- $request = Db::$db->query('', '
- SELECT count_posts
+ $request = Db::$db->query(
+ '',
+ 'SELECT count_posts
FROM {db_prefix}boards
WHERE id_board = {int:current_board}
LIMIT 1',
- array(
+ [
'current_board' => Board::$info->id,
- )
+ ],
);
list($pcounter_from) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- if ($pcounter_from != $pcounter)
- {
- $posters = array();
+ if ($pcounter_from != $pcounter) {
+ $posters = [];
- $request = Db::$db->query('', '
- SELECT id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}messages
WHERE id_topic = {int:current_topic}
AND approved = {int:is_approved}',
- array(
+ [
'current_topic' => Topic::$topic_id,
'is_approved' => 1,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (!isset($posters[$row['id_member']]))
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (!isset($posters[$row['id_member']])) {
$posters[$row['id_member']] = 0;
+ }
$posters[$row['id_member']]++;
}
Db::$db->free_result($request);
- foreach ($posters as $id_member => $posts)
- {
+ foreach ($posters as $id_member => $posts) {
// The board we're moving from counted posts, but not to.
- if (empty($pcounter_from))
- {
- User::updateMemberData($id_member, array('posts' => 'posts - ' . $posts));
+ if (empty($pcounter_from)) {
+ User::updateMemberData($id_member, ['posts' => 'posts - ' . $posts]);
}
// The reverse: from didn't, to did.
- else
- {
- User::updateMemberData($id_member, array('posts' => 'posts + ' . $posts));
+ else {
+ User::updateMemberData($id_member, ['posts' => 'posts + ' . $posts]);
}
}
}
@@ -320,9 +308,8 @@ public function execute(): void
Topic::move(Topic::$topic_id, $_POST['toboard']);
// Log that they moved this topic.
- if (!User::$me->allowedTo('move_own') || $id_member_started != User::$me->id)
- {
- Logging::logAction('move', array('topic' => Topic::$topic_id, 'board_from' => Board::$info->id, 'board_to' => $_POST['toboard']));
+ if (!User::$me->allowedTo('move_own') || $id_member_started != User::$me->id) {
+ Logging::logAction('move', ['topic' => Topic::$topic_id, 'board_from' => Board::$info->id, 'board_to' => $_POST['toboard']]);
}
// Notify people that this topic has been moved?
@@ -331,12 +318,9 @@ public function execute(): void
IntegrationHook::call('integrate_movetopic2_end');
// Why not go back to the original board in case they want to keep moving?
- if (!isset($_REQUEST['goback']))
- {
+ if (!isset($_REQUEST['goback'])) {
Utils::redirectexit('board=' . Board::$info->id . '.0');
- }
- else
- {
+ } else {
Utils::redirectexit('topic=' . Topic::$topic_id . '.0');
}
}
@@ -352,8 +336,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;
}
@@ -371,38 +356,38 @@ public static function call(): void
*/
public static function moveTopicConcurrence()
{
- if (isset($_GET['current_board']))
+ if (isset($_GET['current_board'])) {
$move_from = (int) $_GET['current_board'];
+ }
- if (empty($move_from) || empty(Board::$info->id) || empty(Topic::$topic_id))
+ if (empty($move_from) || empty(Board::$info->id) || empty(Topic::$topic_id)) {
return true;
+ }
- if ($move_from == Board::$info->id)
- {
+ if ($move_from == Board::$info->id) {
return true;
}
- else
- {
- $request = Db::$db->query('', '
- SELECT m.subject, b.name
+
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.subject, b.name
FROM {db_prefix}topics as t
LEFT JOIN {db_prefix}boards AS b ON (t.id_board = b.id_board)
LEFT JOIN {db_prefix}messages AS m ON (t.id_first_msg = m.id_msg)
WHERE t.id_topic = {int:topic_id}
LIMIT 1',
- array(
- 'topic_id' => Topic::$topic_id,
- )
- );
- list($topic_subject, $board_name) = Db::$db->fetch_row($request);
- Db::$db->free_result($request);
+ [
+ 'topic_id' => Topic::$topic_id,
+ ],
+ );
+ list($topic_subject, $board_name) = Db::$db->fetch_row($request);
+ Db::$db->free_result($request);
- $board_link = ' ' . $board_name . '';
+ $board_link = ' ' . $board_name . '';
- $topic_link = ' ' . $topic_subject . '';
+ $topic_link = ' ' . $topic_subject . '';
- ErrorHandler::fatalLang('topic_already_moved', false, array($topic_link, $board_link));
- }
+ ErrorHandler::fatalLang('topic_already_moved', false, [$topic_link, $board_link]);
}
/******************
@@ -418,7 +403,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TopicMove2::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TopicMove2::exportStatic')) {
TopicMove2::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/TopicPrint.php b/Sources/Actions/TopicPrint.php
index 8c6888fd5a..d6667acd13 100644
--- a/Sources/Actions/TopicPrint.php
+++ b/Sources/Actions/TopicPrint.php
@@ -13,12 +13,12 @@
namespace SMF\Actions;
-use SMF\BackwardCompatibility;
-
use SMF\Attachment;
+use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Poll;
@@ -27,7 +27,6 @@
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This class formats a topic to be printer friendly.
@@ -43,12 +42,11 @@ class TopicPrint implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'PrintTopic',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -77,11 +75,11 @@ class TopicPrint implements ActionInterface
public function execute(): void
{
// Redirect to the boardindex if no valid topic id is provided.
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
Utils::redirectexit();
+ }
- if (!empty(Config::$modSettings['disable_print_topic']))
- {
+ if (!empty(Config::$modSettings['disable_print_topic'])) {
unset($_REQUEST['action']);
Utils::$context['theme_loaded'] = false;
ErrorHandler::fatalLang('feature_disabled', false);
@@ -91,29 +89,31 @@ public function execute(): void
Utils::$context['robot_no_index'] = true;
// Get the topic starter information.
- $request = Db::$db->query('', '
- SELECT mem.id_member, m.poster_time, COALESCE(mem.real_name, m.poster_name) AS poster_name, t.id_poll
+ $request = Db::$db->query(
+ '',
+ 'SELECT mem.id_member, m.poster_time, COALESCE(mem.real_name, m.poster_name) AS poster_name, t.id_poll
FROM {db_prefix}messages AS m
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
LEFT JOIN {db_prefix}topics as t ON (t.id_first_msg = m.id_msg)
WHERE m.id_topic = {int:current_topic}
ORDER BY m.id_msg
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
- )
+ ],
);
+
// Redirect to the boardindex if no valid topic id is provided.
- if (Db::$db->num_rows($request) == 0)
+ if (Db::$db->num_rows($request) == 0) {
Utils::redirectexit();
+ }
$row = Db::$db->fetch_assoc($request);
Db::$db->free_result($request);
- if (!empty($row['id_poll']))
- {
+ if (!empty($row['id_poll'])) {
Lang::load('Post');
$poll = Poll::load(Topic::$topic_id, Poll::LOAD_BY_TOPIC);
- Utils::$context['poll'] = $poll->format(array('no_buttons' => true));
+ Utils::$context['poll'] = $poll->format(['no_buttons' => true]);
}
// We want a separate BBCodeParser instance for this, not the reusable one
@@ -125,100 +125,102 @@ public function execute(): void
// Lets "output" all that info.
Theme::loadTemplate('Printpage');
- Utils::$context['template_layers'] = array('print');
+ Utils::$context['template_layers'] = ['print'];
Utils::$context['board_name'] = Board::$info->name;
Utils::$context['category_name'] = Board::$info->cat['name'];
Utils::$context['poster_name'] = $row['poster_name'];
Utils::$context['post_time'] = Time::create('@' . $row['poster_time'])->format(null, false);
- Utils::$context['parent_boards'] = array();
- foreach (Board::$info->parent_boards as $parent)
+ Utils::$context['parent_boards'] = [];
+
+ foreach (Board::$info->parent_boards as $parent) {
Utils::$context['parent_boards'][] = $parent['name'];
+ }
// Split the topics up so we can print them.
- $request = Db::$db->query('', '
- SELECT subject, poster_time, body, COALESCE(mem.real_name, poster_name) AS poster_name, id_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT subject, poster_time, body, COALESCE(mem.real_name, poster_name) AS poster_name, id_msg
FROM {db_prefix}messages AS m
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
WHERE m.id_topic = {int:current_topic}' . (Config::$modSettings['postmod_active'] && !User::$me->allowedTo('approve_posts') ? '
AND (m.approved = {int:is_approved}' . (User::$me->is_guest ? '' : ' OR m.id_member = {int:current_member}') . ')' : '') . '
ORDER BY m.id_msg',
- array(
+ [
'current_topic' => Topic::$topic_id,
'is_approved' => 1,
'current_member' => User::$me->id,
- )
+ ],
);
- Utils::$context['posts'] = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ Utils::$context['posts'] = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Censor the subject and message.
Lang::censorText($row['subject']);
Lang::censorText($row['body']);
- Utils::$context['posts'][] = array(
+ Utils::$context['posts'][] = [
'subject' => $row['subject'],
'member' => $row['poster_name'],
'time' => Time::create('@' . $row['poster_time'])->format(null, false),
'timestamp' => $row['poster_time'],
'body' => $bbcparser->parse($row['body']),
'id_msg' => $row['id_msg'],
- );
+ ];
- if (!isset(Utils::$context['topic_subject']))
+ if (!isset(Utils::$context['topic_subject'])) {
Utils::$context['topic_subject'] = $row['subject'];
+ }
}
Db::$db->free_result($request);
// Fetch attachments so we can print them if asked, enabled and allowed
- if (isset($_REQUEST['images']) && !empty(Config::$modSettings['attachmentEnable']) && User::$me->allowedTo('view_attachments'))
- {
- $messages = array();
- foreach (Utils::$context['posts'] as $temp)
+ if (isset($_REQUEST['images']) && !empty(Config::$modSettings['attachmentEnable']) && User::$me->allowedTo('view_attachments')) {
+ $messages = [];
+
+ foreach (Utils::$context['posts'] as $temp) {
$messages[] = $temp['id_msg'];
+ }
// build the request
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
a.id_attach, a.id_msg, a.approved, a.width, a.height, a.file_hash, a.filename, a.id_folder, a.mime_type
FROM {db_prefix}attachments AS a
WHERE a.id_msg IN ({array_int:message_list})
AND a.attachment_type = {int:attachment_type}',
- array(
+ [
'message_list' => $messages,
'attachment_type' => 0,
'is_approved' => 1,
- )
+ ],
);
- $temp = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $temp = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$temp[$row['id_attach']] = $row;
- if (!isset(Utils::$context['printattach'][$row['id_msg']]))
- Utils::$context['printattach'][$row['id_msg']] = array();
+
+ if (!isset(Utils::$context['printattach'][$row['id_msg']])) {
+ Utils::$context['printattach'][$row['id_msg']] = [];
+ }
}
Db::$db->free_result($request);
ksort($temp);
// load them into Utils::$context so the template can use them
- foreach ($temp as $row)
- {
- if (!empty(Config::$modSettings['dont_show_attach_under_post']) && !empty(Utils::$context['show_attach_under_post'][$row['id_attach']]))
+ foreach ($temp as $row) {
+ if (!empty(Config::$modSettings['dont_show_attach_under_post']) && !empty(Utils::$context['show_attach_under_post'][$row['id_attach']])) {
continue;
+ }
- if (!empty($row['width']) && !empty($row['height']))
- {
- if (!empty(Config::$modSettings['max_image_width']) && (empty(Config::$modSettings['max_image_height']) || $row['height'] * (Config::$modSettings['max_image_width'] / $row['width']) <= Config::$modSettings['max_image_height']))
- {
- if ($row['width'] > Config::$modSettings['max_image_width'])
- {
+ if (!empty($row['width']) && !empty($row['height'])) {
+ if (!empty(Config::$modSettings['max_image_width']) && (empty(Config::$modSettings['max_image_height']) || $row['height'] * (Config::$modSettings['max_image_width'] / $row['width']) <= Config::$modSettings['max_image_height'])) {
+ if ($row['width'] > Config::$modSettings['max_image_width']) {
$row['height'] = floor($row['height'] * (Config::$modSettings['max_image_width'] / $row['width']));
$row['width'] = Config::$modSettings['max_image_width'];
}
- }
- elseif (!empty(Config::$modSettings['max_image_width']))
- {
- if ($row['height'] > Config::$modSettings['max_image_height'])
- {
+ } elseif (!empty(Config::$modSettings['max_image_width'])) {
+ if ($row['height'] > Config::$modSettings['max_image_height']) {
$row['width'] = floor($row['width'] * Config::$modSettings['max_image_height'] / $row['height']);
$row['height'] = Config::$modSettings['max_image_height'];
}
@@ -247,8 +249,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;
}
@@ -274,7 +277,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TopicPrint::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TopicPrint::exportStatic')) {
TopicPrint::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/TopicRemove.php b/Sources/Actions/TopicRemove.php
index 6d1d224dd7..baf4ec45cb 100644
--- a/Sources/Actions/TopicRemove.php
+++ b/Sources/Actions/TopicRemove.php
@@ -14,16 +14,15 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Logging;
use SMF\Mail;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This action handles the deletion of topics.
@@ -37,13 +36,13 @@ class TopicRemove implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'RemoveTopic2',
+ 'removeDeleteConcurrence' => 'removeDeleteConcurrence',
'old' => 'RemoveOldTopics2',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -71,38 +70,42 @@ public function execute(): void
User::$me->checkSession('get');
// Trying to fool us around, are we?
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
Utils::redirectexit();
+ }
self::removeDeleteConcurrence();
- $request = Db::$db->query('', '
- SELECT t.id_member_started, ms.subject, t.approved, t.locked
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_member_started, ms.subject, t.approved, t.locked
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
WHERE t.id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
- )
+ ],
);
- list ($starter, $subject, $approved, $locked) = Db::$db->fetch_row($request);
+ list($starter, $subject, $approved, $locked) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- if ($starter == User::$me->id && !User::$me->allowedTo('remove_any'))
+ if ($starter == User::$me->id && !User::$me->allowedTo('remove_any')) {
User::$me->isAllowedTo('remove_own');
- else
+ } else {
User::$me->isAllowedTo('remove_any');
+ }
// Can they see the topic?
- if (Config::$modSettings['postmod_active'] && !$approved && $starter != User::$me->id)
+ if (Config::$modSettings['postmod_active'] && !$approved && $starter != User::$me->id) {
User::$me->isAllowedTo('approve_posts');
+ }
// Ok, we got that far, but is it locked?
- if ($locked)
- {
- if (!($locked == 1 && $starter == User::$me->id || User::$me->allowedTo('lock_any')))
+ if ($locked) {
+ if (!($locked == 1 && $starter == User::$me->id || User::$me->allowedTo('lock_any'))) {
ErrorHandler::fatalLang('cannot_remove_locked', 'user');
+ }
}
// Notify people that this topic has been removed.
@@ -111,14 +114,13 @@ public function execute(): void
Topic::remove(Topic::$topic_id);
// Note, only log topic ID in native form if it's not gone forever.
- if (User::$me->allowedTo('remove_any') || (User::$me->allowedTo('remove_own') && $starter == User::$me->id))
- {
- Logging::logAction('remove', array(
+ if (User::$me->allowedTo('remove_any') || (User::$me->allowedTo('remove_own') && $starter == User::$me->id)) {
+ Logging::logAction('remove', [
(empty(Config::$modSettings['recycle_enable']) || Config::$modSettings['recycle_board'] != Board::$info->id ? 'topic' : 'old_topic_id') => Topic::$topic_id,
'subject' => $subject,
'member' => $starter,
- 'board' => Board::$info->id
- ));
+ 'board' => Board::$info->id,
+ ]);
}
Utils::redirectexit('board=' . Board::$info->id . '.0');
@@ -135,8 +137,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;
}
@@ -157,30 +160,30 @@ public static function call(): void
public static function removeDeleteConcurrence()
{
// No recycle no need to go further
- if (empty(Config::$modSettings['recycle_enable']) || empty(Config::$modSettings['recycle_board']))
+ if (empty(Config::$modSettings['recycle_enable']) || empty(Config::$modSettings['recycle_board'])) {
return false;
+ }
// If it's confirmed go on and delete (from recycle)
- if (isset($_GET['confirm_delete']))
+ if (isset($_GET['confirm_delete'])) {
return true;
+ }
- if (empty(Board::$info->id))
+ if (empty(Board::$info->id)) {
return false;
+ }
- if (Config::$modSettings['recycle_board'] != Board::$info->id)
- {
+ if (Config::$modSettings['recycle_board'] != Board::$info->id) {
return true;
}
- elseif (isset($_REQUEST['msg']))
- {
+
+ if (isset($_REQUEST['msg'])) {
$confirm_url = Config::$scripturl . '?action=deletemsg;confirm_delete;topic=' . Utils::$context['current_topic'] . '.0;msg=' . $_REQUEST['msg'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
- }
- else
- {
+ } else {
$confirm_url = Config::$scripturl . '?action=removetopic2;confirm_delete;topic=' . Utils::$context['current_topic'] . '.0;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
}
- ErrorHandler::fatalLang('post_already_deleted', false, array($confirm_url));
+ ErrorHandler::fatalLang('post_already_deleted', false, [$confirm_url]);
}
/**
@@ -194,23 +197,23 @@ public static function old()
User::$me->checkSession('post', 'admin');
// No boards at all? Forget it then :/.
- if (empty($_POST['boards']))
+ if (empty($_POST['boards'])) {
Utils::redirectexit('action=admin;area=maintain;sa=topics');
+ }
// This should exist, but we can make sure.
- $_POST['delete_type'] = isset($_POST['delete_type']) ? $_POST['delete_type'] : 'nothing';
+ $_POST['delete_type'] = $_POST['delete_type'] ?? 'nothing';
// Custom conditions.
$condition = '';
- $condition_params = array(
+ $condition_params = [
'boards' => array_keys($_POST['boards']),
'poster_time' => time() - 3600 * 24 * $_POST['maxdays'],
- );
+ ];
// Just moved notice topics?
// Note that this ignores redirection topics unless it's a non-expiring one
- if ($_POST['delete_type'] == 'moved')
- {
+ if ($_POST['delete_type'] == 'moved') {
$condition .= '
AND m.icon = {string:icon}
AND t.locked = {int:locked}
@@ -220,8 +223,7 @@ public static function old()
$condition_params['not_expiring'] = 0;
}
// Otherwise, maybe locked topics only?
- elseif ($_POST['delete_type'] == 'locked')
- {
+ elseif ($_POST['delete_type'] == 'locked') {
// Exclude moved/merged notices since we have another option for those...
$condition .= '
AND t.icon != {string:icon}
@@ -231,32 +233,34 @@ public static function old()
}
// Exclude stickies?
- if (isset($_POST['delete_old_not_sticky']))
- {
+ if (isset($_POST['delete_old_not_sticky'])) {
$condition .= '
AND t.is_sticky = {int:is_sticky}';
$condition_params['is_sticky'] = 0;
}
// All we're gonna do here is grab the id_topic's and send them to Topic::remove().
- $request = Db::$db->query('', '
- SELECT t.id_topic
+ $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)
WHERE
m.poster_time < {int:poster_time}' . $condition . '
AND t.id_board IN ({array_int:boards})',
- $condition_params
+ $condition_params,
);
- $topics = array();
- while ($row = Db::$db->fetch_assoc($request))
+ $topics = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$topics[] = $row['id_topic'];
+ }
Db::$db->free_result($request);
Topic::remove($topics, false, true);
// Log an action into the moderation log.
- Logging::logAction('pruned', array('days' => $_POST['maxdays']));
+ Logging::logAction('pruned', ['days' => $_POST['maxdays']]);
Utils::redirectexit('action=admin;area=maintain;sa=topics;done=purgeold');
}
@@ -275,11 +279,11 @@ protected function __construct()
/*************************
* Internal static methods
*************************/
-
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TopicRemove::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TopicRemove::exportStatic')) {
TopicRemove::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/TopicRestore.php b/Sources/Actions/TopicRestore.php
index 3a32ef8653..c4941a394c 100644
--- a/Sources/Actions/TopicRestore.php
+++ b/Sources/Actions/TopicRestore.php
@@ -14,14 +14,14 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
+use SMF\ErrorHandler;
use SMF\Logging;
use SMF\Msg;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* This action handles restoring a topic from the recycle board back to its
@@ -36,12 +36,11 @@ class TopicRestore implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'RestoreTopic',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -68,151 +67,162 @@ public function execute(): void
User::$me->checkSession('get');
// Is recycled board enabled?
- if (empty(Config::$modSettings['recycle_enable']))
+ if (empty(Config::$modSettings['recycle_enable'])) {
ErrorHandler::fatalLang('restored_disabled', 'critical');
+ }
// Can we be in here?
User::$me->isAllowedTo('move_any', Config::$modSettings['recycle_board']);
- $unfound_messages = array();
- $topics_to_restore = array();
+ $unfound_messages = [];
+ $topics_to_restore = [];
// Restoring messages?
- if (!empty($_REQUEST['msgs']))
- {
+ if (!empty($_REQUEST['msgs'])) {
$msgs = explode(',', $_REQUEST['msgs']);
- foreach ($msgs as $k => $msg)
+
+ foreach ($msgs as $k => $msg) {
$msgs[$k] = (int) $msg;
+ }
// Get the id_previous_board and id_previous_topic.
- $request = Db::$db->query('', '
- SELECT m.id_topic, m.id_msg, m.id_board, m.subject, m.id_member, t.id_previous_board, t.id_previous_topic,
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_topic, m.id_msg, m.id_board, m.subject, m.id_member, t.id_previous_board, t.id_previous_topic,
t.id_first_msg, b.count_posts, COALESCE(pt.id_board, 0) AS possible_prev_board
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
LEFT JOIN {db_prefix}topics AS pt ON (pt.id_topic = t.id_previous_topic)
WHERE m.id_msg IN ({array_int:messages})',
- array(
+ [
'messages' => $msgs,
- )
+ ],
);
- $actioned_messages = array();
- $previous_topics = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $actioned_messages = [];
+ $previous_topics = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Restoring the first post means topic.
- if ($row['id_msg'] == $row['id_first_msg'] && $row['id_previous_topic'] == $row['id_topic'])
- {
+ if ($row['id_msg'] == $row['id_first_msg'] && $row['id_previous_topic'] == $row['id_topic']) {
$topics_to_restore[] = $row['id_topic'];
+
continue;
}
+
// Don't know where it's going?
- if (empty($row['id_previous_topic']))
- {
+ if (empty($row['id_previous_topic'])) {
$unfound_messages[$row['id_msg']] = $row['subject'];
+
continue;
}
$previous_topics[] = $row['id_previous_topic'];
- if (empty($actioned_messages[$row['id_previous_topic']]))
- $actioned_messages[$row['id_previous_topic']] = array(
- 'msgs' => array(),
+
+ if (empty($actioned_messages[$row['id_previous_topic']])) {
+ $actioned_messages[$row['id_previous_topic']] = [
+ 'msgs' => [],
'count_posts' => $row['count_posts'],
'subject' => $row['subject'],
'previous_board' => $row['id_previous_board'],
'possible_prev_board' => $row['possible_prev_board'],
'current_topic' => $row['id_topic'],
'current_board' => $row['id_board'],
- 'members' => array(),
- );
+ 'members' => [],
+ ];
+ }
$actioned_messages[$row['id_previous_topic']]['msgs'][$row['id_msg']] = $row['subject'];
- if ($row['id_member'])
+
+ if ($row['id_member']) {
$actioned_messages[$row['id_previous_topic']]['members'][] = $row['id_member'];
+ }
}
Db::$db->free_result($request);
// Check for topics we are going to fully restore.
- foreach ($actioned_messages as $topic => $data)
- if (in_array($topic, $topics_to_restore))
+ foreach ($actioned_messages as $topic => $data) {
+ if (in_array($topic, $topics_to_restore)) {
unset($actioned_messages[$topic]);
+ }
+ }
// Load any previous topics to check they exist.
- if (!empty($previous_topics))
- {
- $request = Db::$db->query('', '
- SELECT t.id_topic, t.id_board, m.subject
+ if (!empty($previous_topics)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_topic, t.id_board, m.subject
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
WHERE t.id_topic IN ({array_int:previous_topics})',
- array(
+ [
'previous_topics' => $previous_topics,
- )
+ ],
);
- $previous_topics = array();
- while ($row = Db::$db->fetch_assoc($request))
- $previous_topics[$row['id_topic']] = array(
+ $previous_topics = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $previous_topics[$row['id_topic']] = [
'board' => $row['id_board'],
'subject' => $row['subject'],
- );
+ ];
+ }
Db::$db->free_result($request);
}
// Restore each topic.
- $messages = array();
- foreach ($actioned_messages as $topic => $data)
- {
+ $messages = [];
+
+ foreach ($actioned_messages as $topic => $data) {
// If we have topics we are going to restore the whole lot ignore them.
- if (in_array($topic, $topics_to_restore))
- {
+ if (in_array($topic, $topics_to_restore)) {
unset($actioned_messages[$topic]);
+
continue;
}
// Move the posts back then!
- if (isset($previous_topics[$topic]))
- {
+ if (isset($previous_topics[$topic])) {
self::mergePosts(array_keys($data['msgs']), $data['current_topic'], $topic);
// Log em.
- Logging::logAction('restore_posts', array('topic' => $topic, 'subject' => $previous_topics[$topic]['subject'], 'board' => empty($data['previous_board']) ? $data['possible_prev_board'] : $data['previous_board']));
+ Logging::logAction('restore_posts', ['topic' => $topic, 'subject' => $previous_topics[$topic]['subject'], 'board' => empty($data['previous_board']) ? $data['possible_prev_board'] : $data['previous_board']]);
$messages = array_merge(array_keys($data['msgs']), $messages);
- }
- else
- {
- foreach ($data['msgs'] as $msg)
+ } else {
+ foreach ($data['msgs'] as $msg) {
$unfound_messages[$msg['id']] = $msg['subject'];
+ }
}
}
}
// Now any topics?
- if (!empty($_REQUEST['topics']))
- {
+ if (!empty($_REQUEST['topics'])) {
$topics = explode(',', $_REQUEST['topics']);
- foreach ($topics as $id)
+
+ foreach ($topics as $id) {
$topics_to_restore[] = (int) $id;
+ }
}
- if (!empty($topics_to_restore))
- {
+ if (!empty($topics_to_restore)) {
// Lets get the data for these topics.
- $request = Db::$db->query('', '
- SELECT t.id_topic, t.id_previous_board, t.id_board, t.id_first_msg, m.subject
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_topic, t.id_previous_board, t.id_board, t.id_first_msg, m.subject
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
WHERE t.id_topic IN ({array_int:topics})',
- array(
+ [
'topics' => $topics_to_restore,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// We can only restore if the previous board is set.
- if (empty($row['id_previous_board']))
- {
+ if (empty($row['id_previous_board'])) {
$unfound_messages[$row['id_first_msg']] = $row['subject'];
+
continue;
}
@@ -220,47 +230,48 @@ public function execute(): void
Topic::move($row['id_topic'], $row['id_previous_board']);
// Lets see if the board that we are returning to has post count enabled.
- $request2 = Db::$db->query('', '
- SELECT count_posts
+ $request2 = Db::$db->query(
+ '',
+ 'SELECT count_posts
FROM {db_prefix}boards
WHERE id_board = {int:board}',
- array(
+ [
'board' => $row['id_previous_board'],
- )
+ ],
);
- list ($count_posts) = Db::$db->fetch_row($request2);
+ list($count_posts) = Db::$db->fetch_row($request2);
Db::$db->free_result($request2);
- if (empty($count_posts))
- {
+ if (empty($count_posts)) {
// Lets get the members that need their post count restored.
- $request2 = Db::$db->query('', '
- SELECT id_member, COUNT(*) AS post_count
+ $request2 = Db::$db->query(
+ '',
+ 'SELECT id_member, COUNT(*) AS post_count
FROM {db_prefix}messages
WHERE id_topic = {int:topic}
AND approved = {int:is_approved}
GROUP BY id_member',
- array(
+ [
'topic' => $row['id_topic'],
'is_approved' => 1,
- )
+ ],
);
- while ($member = Db::$db->fetch_assoc($request2))
- User::updateMemberData($member['id_member'], array('posts' => 'posts + ' . $member['post_count']));
+ while ($member = Db::$db->fetch_assoc($request2)) {
+ User::updateMemberData($member['id_member'], ['posts' => 'posts + ' . $member['post_count']]);
+ }
Db::$db->free_result($request2);
}
// Log it.
- Logging::logAction('restore_topic', array('topic' => $row['id_topic'], 'board' => $row['id_board'], 'board_to' => $row['id_previous_board']));
+ Logging::logAction('restore_topic', ['topic' => $row['id_topic'], 'board' => $row['id_board'], 'board_to' => $row['id_previous_board']]);
}
Db::$db->free_result($request);
}
// Didn't find some things?
- if (!empty($unfound_messages))
- {
- ErrorHandler::fatalLang('restore_not_found', false, array(implode(' ', $unfound_messages)));
+ if (!empty($unfound_messages)) {
+ ErrorHandler::fatalLang('restore_not_found', false, [implode(' ', $unfound_messages)]);
}
// Just send them to the index if they get here.
@@ -278,8 +289,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;
}
@@ -311,223 +323,241 @@ protected function __construct()
* Take a load of messages from one place and stick them in a topic
*
* @param array $msgs The IDs of the posts to merge
- * @param integer $from_topic The ID of the topic the messages were originally in
- * @param integer $target_topic The ID of the topic the messages are being merged into
+ * @param int $from_topic The ID of the topic the messages were originally in
+ * @param int $target_topic The ID of the topic the messages are being merged into
*/
protected static function mergePosts($msgs, $from_topic, $target_topic)
{
- //!!! This really needs to be rewritten to take a load of messages from ANY topic, it's also inefficient.
+ // !!! This really needs to be rewritten to take a load of messages from ANY topic, it's also inefficient.
// Is it an array?
- if (!is_array($msgs))
- $msgs = array($msgs);
+ if (!is_array($msgs)) {
+ $msgs = [$msgs];
+ }
// Lets make sure they are int.
- foreach ($msgs as $key => $msg)
+ foreach ($msgs as $key => $msg) {
$msgs[$key] = (int) $msg;
+ }
// Get the source information.
- $request = Db::$db->query('', '
- SELECT t.id_board, t.id_first_msg, t.num_replies, t.unapproved_posts
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_board, t.id_first_msg, t.num_replies, t.unapproved_posts
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
WHERE t.id_topic = {int:from_topic}',
- array(
+ [
'from_topic' => $from_topic,
- )
+ ],
);
- list ($from_board, $from_first_msg, $from_replies, $from_unapproved_posts) = Db::$db->fetch_row($request);
+ list($from_board, $from_first_msg, $from_replies, $from_unapproved_posts) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Get some target topic and board stats.
- $request = Db::$db->query('', '
- SELECT t.id_board, t.id_first_msg, t.num_replies, t.unapproved_posts, b.count_posts
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_board, t.id_first_msg, t.num_replies, t.unapproved_posts, b.count_posts
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
WHERE t.id_topic = {int:target_topic}',
- array(
+ [
'target_topic' => $target_topic,
- )
+ ],
);
- list ($target_board, $target_first_msg, $target_replies, $target_unapproved_posts, $count_posts) = Db::$db->fetch_row($request);
+ list($target_board, $target_first_msg, $target_replies, $target_unapproved_posts, $count_posts) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Lets see if the board that we are returning to has post count enabled.
- if (empty($count_posts))
- {
+ if (empty($count_posts)) {
// Lets get the members that need their post count restored.
- $request = Db::$db->query('', '
- SELECT id_member
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member
FROM {db_prefix}messages
WHERE id_msg IN ({array_int:messages})
AND approved = {int:is_approved}',
- array(
+ [
'messages' => $msgs,
'is_approved' => 1,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- User::updateMemberData($row['id_member'], array('posts' => '+'));
+ while ($row = Db::$db->fetch_assoc($request)) {
+ User::updateMemberData($row['id_member'], ['posts' => '+']);
+ }
}
// Time to move the messages.
- Db::$db->query('', '
- UPDATE {db_prefix}messages
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}messages
SET
id_topic = {int:target_topic},
id_board = {int:target_board}
WHERE id_msg IN({array_int:msgs})',
- array(
+ [
'target_topic' => $target_topic,
'target_board' => $target_board,
'msgs' => $msgs,
- )
+ ],
);
// Fix the id_first_msg and id_last_msg for the target topic.
- $target_topic_data = array(
+ $target_topic_data = [
'num_replies' => 0,
'unapproved_posts' => 0,
'id_first_msg' => 9999999999,
- );
- $request = Db::$db->query('', '
- SELECT MIN(id_msg) AS id_first_msg, MAX(id_msg) AS id_last_msg, COUNT(*) AS message_count, approved
+ ];
+ $request = Db::$db->query(
+ '',
+ 'SELECT MIN(id_msg) AS id_first_msg, MAX(id_msg) AS id_last_msg, COUNT(*) AS message_count, approved
FROM {db_prefix}messages
WHERE id_topic = {int:target_topic}
GROUP BY id_topic, approved
ORDER BY approved ASC
LIMIT 2',
- array(
+ [
'target_topic' => $target_topic,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if ($row['id_first_msg'] < $target_topic_data['id_first_msg'])
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if ($row['id_first_msg'] < $target_topic_data['id_first_msg']) {
$target_topic_data['id_first_msg'] = $row['id_first_msg'];
+ }
$target_topic_data['id_last_msg'] = $row['id_last_msg'];
- if (!$row['approved'])
+
+ if (!$row['approved']) {
$target_topic_data['unapproved_posts'] = $row['message_count'];
- else
+ } else {
$target_topic_data['num_replies'] = max(0, $row['message_count'] - 1);
+ }
}
Db::$db->free_result($request);
// We have a new post count for the board.
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET
num_posts = num_posts + {int:diff_replies},
unapproved_posts = unapproved_posts + {int:diff_unapproved_posts}
WHERE id_board = {int:target_board}',
- array(
+ [
'diff_replies' => $target_topic_data['num_replies'] - $target_replies, // Lets keep in mind that the first message in a topic counts towards num_replies in a board.
'diff_unapproved_posts' => $target_topic_data['unapproved_posts'] - $target_unapproved_posts,
'target_board' => $target_board,
- )
+ ],
);
// In some cases we merged the only post in a topic so the topic data is left behind in the topic table.
- $request = Db::$db->query('', '
- SELECT id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic
FROM {db_prefix}messages
WHERE id_topic = {int:from_topic}',
- array(
+ [
'from_topic' => $from_topic,
- )
+ ],
);
// Remove the topic if it doesn't have any messages.
$topic_exists = true;
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
Topic::remove($from_topic, false, true);
$topic_exists = false;
}
Db::$db->free_result($request);
// Recycled topic.
- if ($topic_exists == true)
- {
+ if ($topic_exists == true) {
// Fix the id_first_msg and id_last_msg for the source topic.
- $source_topic_data = array(
+ $source_topic_data = [
'num_replies' => 0,
'unapproved_posts' => 0,
'id_first_msg' => 9999999999,
- );
- $request = Db::$db->query('', '
- SELECT MIN(id_msg) AS id_first_msg, MAX(id_msg) AS id_last_msg, COUNT(*) AS message_count, approved, subject
+ ];
+ $request = Db::$db->query(
+ '',
+ 'SELECT MIN(id_msg) AS id_first_msg, MAX(id_msg) AS id_last_msg, COUNT(*) AS message_count, approved, subject
FROM {db_prefix}messages
WHERE id_topic = {int:from_topic}
GROUP BY id_topic, approved, subject
ORDER BY approved ASC
LIMIT 2',
- array(
+ [
'from_topic' => $from_topic,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if ($row['id_first_msg'] < $source_topic_data['id_first_msg'])
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if ($row['id_first_msg'] < $source_topic_data['id_first_msg']) {
$source_topic_data['id_first_msg'] = $row['id_first_msg'];
+ }
$source_topic_data['id_last_msg'] = $row['id_last_msg'];
- if (!$row['approved'])
+
+ if (!$row['approved']) {
$source_topic_data['unapproved_posts'] = $row['message_count'];
- else
+ } else {
$source_topic_data['num_replies'] = max(0, $row['message_count'] - 1);
+ }
}
Db::$db->free_result($request);
// Update the topic details for the source topic.
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET
id_first_msg = {int:id_first_msg},
id_last_msg = {int:id_last_msg},
num_replies = {int:num_replies},
unapproved_posts = {int:unapproved_posts}
WHERE id_topic = {int:from_topic}',
- array(
+ [
'id_first_msg' => $source_topic_data['id_first_msg'],
'id_last_msg' => $source_topic_data['id_last_msg'],
'num_replies' => $source_topic_data['num_replies'],
'unapproved_posts' => $source_topic_data['unapproved_posts'],
'from_topic' => $from_topic,
- )
+ ],
);
// We have a new post count for the source board.
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET
num_posts = num_posts + {int:diff_replies},
unapproved_posts = unapproved_posts + {int:diff_unapproved_posts}
WHERE id_board = {int:from_board}',
- array(
+ [
'diff_replies' => $source_topic_data['num_replies'] - $from_replies, // Lets keep in mind that the first message in a topic counts towards num_replies in a board.
'diff_unapproved_posts' => $source_topic_data['unapproved_posts'] - $from_unapproved_posts,
'from_board' => $from_board,
- )
+ ],
);
}
// Finally get around to updating the destination topic, now all indexes etc on the source are fixed.
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET
id_first_msg = {int:id_first_msg},
id_last_msg = {int:id_last_msg},
num_replies = {int:num_replies},
unapproved_posts = {int:unapproved_posts}
WHERE id_topic = {int:target_topic}',
- array(
+ [
'id_first_msg' => $target_topic_data['id_first_msg'],
'id_last_msg' => $target_topic_data['id_last_msg'],
'num_replies' => $target_topic_data['num_replies'],
'unapproved_posts' => $target_topic_data['unapproved_posts'],
'target_topic' => $target_topic,
- )
+ ],
);
// Update stats.
@@ -535,34 +565,40 @@ protected static function mergePosts($msgs, $from_topic, $target_topic)
Logging::updateStats('message');
// Subject cache?
- $cache_updates = array();
- if ($target_first_msg != $target_topic_data['id_first_msg'])
+ $cache_updates = [];
+
+ if ($target_first_msg != $target_topic_data['id_first_msg']) {
$cache_updates[] = $target_topic_data['id_first_msg'];
- if (!empty($source_topic_data['id_first_msg']) && $from_first_msg != $source_topic_data['id_first_msg'])
+ }
+
+ if (!empty($source_topic_data['id_first_msg']) && $from_first_msg != $source_topic_data['id_first_msg']) {
$cache_updates[] = $source_topic_data['id_first_msg'];
+ }
- if (!empty($cache_updates))
- {
- $request = Db::$db->query('', '
- SELECT id_topic, subject
+ if (!empty($cache_updates)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic, subject
FROM {db_prefix}messages
WHERE id_msg IN ({array_int:first_messages})',
- array(
+ [
'first_messages' => $cache_updates,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Logging::updateStats('subject', $row['id_topic'], $row['subject']);
+ }
Db::$db->free_result($request);
}
- Msg::updateLastMessages(array($from_board, $target_board));
+ Msg::updateLastMessages([$from_board, $target_board]);
}
-
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TopicRestore::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TopicRestore::exportStatic')) {
TopicRestore::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/TopicSplit.php b/Sources/Actions/TopicSplit.php
index 34b95f7bce..1d44cf6c9c 100644
--- a/Sources/Actions/TopicSplit.php
+++ b/Sources/Actions/TopicSplit.php
@@ -16,26 +16,23 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\BBCodeParser;
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Logging;
-use SMF\MessageIndex;
-use SMF\Msg;
use SMF\Mail;
+use SMF\Msg;
use SMF\PageIndex;
+use SMF\Search\SearchApi;
use SMF\Theme;
use SMF\Time;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
-use SMF\Search\SearchApi;
/**
* Handles splitting of topics.
@@ -49,12 +46,16 @@ class TopicSplit implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'SplitTopics',
- ),
- );
+ 'splitTopic' => 'splitTopic',
+ 'splitIndex' => 'SplitIndex',
+ 'splitExecute' => 'SplitExecute',
+ 'splitSelectTopics' => 'SplitSelectTopics',
+ 'SplitSelectionExecute' => 'SplitSelectionExecute',
+ ],
+ ];
/*****************
* Class constants
@@ -83,12 +84,12 @@ class TopicSplit implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'index' => 'index',
'split' => 'split',
'selectTopics' => 'select',
'splitSelection' => 'splitSelection',
- );
+ ];
/*********************
* Internal properties
@@ -123,20 +124,23 @@ class TopicSplit implements ActionInterface
public function execute(): void
{
// And... which topic were you splitting, again?
- if (empty(Topic::$topic_id))
+ if (empty(Topic::$topic_id)) {
ErrorHandler::fatalLang('numbers_one_to_nine', false);
+ }
// Are you allowed to split topics?
User::$me->isAllowedTo('split_any');
// Load up the "dependencies" - the template and getMsgMemberID().
- if (!isset($_REQUEST['xml']))
+ if (!isset($_REQUEST['xml'])) {
Theme::loadTemplate('SplitTopics');
+ }
- $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);
+ }
}
/**
@@ -152,53 +156,59 @@ public function execute(): void
public function index()
{
// Validate "at".
- if (empty($_GET['at']))
+ if (empty($_GET['at'])) {
ErrorHandler::fatalLang('numbers_one_to_nine', false);
+ }
$_GET['at'] = (int) $_GET['at'];
// Retrieve the subject and stuff of the specific topic/message.
- $request = Db::$db->query('', '
- SELECT m.subject, t.num_replies, t.unapproved_posts, t.id_first_msg, t.approved
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.subject, t.num_replies, t.unapproved_posts, t.id_first_msg, t.approved
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})
WHERE m.id_msg = {int:split_at}' . (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
AND m.approved = 1') . '
AND m.id_topic = {int:current_topic}
LIMIT 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
'split_at' => $_GET['at'],
- )
+ ],
);
- if (Db::$db->num_rows($request) == 0)
- {
+
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('cant_find_messages');
}
list($_REQUEST['subname'], $num_replies, $unapproved_posts, $id_first_msg, $approved) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// If not approved validate they can see it.
- if (Config::$modSettings['postmod_active'] && !$approved)
+ if (Config::$modSettings['postmod_active'] && !$approved) {
User::$me->isAllowedTo('approve_posts');
+ }
// If this topic has unapproved posts, we need to count them too...
- if (Config::$modSettings['postmod_active'] && User::$me->allowedTo('approve_posts'))
+ if (Config::$modSettings['postmod_active'] && User::$me->allowedTo('approve_posts')) {
$num_replies += $unapproved_posts - ($approved ? 0 : 1);
+ }
// Check if there is more than one message in the topic. (there should be.)
- if ($num_replies < 1)
+ if ($num_replies < 1) {
ErrorHandler::fatalLang('topic_one_post', false);
+ }
// Check if this is the first message in the topic (if so, the first and second option won't be available)
- if ($id_first_msg == $_GET['at'])
- return select();
+ if ($id_first_msg == $_GET['at']) {
+ return $this->select();
+ }
// Basic template information....
- Utils::$context['message'] = array(
+ Utils::$context['message'] = [
'id' => $_GET['at'],
- 'subject' => $_REQUEST['subname']
- );
+ 'subject' => $_REQUEST['subname'],
+ ];
Utils::$context['sub_template'] = 'ask';
Utils::$context['page_title'] = Lang::$txt['split'];
}
@@ -220,50 +230,48 @@ public function split()
User::$me->checkSession();
// Clean up the subject.
- if (!isset($_POST['subname']) || $_POST['subname'] == '')
+ if (!isset($_POST['subname']) || $_POST['subname'] == '') {
$_POST['subname'] = Lang::$txt['new_topic'];
+ }
// Redirect to the selector if they chose selective.
- if ($_POST['step2'] == 'selective')
- {
- Utils::redirectexit ('action=splittopics;sa=selectTopics;subname=' . $_POST['subname'] . ';topic=' . Topic::$topic_id . '.0;start2=0');
+ if ($_POST['step2'] == 'selective') {
+ Utils::redirectexit('action=splittopics;sa=selectTopics;subname=' . $_POST['subname'] . ';topic=' . Topic::$topic_id . '.0;start2=0');
}
$_POST['at'] = (int) $_POST['at'];
- $messagesToBeSplit = array();
+ $messagesToBeSplit = [];
- if ($_POST['step2'] == 'afterthis')
- {
+ if ($_POST['step2'] == 'afterthis') {
// Fetch the message IDs of the topic that are at or after the message.
- $request = Db::$db->query('', '
- SELECT id_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_msg
FROM {db_prefix}messages
WHERE id_topic = {int:current_topic}
AND id_msg >= {int:split_at}',
- array(
+ [
'current_topic' => Topic::$topic_id,
'split_at' => $_POST['at'],
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$messagesToBeSplit[] = $row['id_msg'];
}
Db::$db->free_result($request);
}
// Only the selected message has to be split. That should be easy.
- elseif ($_POST['step2'] == 'onlythis')
- {
+ elseif ($_POST['step2'] == 'onlythis') {
$messagesToBeSplit[] = $_POST['at'];
}
// There's another action?!
- else
- {
+ else {
ErrorHandler::fatalLang('no_access', false);
}
Utils::$context['old_topic'] = Topic::$topic_id;
- Utils::$context['new_topic'] = splitTopic(Topic::$topic_id, $messagesToBeSplit, $_POST['subname']);
+ Utils::$context['new_topic'] = $this->splitTopic(Topic::$topic_id, $messagesToBeSplit, $_POST['subname']);
Utils::$context['page_title'] = Lang::$txt['split'];
}
@@ -283,28 +291,29 @@ public function select()
Utils::$context['page_title'] = Lang::$txt['split'] . ' - ' . Lang::$txt['select_split_posts'];
// Haven't selected anything have we?
- $_SESSION['split_selection'][Topic::$topic_id] = empty($_SESSION['split_selection'][Topic::$topic_id]) ? array() : $_SESSION['split_selection'][Topic::$topic_id];
+ $_SESSION['split_selection'][Topic::$topic_id] = empty($_SESSION['split_selection'][Topic::$topic_id]) ? [] : $_SESSION['split_selection'][Topic::$topic_id];
// This is a special case for split topics from quick-moderation checkboxes
- if (isset($_REQUEST['subname_enc']))
+ if (isset($_REQUEST['subname_enc'])) {
$_REQUEST['subname'] = urldecode($_REQUEST['subname_enc']);
+ }
- Utils::$context['not_selected'] = array(
+ Utils::$context['not_selected'] = [
'num_messages' => 0,
'start' => empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'],
- 'messages' => array(),
- );
+ 'messages' => [],
+ ];
- Utils::$context['selected'] = array(
+ Utils::$context['selected'] = [
'num_messages' => 0,
'start' => empty($_REQUEST['start2']) ? 0 : (int) $_REQUEST['start2'],
- 'messages' => array(),
- );
+ 'messages' => [],
+ ];
- Utils::$context['topic'] = array(
+ Utils::$context['topic'] = [
'id' => Topic::$topic_id,
'subject' => urlencode($_REQUEST['subname']),
- );
+ ];
// Some stuff for our favorite template.
Utils::$context['new_subject'] = $_REQUEST['subname'];
@@ -316,60 +325,60 @@ public function select()
Utils::$context['messages_per_page'] = empty(Config::$modSettings['disableCustomPerPage']) && !empty(Theme::$current->options['messages_per_page']) ? Theme::$current->options['messages_per_page'] : Config::$modSettings['defaultMaxMessages'];
// Get the message ID's from before the move.
- if (isset($_REQUEST['xml']))
- {
- $original_msgs = array(
- 'not_selected' => array(),
- 'selected' => array(),
- );
-
- $request = Db::$db->query('', '
- SELECT id_msg
+ if (isset($_REQUEST['xml'])) {
+ $original_msgs = [
+ 'not_selected' => [],
+ 'selected' => [],
+ ];
+
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_msg
FROM {db_prefix}messages
WHERE id_topic = {int:current_topic}' . (empty($_SESSION['split_selection'][Topic::$topic_id]) ? '' : '
AND id_msg NOT IN ({array_int:no_split_msgs})') . (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
AND approved = {int:is_approved}') . '
' . (empty(Theme::$current->options['view_newest_first']) ? '' : 'ORDER BY id_msg DESC') . '
LIMIT {int:start}, {int:messages_per_page}',
- array(
+ [
'current_topic' => Topic::$topic_id,
- 'no_split_msgs' => empty($_SESSION['split_selection'][Topic::$topic_id]) ? array() : $_SESSION['split_selection'][Topic::$topic_id],
+ 'no_split_msgs' => empty($_SESSION['split_selection'][Topic::$topic_id]) ? [] : $_SESSION['split_selection'][Topic::$topic_id],
'is_approved' => 1,
'start' => Utils::$context['not_selected']['start'],
'messages_per_page' => Utils::$context['messages_per_page'],
- )
+ ],
);
+
// You can't split the last message off.
- if (empty(Utils::$context['not_selected']['start']) && Db::$db->num_rows($request) <= 1 && $_REQUEST['move'] == 'down')
- {
+ if (empty(Utils::$context['not_selected']['start']) && Db::$db->num_rows($request) <= 1 && $_REQUEST['move'] == 'down') {
$_REQUEST['move'] = '';
}
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$original_msgs['not_selected'][] = $row['id_msg'];
}
Db::$db->free_result($request);
- if (!empty($_SESSION['split_selection'][Topic::$topic_id]))
- {
- $request = Db::$db->query('', '
- SELECT id_msg
+ if (!empty($_SESSION['split_selection'][Topic::$topic_id])) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_msg
FROM {db_prefix}messages
WHERE id_topic = {int:current_topic}
AND id_msg IN ({array_int:split_msgs})' . (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
AND approved = {int:is_approved}') . '
' . (empty(Theme::$current->options['view_newest_first']) ? '' : 'ORDER BY id_msg DESC') . '
LIMIT {int:start}, {int:messages_per_page}',
- array(
+ [
'current_topic' => Topic::$topic_id,
'split_msgs' => $_SESSION['split_selection'][Topic::$topic_id],
'is_approved' => 1,
'start' => Utils::$context['selected']['start'],
'messages_per_page' => Utils::$context['messages_per_page'],
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$original_msgs['selected'][] = $row['id_msg'];
}
Db::$db->free_result($request);
@@ -377,83 +386,78 @@ public function select()
}
// (De)select a message..
- if (!empty($_REQUEST['move']))
- {
+ if (!empty($_REQUEST['move'])) {
$_REQUEST['msg'] = (int) $_REQUEST['msg'];
- if ($_REQUEST['move'] == 'reset')
- {
- $_SESSION['split_selection'][Topic::$topic_id] = array();
- }
- elseif ($_REQUEST['move'] == 'up')
- {
- $_SESSION['split_selection'][Topic::$topic_id] = array_diff($_SESSION['split_selection'][Topic::$topic_id], array($_REQUEST['msg']));
- }
- else
- {
+ if ($_REQUEST['move'] == 'reset') {
+ $_SESSION['split_selection'][Topic::$topic_id] = [];
+ } elseif ($_REQUEST['move'] == 'up') {
+ $_SESSION['split_selection'][Topic::$topic_id] = array_diff($_SESSION['split_selection'][Topic::$topic_id], [$_REQUEST['msg']]);
+ } else {
$_SESSION['split_selection'][Topic::$topic_id][] = $_REQUEST['msg'];
}
}
// Make sure the selection is still accurate.
- if (!empty($_SESSION['split_selection'][Topic::$topic_id]))
- {
+ if (!empty($_SESSION['split_selection'][Topic::$topic_id])) {
$split_msgs = $_SESSION['split_selection'][Topic::$topic_id];
- $_SESSION['split_selection'][Topic::$topic_id] = array();
+ $_SESSION['split_selection'][Topic::$topic_id] = [];
- $request = Db::$db->query('', '
- SELECT id_msg
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_msg
FROM {db_prefix}messages
WHERE id_topic = {int:current_topic}
AND id_msg IN ({array_int:split_msgs})' . (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
AND approved = {int:is_approved}'),
- array(
+ [
'current_topic' => Topic::$topic_id,
'split_msgs' => $split_msgs,
'is_approved' => 1,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$_SESSION['split_selection'][Topic::$topic_id][] = $row['id_msg'];
}
Db::$db->free_result($request);
}
// Get the number of messages (not) selected to be split.
- $request = Db::$db->query('', '
- SELECT ' . (empty($_SESSION['split_selection'][Topic::$topic_id]) ? '0' : 'm.id_msg IN ({array_int:split_msgs})') . ' AS is_selected, COUNT(*) AS num_messages
+ $request = Db::$db->query(
+ '',
+ 'SELECT ' . (empty($_SESSION['split_selection'][Topic::$topic_id]) ? '0' : 'm.id_msg IN ({array_int:split_msgs})') . ' AS is_selected, COUNT(*) AS num_messages
FROM {db_prefix}messages AS m
WHERE m.id_topic = {int:current_topic}' . (!Config::$modSettings['postmod_active'] || User::$me->allowedTo('approve_posts') ? '' : '
AND approved = {int:is_approved}') . (empty($_SESSION['split_selection'][Topic::$topic_id]) ? '' : '
GROUP BY is_selected'),
- array(
+ [
'current_topic' => Topic::$topic_id,
- 'split_msgs' => !empty($_SESSION['split_selection'][Topic::$topic_id]) ? $_SESSION['split_selection'][Topic::$topic_id] : array(),
+ 'split_msgs' => !empty($_SESSION['split_selection'][Topic::$topic_id]) ? $_SESSION['split_selection'][Topic::$topic_id] : [],
'is_approved' => 1,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Utils::$context[empty($row['is_selected']) || $row['is_selected'] == 'f' ? 'not_selected' : 'selected']['num_messages'] = $row['num_messages'];
}
Db::$db->free_result($request);
// Fix an oversized starting page (to make sure both pageindexes are properly set).
- if (Utils::$context['selected']['start'] >= Utils::$context['selected']['num_messages'])
- {
+ if (Utils::$context['selected']['start'] >= Utils::$context['selected']['num_messages']) {
Utils::$context['selected']['start'] = Utils::$context['selected']['num_messages'] <= Utils::$context['messages_per_page'] ? 0 : (Utils::$context['selected']['num_messages'] - ((Utils::$context['selected']['num_messages'] % Utils::$context['messages_per_page']) == 0 ? Utils::$context['messages_per_page'] : (Utils::$context['selected']['num_messages'] % Utils::$context['messages_per_page'])));
}
// Build a page list of the not-selected topics...
- Utils::$context['not_selected']['page_index'] = new PageIndex(Config::$scripturl . '?action=splittopics;sa=selectTopics;subname=' . strtr(urlencode($_REQUEST['subname']), array('%' => '%%')) . ';topic=' . Topic::$topic_id . '.%1$d;start2=' . Utils::$context['selected']['start'], Utils::$context['not_selected']['start'], Utils::$context['not_selected']['num_messages'], Utils::$context['messages_per_page'], true);
+ Utils::$context['not_selected']['page_index'] = new PageIndex(Config::$scripturl . '?action=splittopics;sa=selectTopics;subname=' . strtr(urlencode($_REQUEST['subname']), ['%' => '%%']) . ';topic=' . Topic::$topic_id . '.%1$d;start2=' . Utils::$context['selected']['start'], Utils::$context['not_selected']['start'], Utils::$context['not_selected']['num_messages'], Utils::$context['messages_per_page'], true);
// ...and one of the selected topics.
- Utils::$context['selected']['page_index'] = new PageIndex(Config::$scripturl . '?action=splittopics;sa=selectTopics;subname=' . strtr(urlencode($_REQUEST['subname']), array('%' => '%%')) . ';topic=' . Topic::$topic_id . '.' . Utils::$context['not_selected']['start'] . ';start2=%1$d', Utils::$context['selected']['start'], Utils::$context['selected']['num_messages'], Utils::$context['messages_per_page'], true);
+ Utils::$context['selected']['page_index'] = new PageIndex(Config::$scripturl . '?action=splittopics;sa=selectTopics;subname=' . strtr(urlencode($_REQUEST['subname']), ['%' => '%%']) . ';topic=' . Topic::$topic_id . '.' . Utils::$context['not_selected']['start'] . ';start2=%1$d', Utils::$context['selected']['start'], Utils::$context['selected']['num_messages'], Utils::$context['messages_per_page'], true);
// Get the messages and stick them into an array.
- $request = Db::$db->query('', '
- SELECT m.subject, COALESCE(mem.real_name, m.poster_name) AS real_name, m.poster_time, m.body, m.id_msg, m.smileys_enabled
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.subject, COALESCE(mem.real_name, m.poster_name) AS real_name, m.poster_time, m.body, m.id_msg, m.smileys_enabled
FROM {db_prefix}messages AS m
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
WHERE m.id_topic = {int:current_topic}' . (empty($_SESSION['split_selection'][Topic::$topic_id]) ? '' : '
@@ -461,38 +465,38 @@ public function select()
AND approved = {int:is_approved}') . '
' . (empty(Theme::$current->options['view_newest_first']) ? '' : 'ORDER BY m.id_msg DESC') . '
LIMIT {int:start}, {int:messages_per_page}',
- array(
+ [
'current_topic' => Topic::$topic_id,
- 'no_split_msgs' => !empty($_SESSION['split_selection'][Topic::$topic_id]) ? $_SESSION['split_selection'][Topic::$topic_id] : array(),
+ 'no_split_msgs' => !empty($_SESSION['split_selection'][Topic::$topic_id]) ? $_SESSION['split_selection'][Topic::$topic_id] : [],
'is_approved' => 1,
'start' => Utils::$context['not_selected']['start'],
'messages_per_page' => Utils::$context['messages_per_page'],
- )
+ ],
);
- for ($counter = 0; $row = Db::$db->fetch_assoc($request); $counter++)
- {
+
+ for ($counter = 0; $row = Db::$db->fetch_assoc($request); $counter++) {
Lang::censorText($row['subject']);
Lang::censorText($row['body']);
$row['body'] = BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], $row['id_msg']);
- Utils::$context['not_selected']['messages'][$row['id_msg']] = array(
+ Utils::$context['not_selected']['messages'][$row['id_msg']] = [
'id' => $row['id_msg'],
'subject' => $row['subject'],
'time' => Time::create('@' . $row['poster_time'])->format(),
'timestamp' => $row['poster_time'],
'body' => $row['body'],
'poster' => $row['real_name'],
- );
+ ];
}
Db::$db->free_result($request);
// Now get the selected messages.
- if (!empty($_SESSION['split_selection'][Topic::$topic_id]))
- {
+ if (!empty($_SESSION['split_selection'][Topic::$topic_id])) {
// Get the messages and stick them into an array.
- $request = Db::$db->query('', '
- SELECT m.subject, COALESCE(mem.real_name, m.poster_name) AS real_name, m.poster_time, m.body, m.id_msg, m.smileys_enabled
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.subject, COALESCE(mem.real_name, m.poster_name) AS real_name, m.poster_time, m.body, m.id_msg, m.smileys_enabled
FROM {db_prefix}messages AS m
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
WHERE m.id_topic = {int:current_topic}
@@ -500,66 +504,62 @@ public function select()
AND approved = {int:is_approved}') . '
' . (empty(Theme::$current->options['view_newest_first']) ? '' : 'ORDER BY m.id_msg DESC') . '
LIMIT {int:start}, {int:messages_per_page}',
- array(
+ [
'current_topic' => Topic::$topic_id,
'split_msgs' => $_SESSION['split_selection'][Topic::$topic_id],
'is_approved' => 1,
'start' => Utils::$context['selected']['start'],
'messages_per_page' => Utils::$context['messages_per_page'],
- )
+ ],
);
- for ($counter = 0; $row = Db::$db->fetch_assoc($request); $counter++)
- {
+
+ for ($counter = 0; $row = Db::$db->fetch_assoc($request); $counter++) {
Lang::censorText($row['subject']);
Lang::censorText($row['body']);
$row['body'] = BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], $row['id_msg']);
- Utils::$context['selected']['messages'][$row['id_msg']] = array(
+ Utils::$context['selected']['messages'][$row['id_msg']] = [
'id' => $row['id_msg'],
'subject' => $row['subject'],
'time' => Time::create('@' . $row['poster_time'])->format(),
'timestamp' => $row['poster_time'],
'body' => $row['body'],
- 'poster' => $row['real_name']
- );
+ 'poster' => $row['real_name'],
+ ];
}
Db::$db->free_result($request);
}
// The XMLhttp method only needs the stuff that changed, so let's compare.
- if (isset($_REQUEST['xml']))
- {
- $changes = array(
- 'remove' => array(
+ if (isset($_REQUEST['xml'])) {
+ $changes = [
+ 'remove' => [
'not_selected' => array_diff($original_msgs['not_selected'], array_keys(Utils::$context['not_selected']['messages'])),
'selected' => array_diff($original_msgs['selected'], array_keys(Utils::$context['selected']['messages'])),
- ),
- 'insert' => array(
+ ],
+ 'insert' => [
'not_selected' => array_diff(array_keys(Utils::$context['not_selected']['messages']), $original_msgs['not_selected']),
'selected' => array_diff(array_keys(Utils::$context['selected']['messages']), $original_msgs['selected']),
- ),
- );
+ ],
+ ];
- Utils::$context['changes'] = array();
+ Utils::$context['changes'] = [];
- foreach ($changes as $change_type => $change_array)
- {
- foreach ($change_array as $section => $msg_array)
- {
- if (empty($msg_array))
+ foreach ($changes as $change_type => $change_array) {
+ foreach ($change_array as $section => $msg_array) {
+ if (empty($msg_array)) {
continue;
+ }
- foreach ($msg_array as $id_msg)
- {
- Utils::$context['changes'][$change_type . $id_msg] = array(
+ foreach ($msg_array as $id_msg) {
+ Utils::$context['changes'][$change_type . $id_msg] = [
'id' => $id_msg,
'type' => $change_type,
'section' => $section,
- );
+ ];
- if ($change_type == 'insert')
- {
+ if ($change_type == 'insert') {
Utils::$context['changes']['insert' . $id_msg]['insert_value'] = Utils::$context[$section]['messages'][$id_msg];
}
}
@@ -581,15 +581,17 @@ public function splitSelection()
User::$me->checkSession();
// Default the subject in case it's blank.
- if (!isset($_POST['subname']) || $_POST['subname'] == '')
+ if (!isset($_POST['subname']) || $_POST['subname'] == '') {
$_POST['subname'] = Lang::$txt['new_topic'];
+ }
// You must've selected some messages! Can't split out none!
- if (empty($_SESSION['split_selection'][Topic::$topic_id]))
+ if (empty($_SESSION['split_selection'][Topic::$topic_id])) {
ErrorHandler::fatalLang('no_posts_selected', false);
+ }
Utils::$context['old_topic'] = Topic::$topic_id;
- Utils::$context['new_topic'] = splitTopic(Topic::$topic_id, $_SESSION['split_selection'][Topic::$topic_id], $_POST['subname']);
+ Utils::$context['new_topic'] = $this->splitTopic(Topic::$topic_id, $_SESSION['split_selection'][Topic::$topic_id], $_POST['subname']);
Utils::$context['page_title'] = Lang::$txt['split'];
}
@@ -604,8 +606,9 @@ public function splitSelection()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -637,25 +640,28 @@ public static function call(): void
public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject)
{
// Nothing to split?
- if (empty($splitMessages))
+ if (empty($splitMessages)) {
ErrorHandler::fatalLang('no_posts_selected', false);
+ }
// Get some board info.
- $request = Db::$db->query('', '
- SELECT id_board, approved
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board, approved
FROM {db_prefix}topics
WHERE id_topic = {int:id_topic}
LIMIT 1',
- array(
+ [
'id_topic' => $split1_ID_TOPIC,
- )
+ ],
);
list($id_board, $split1_approved) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// Find the new first and last not in the list. (old topic)
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
MIN(m.id_msg) AS myid_first_msg, MAX(m.id_msg) AS myid_last_msg, COUNT(*) AS message_count, m.approved
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:id_topic})
@@ -664,42 +670,40 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
GROUP BY m.approved
ORDER BY m.approved DESC
LIMIT 2',
- array(
+ [
'id_topic' => $split1_ID_TOPIC,
'no_msg_list' => $splitMessages,
- )
+ ],
);
+
// You can't select ALL the messages!
- if (Db::$db->num_rows($request) == 0)
+ if (Db::$db->num_rows($request) == 0) {
ErrorHandler::fatalLang('selected_all_posts', false);
+ }
$split1_first_msg = null;
$split1_last_msg = null;
- while ($row = Db::$db->fetch_assoc($request))
- {
+ while ($row = Db::$db->fetch_assoc($request)) {
// Get the right first and last message dependent on approved state...
- if (empty($split1_first_msg) || $row['myid_first_msg'] < $split1_first_msg)
+ if (empty($split1_first_msg) || $row['myid_first_msg'] < $split1_first_msg) {
$split1_first_msg = $row['myid_first_msg'];
+ }
- if (empty($split1_last_msg) || $row['approved'])
+ if (empty($split1_last_msg) || $row['approved']) {
$split1_last_msg = $row['myid_last_msg'];
+ }
// Get the counts correct...
- if ($row['approved'])
- {
+ if ($row['approved']) {
$split1_replies = $row['message_count'] - 1;
$split1_unapprovedposts = 0;
- }
- else
- {
- if (!isset($split1_replies))
- {
+ } else {
+ if (!isset($split1_replies)) {
$split1_replies = 0;
}
// If the topic isn't approved then num replies must go up by one... as first post wouldn't be counted.
- elseif (!$split1_approved)
- {
+ elseif (!$split1_approved) {
$split1_replies++;
}
@@ -712,48 +716,47 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
$split1_lastMem = Board::getMsgMemberID($split1_last_msg);
// Find the first and last in the list. (new topic)
- $request = Db::$db->query('', '
- SELECT MIN(id_msg) AS myid_first_msg, MAX(id_msg) AS myid_last_msg, COUNT(*) AS message_count, approved
+ $request = Db::$db->query(
+ '',
+ 'SELECT MIN(id_msg) AS myid_first_msg, MAX(id_msg) AS myid_last_msg, COUNT(*) AS message_count, approved
FROM {db_prefix}messages
WHERE id_msg IN ({array_int:msg_list})
AND id_topic = {int:id_topic}
GROUP BY id_topic, approved
ORDER BY approved DESC
LIMIT 2',
- array(
+ [
'msg_list' => $splitMessages,
'id_topic' => $split1_ID_TOPIC,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// As before get the right first and last message dependent on approved state...
- if (empty($split2_first_msg) || $row['myid_first_msg'] < $split2_first_msg)
+ if (empty($split2_first_msg) || $row['myid_first_msg'] < $split2_first_msg) {
$split2_first_msg = $row['myid_first_msg'];
+ }
- if (empty($split2_last_msg) || $row['approved'])
+ if (empty($split2_last_msg) || $row['approved']) {
$split2_last_msg = $row['myid_last_msg'];
+ }
// Then do the counts again...
- if ($row['approved'])
- {
+ if ($row['approved']) {
$split2_approved = true;
$split2_replies = $row['message_count'] - 1;
$split2_unapprovedposts = 0;
- }
- else
- {
+ } else {
// Should this one be approved??
- if ($split2_first_msg == $row['myid_first_msg'])
+ if ($split2_first_msg == $row['myid_first_msg']) {
$split2_approved = false;
+ }
- if (!isset($split2_replies))
- {
+ if (!isset($split2_replies)) {
$split2_replies = 0;
}
// As before, fix number of replies.
- elseif (!$split2_approved)
- {
+ elseif (!$split2_approved) {
$split2_replies++;
}
@@ -766,19 +769,20 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
$split2_lastMem = Board::getMsgMemberID($split2_last_msg);
// No database changes yet, so let's double check to see if everything makes at least a little sense.
- if ($split1_first_msg <= 0 || $split1_last_msg <= 0 || $split2_first_msg <= 0 || $split2_last_msg <= 0 || $split1_replies < 0 || $split2_replies < 0 || $split1_unapprovedposts < 0 || $split2_unapprovedposts < 0 || !isset($split1_approved) || !isset($split2_approved))
- {
+ if ($split1_first_msg <= 0 || $split1_last_msg <= 0 || $split2_first_msg <= 0 || $split2_last_msg <= 0 || $split1_replies < 0 || $split2_replies < 0 || $split1_unapprovedposts < 0 || $split2_unapprovedposts < 0 || !isset($split1_approved) || !isset($split2_approved)) {
ErrorHandler::fatalLang('cant_find_messages');
}
// You cannot split off the first message of a topic.
- if ($split1_first_msg > $split2_first_msg)
+ if ($split1_first_msg > $split2_first_msg) {
ErrorHandler::fatalLang('split_first_post', false);
+ }
// We're off to insert the new topic! Use 0 for now to avoid UNIQUE errors.
- $split2_ID_TOPIC = Db::$db->insert('',
+ $split2_ID_TOPIC = Db::$db->insert(
+ '',
'{db_prefix}topics',
- array(
+ [
'id_board' => 'int',
'id_member_started' => 'int',
'id_member_updated' => 'int',
@@ -788,8 +792,8 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
'unapproved_posts' => 'int',
'approved' => 'int',
'is_sticky' => 'int',
- ),
- array(
+ ],
+ [
(int) $id_board,
$split2_firstMem,
$split2_lastMem,
@@ -799,37 +803,39 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
$split2_unapprovedposts,
(int) $split2_approved,
0,
- ),
- array('id_topic'),
- 1
+ ],
+ ['id_topic'],
+ 1,
);
- if ($split2_ID_TOPIC <= 0)
+ if ($split2_ID_TOPIC <= 0) {
ErrorHandler::fatalLang('cant_insert_topic');
+ }
// Move the messages over to the other topic.
- $new_subject = strtr(Utils::htmlTrim(Utils::htmlspecialchars($new_subject)), array("\r" => '', "\n" => '', "\t" => ''));
+ $new_subject = strtr(Utils::htmlTrim(Utils::htmlspecialchars($new_subject)), ["\r" => '', "\n" => '', "\t" => '']);
// Check the subject length.
- if (Utils::entityStrlen($new_subject) > 100)
+ if (Utils::entityStrlen($new_subject) > 100) {
$new_subject = Utils::entitySubstr($new_subject, 0, 100);
+ }
// Valid subject?
- if ($new_subject != '')
- {
- Db::$db->query('', '
- UPDATE {db_prefix}messages
+ if ($new_subject != '') {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}messages
SET
id_topic = {int:id_topic},
subject = CASE WHEN id_msg = {int:split_first_msg} THEN {string:new_subject} ELSE {string:new_subject_replies} END
WHERE id_msg IN ({array_int:split_msgs})',
- array(
+ [
'split_msgs' => $splitMessages,
'id_topic' => $split2_ID_TOPIC,
'new_subject' => $new_subject,
'split_first_msg' => $split2_first_msg,
'new_subject_replies' => Lang::$txt['response_prefix'] . $new_subject,
- )
+ ],
);
// Cache the new topics subject... we can do it now as all the subjects are the same!
@@ -837,19 +843,21 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
}
// Any associated reported posts better follow...
- Db::$db->query('', '
- UPDATE {db_prefix}log_reported
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}log_reported
SET id_topic = {int:id_topic}
WHERE id_msg IN ({array_int:split_msgs})',
- array(
+ [
'split_msgs' => $splitMessages,
'id_topic' => $split2_ID_TOPIC,
- )
+ ],
);
// Mess with the old topic's first, last, and number of messages.
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET
num_replies = {int:num_replies},
id_first_msg = {int:id_first_msg},
@@ -858,7 +866,7 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
id_member_updated = {int:id_member_updated},
unapproved_posts = {int:unapproved_posts}
WHERE id_topic = {int:id_topic}',
- array(
+ [
'num_replies' => $split1_replies,
'id_first_msg' => $split1_first_msg,
'id_last_msg' => $split1_last_msg,
@@ -866,75 +874,78 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
'id_member_updated' => $split1_lastMem,
'unapproved_posts' => $split1_unapprovedposts,
'id_topic' => $split1_ID_TOPIC,
- )
+ ],
);
// Now, put the first/last message back to what they should be.
- Db::$db->query('', '
- UPDATE {db_prefix}topics
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}topics
SET
id_first_msg = {int:id_first_msg},
id_last_msg = {int:id_last_msg}
WHERE id_topic = {int:id_topic}',
- array(
+ [
'id_first_msg' => $split2_first_msg,
'id_last_msg' => $split2_last_msg,
'id_topic' => $split2_ID_TOPIC,
- )
+ ],
);
// If the new topic isn't approved ensure the first message flags this just in case.
- if (!$split2_approved)
- {
- Db::$db->query('', '
- UPDATE {db_prefix}messages
+ if (!$split2_approved) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}messages
SET approved = {int:approved}
WHERE id_msg = {int:id_msg}
AND id_topic = {int:id_topic}',
- array(
+ [
'approved' => 0,
'id_msg' => $split2_first_msg,
'id_topic' => $split2_ID_TOPIC,
- )
+ ],
);
}
// The board has more topics now (Or more unapproved ones!).
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET ' . ($split2_approved ? '
num_topics = num_topics + 1' : '
unapproved_topics = unapproved_topics + 1') . '
WHERE id_board = {int:id_board}',
- array(
+ [
'id_board' => $id_board,
- )
+ ],
);
// Copy log topic entries.
// @todo This should really be chunked.
- $request = Db::$db->query('', '
- SELECT id_member, id_msg, unwatched
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, id_msg, unwatched
FROM {db_prefix}log_topics
WHERE id_topic = {int:id_topic}',
- array(
+ [
'id_topic' => (int) $split1_ID_TOPIC,
- )
+ ],
);
- if (Db::$db->num_rows($request) > 0)
- {
- $replaceEntries = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
- $replaceEntries[] = array($row['id_member'], $split2_ID_TOPIC, $row['id_msg'], $row['unwatched']);
+ if (Db::$db->num_rows($request) > 0) {
+ $replaceEntries = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $replaceEntries[] = [$row['id_member'], $split2_ID_TOPIC, $row['id_msg'], $row['unwatched']];
}
- Db::$db->insert('ignore',
+ Db::$db->insert(
+ 'ignore',
'{db_prefix}log_topics',
- array('id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int'),
+ ['id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int'],
$replaceEntries,
- array('id_member', 'id_topic')
+ ['id_member', 'id_topic'],
);
unset($replaceEntries);
@@ -945,7 +956,7 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
Logging::updateStats('topic');
Msg::updateLastMessages($id_board);
- Logging::logAction('split', array('topic' => $split1_ID_TOPIC, 'new_topic' => $split2_ID_TOPIC, 'board' => $id_board));
+ Logging::logAction('split', ['topic' => $split1_ID_TOPIC, 'new_topic' => $split2_ID_TOPIC, 'board' => $id_board]);
// Notify people that this topic has been split?
Mail::sendNotifications($split1_ID_TOPIC, 'split');
@@ -953,11 +964,12 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
// If there's a search index that needs updating, update it...
$searchAPI = SearchApi::load();
- if (is_callable(array($searchAPI, 'topicSplit')))
+ if (is_callable([$searchAPI, 'topicSplit'])) {
$searchAPI->topicSplit($split2_ID_TOPIC, $splitMessages);
+ }
// Maybe we want to let an external CMS know about this split
- $split1 = array(
+ $split1 = [
'num_replies' => $split1_replies,
'id_first_msg' => $split1_first_msg,
'id_last_msg' => $split1_last_msg,
@@ -965,9 +977,9 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
'id_member_updated' => $split1_lastMem,
'unapproved_posts' => $split1_unapprovedposts,
'id_topic' => $split1_ID_TOPIC,
- );
+ ];
- $split2 = array(
+ $split2 = [
'num_replies' => $split2_replies,
'id_first_msg' => $split2_first_msg,
'id_last_msg' => $split2_last_msg,
@@ -975,9 +987,9 @@ public static function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject
'id_member_updated' => $split2_lastMem,
'unapproved_posts' => $split2_unapprovedposts,
'id_topic' => $split2_ID_TOPIC,
- );
+ ];
- IntegrationHook::call('integrate_split_topic', array($split1, $split2, $new_subject, $id_board));
+ IntegrationHook::call('integrate_split_topic', [$split1, $split2, $new_subject, $id_board]);
// Return the ID of the newly created topic.
return $split2_ID_TOPIC;
@@ -1033,19 +1045,20 @@ public static function SplitSelectionExecute(): void
protected function __construct()
{
// The 'split' sub-action used to be called 'execute'.
- if (!empty($_GET['sa']) && $_GET['sa'] === 'execute')
- {
+ if (!empty($_GET['sa']) && $_GET['sa'] === 'execute') {
$_GET['sa'] = 'split';
$_REQUEST['sa'] = 'split';
}
- if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']]))
+ if (!empty($_GET['sa']) && isset(self::$subactions[$_GET['sa']])) {
$this->subaction = $_GET['sa'];
+ }
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TopicSplit::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TopicSplit::exportStatic')) {
TopicSplit::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/TrackIP.php b/Sources/Actions/TrackIP.php
index 08bee8c635..ed94e9588c 100644
--- a/Sources/Actions/TrackIP.php
+++ b/Sources/Actions/TrackIP.php
@@ -14,19 +14,18 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
-use SMF\Lang;
use SMF\IntegrationHook;
use SMF\IP;
use SMF\ItemList;
+use SMF\Lang;
use SMF\Profile;
use SMF\Theme;
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Rename here and in the exportStatic call at the end of the file.
@@ -40,26 +39,27 @@ class TrackIP implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'call' => false,
- ),
- );
+ private static $backcompat = [
+ 'func_names' => [
+ 'list_getIPMessages' => 'list_getIPMessages',
+ 'list_getIPMessageCount' => 'list_getIPMessageCount',
+ 'trackIP' => 'TrackIP',
+ ],
+ ];
/*******************
* Public properties
*******************/
/**
- * @var int $memID
+ * @var int
*
* ID of the member to track.
*/
public int $memID;
/**
- * @var bool $standalone
+ * @var bool
*
* True if this was called via ?action=trackip.
* False if this was called via ?action=profile;area=tracking;sa=ip.
@@ -90,16 +90,13 @@ public function execute(): void
// Can the user do this?
User::$me->isAllowedTo('moderate_forum');
- if ($this->standalone)
- {
+ if ($this->standalone) {
Theme::loadTemplate('Profile');
Lang::load('Profile');
Utils::$context['base_url'] = Config::$scripturl . '?action=trackip';
Utils::$context['ip'] = IP::ip2range(User::$me->ip);
- }
- else
- {
+ } else {
Utils::$context['base_url'] = Config::$scripturl . '?action=profile;area=tracking;sa=ip;u=' . $this->memID;
Utils::$context['ip'] = IP::ip2range(User::$loaded[$this->memID]->ip);
@@ -108,43 +105,44 @@ public function execute(): void
Utils::$context['sub_template'] = 'trackIP';
// Searching?
- if (isset($_REQUEST['searchip']))
+ if (isset($_REQUEST['searchip'])) {
Utils::$context['ip'] = IP::ip2range(trim($_REQUEST['searchip']));
+ }
- if (count(Utils::$context['ip']) !== 2)
+ if (count(Utils::$context['ip']) !== 2) {
ErrorHandler::fatalLang('invalid_tracking_ip', false);
+ }
- $ip_string = array('{inet:ip_address_low}', '{inet:ip_address_high}');
+ $ip_string = ['{inet:ip_address_low}', '{inet:ip_address_high}'];
- $fields = array(
+ $fields = [
'ip_address_low' => Utils::$context['ip']['low'],
'ip_address_high' => Utils::$context['ip']['high'],
- );
+ ];
$ip_var = Utils::$context['ip'];
- if (Utils::$context['ip']['low'] !== Utils::$context['ip']['high'])
- {
+ if (Utils::$context['ip']['low'] !== Utils::$context['ip']['high']) {
Utils::$context['ip'] = Utils::$context['ip']['low'] . '-' . Utils::$context['ip']['high'];
- }
- else
- {
+ } else {
Utils::$context['ip'] = Utils::$context['ip']['low'];
}
- if ($this->standalone)
+ if ($this->standalone) {
Utils::$context['page_title'] = Lang::$txt['trackIP'] . ' - ' . Utils::$context['ip'];
+ }
- Utils::$context['ips'] = array();
+ Utils::$context['ips'] = [];
- $request = Db::$db->query('', '
- SELECT id_member, real_name AS display_name, member_ip
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name AS display_name, member_ip
FROM {db_prefix}members
WHERE member_ip >= ' . $ip_string[0] . ' and member_ip <= ' . $ip_string[1],
- $fields
+ $fields,
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Utils::$context['ips'][(string) new IP($row['member_ip'])][] = ' ' . $row['display_name'] . '';
}
Db::$db->free_result($request);
@@ -155,7 +153,7 @@ public function execute(): void
$max_per_page = empty(Config::$modSettings['disableCustomPerPage']) && !empty(Theme::$current->options['messages_per_page']) ? Theme::$current->options['messages_per_page'] : Config::$modSettings['defaultMaxMessages'];
// Start with the user messages.
- $list_options = array(
+ $list_options = [
'id' => 'track_message_list',
'title' => Lang::$txt['messages_from_ip'] . ' ' . Utils::$context['ip'],
'start_var_name' => 'messageStart',
@@ -163,87 +161,87 @@ public function execute(): void
'no_items_label' => Lang::$txt['no_messages_from_ip'],
'base_href' => Utils::$context['base_url'] . ';searchip=' . Utils::$context['ip'],
'default_sort_col' => 'date',
- 'get_items' => array(
+ 'get_items' => [
'function' => __CLASS__ . '::list_getIPMessages',
- 'params' => array(
+ 'params' => [
'm.poster_ip >= ' . $ip_string[0] . ' and m.poster_ip <= ' . $ip_string[1],
$fields,
- ),
- ),
- 'get_count' => array(
+ ],
+ ],
+ 'get_count' => [
'function' => __CLASS__ . '::list_getIPMessageCount',
- 'params' => array(
+ 'params' => [
'm.poster_ip >= ' . $ip_string[0] . ' and m.poster_ip <= ' . $ip_string[1],
$fields,
- ),
- ),
- 'columns' => array(
- 'ip_address' => array(
- 'header' => array(
+ ],
+ ],
+ 'columns' => [
+ 'ip_address' => [
+ 'header' => [
'value' => Lang::$txt['ip_address'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' %1$s',
- 'params' => array(
+ 'params' => [
'ip' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'm.poster_ip',
'reverse' => 'm.poster_ip DESC',
- ),
- ),
- 'poster' => array(
- 'header' => array(
+ ],
+ ],
+ 'poster' => [
+ 'header' => [
'value' => Lang::$txt['poster'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'member_link',
- ),
- ),
- 'subject' => array(
- 'header' => array(
+ ],
+ ],
+ 'subject' => [
+ 'header' => [
'value' => Lang::$txt['subject'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' %3$s',
- 'params' => array(
+ 'params' => [
'topic' => false,
'id' => false,
'subject' => false,
- ),
- ),
- ),
- ),
- 'date' => array(
- 'header' => array(
+ ],
+ ],
+ ],
+ ],
+ 'date' => [
+ 'header' => [
'value' => Lang::$txt['date'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'm.id_msg DESC',
'reverse' => 'm.id_msg',
- ),
- ),
- ),
- 'additional_rows' => array(
- array(
+ ],
+ ],
+ ],
+ 'additional_rows' => [
+ [
'position' => 'after_title',
'value' => Lang::$txt['messages_from_ip_desc'],
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the messages list.
new ItemList($list_options);
// Set the options for the error lists.
- $list_options = array(
+ $list_options = [
'id' => 'track_user_list',
'title' => Lang::$txt['errors_from_ip'] . ' ' . Utils::$context['ip'],
'start_var_name' => 'errorStart',
@@ -251,111 +249,110 @@ public function execute(): void
'no_items_label' => Lang::$txt['no_errors_from_ip'],
'base_href' => Utils::$context['base_url'] . ';searchip=' . Utils::$context['ip'],
'default_sort_col' => 'date2',
- 'get_items' => array(
+ 'get_items' => [
'function' => 'list_getUserErrors',
- 'params' => array(
+ 'params' => [
'le.ip >= ' . $ip_string[0] . ' and le.ip <= ' . $ip_string[1],
$fields,
- ),
- ),
- 'get_count' => array(
+ ],
+ ],
+ 'get_count' => [
'function' => 'list_getUserErrorCount',
- 'params' => array(
+ 'params' => [
'ip >= ' . $ip_string[0] . ' and ip <= ' . $ip_string[1],
$fields,
- ),
- ),
- 'columns' => array(
- 'ip_address2' => array(
- 'header' => array(
+ ],
+ ],
+ 'columns' => [
+ 'ip_address2' => [
+ 'header' => [
'value' => Lang::$txt['ip_address'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => ' %1$s',
- 'params' => array(
+ 'params' => [
'ip' => false,
- ),
- ),
- ),
- 'sort' => array(
+ ],
+ ],
+ ],
+ 'sort' => [
'default' => 'le.ip',
'reverse' => 'le.ip DESC',
- ),
- ),
- 'display_name' => array(
- 'header' => array(
+ ],
+ ],
+ 'display_name' => [
+ 'header' => [
'value' => Lang::$txt['display_name'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'member_link',
- ),
- ),
- 'message' => array(
- 'header' => array(
+ ],
+ ],
+ 'message' => [
+ 'header' => [
'value' => Lang::$txt['message'],
- ),
- 'data' => array(
- 'sprintf' => array(
+ ],
+ 'data' => [
+ 'sprintf' => [
'format' => '%1$s %2$s',
- 'params' => array(
+ 'params' => [
'message' => false,
'url' => false,
- ),
- ),
+ ],
+ ],
'class' => 'word_break',
- ),
- ),
- 'date2' => array(
- 'header' => array(
+ ],
+ ],
+ 'date2' => [
+ 'header' => [
'value' => Lang::$txt['date'],
- ),
- 'data' => array(
+ ],
+ 'data' => [
'db' => 'time',
- ),
- 'sort' => array(
+ ],
+ 'sort' => [
'default' => 'le.id_error DESC',
'reverse' => 'le.id_error',
- ),
- ),
- ),
- 'additional_rows' => array(
- array(
+ ],
+ ],
+ ],
+ 'additional_rows' => [
+ [
'position' => 'after_title',
'value' => Lang::$txt['errors_from_ip_desc'],
- ),
- ),
- );
+ ],
+ ],
+ ];
// Create the error list.
new ItemList($list_options);
// Allow 3rd party integrations to add in their own lists or whatever.
- Utils::$context['additional_track_lists'] = array();
- IntegrationHook::call('integrate_profile_trackip', array($ip_string, $ip_var));
+ Utils::$context['additional_track_lists'] = [];
+ IntegrationHook::call('integrate_profile_trackip', [$ip_string, $ip_var]);
Utils::$context['single_ip'] = ($ip_var['low'] === $ip_var['high']);
- if (Utils::$context['single_ip'])
- {
- Utils::$context['whois_servers'] = array(
- 'apnic' => array(
+ if (Utils::$context['single_ip']) {
+ Utils::$context['whois_servers'] = [
+ 'apnic' => [
'name' => Lang::$txt['whois_apnic'],
'url' => 'https://wq.apnic.net/apnic-bin/whois.pl?searchtext=' . Utils::$context['ip'],
- ),
- 'arin' => array(
+ ],
+ 'arin' => [
'name' => Lang::$txt['whois_arin'],
'url' => 'https://whois.arin.net/rest/ip/' . Utils::$context['ip'],
- ),
- 'lacnic' => array(
+ ],
+ 'lacnic' => [
'name' => Lang::$txt['whois_lacnic'],
'url' => 'https://lacnic.net/cgi-bin/lacnic/whois?query=' . Utils::$context['ip'],
- ),
- 'ripe' => array(
+ ],
+ 'ripe' => [
'name' => Lang::$txt['whois_ripe'],
'url' => 'https://apps.db.ripe.net/search/query.html?searchtext=' . Utils::$context['ip'],
- ),
- );
+ ],
+ ];
}
}
@@ -370,8 +367,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;
}
@@ -394,13 +392,14 @@ public static function call(): void
* @param array $where_vars An array of parameters for $where
* @return array An array containing information about the posts
*/
- public static function list_getIPMessages(int $start, int $items_per_page, string $sort, string $where, array $where_vars = array()): array
+ public static function list_getIPMessages(int $start, int $items_per_page, string $sort, string $where, array $where_vars = []): array
{
- $messages = array();
+ $messages = [];
// Get all the messages fitting this where clause.
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
m.id_msg, m.poster_ip, COALESCE(mem.real_name, m.poster_name) AS display_name, mem.id_member,
m.subject, m.poster_time, m.id_topic, m.id_board
FROM {db_prefix}messages AS m
@@ -408,27 +407,27 @@ public static function list_getIPMessages(int $start, int $items_per_page, strin
WHERE {query_see_message_board} AND ' . $where . '
ORDER BY {raw:sort}
LIMIT {int:start}, {int:max}',
- array_merge($where_vars, array(
+ array_merge($where_vars, [
'sort' => $sort,
'start' => $start,
'max' => $items_per_page,
- ))
+ ]),
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $messages[] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $messages[] = [
'ip' => new IP($row['poster_ip']),
'member_link' => empty($row['id_member']) ? $row['display_name'] : ' ' . $row['display_name'] . '',
- 'board' => array(
+ 'board' => [
'id' => $row['id_board'],
- 'href' => Config::$scripturl . '?board=' . $row['id_board']
- ),
+ 'href' => Config::$scripturl . '?board=' . $row['id_board'],
+ ],
'topic' => $row['id_topic'],
'id' => $row['id_msg'],
'subject' => $row['subject'],
'time' => Time::create('@' . $row['poster_time'])->format(),
- 'timestamp' => $row['poster_time']
- );
+ 'timestamp' => $row['poster_time'],
+ ];
}
Db::$db->free_result($request);
@@ -442,13 +441,14 @@ public static function list_getIPMessages(int $start, int $items_per_page, strin
* @param array $where_vars The parameters for $where
* @return int Count of messages matching the IP
*/
- public static function list_getIPMessageCount(string $where, array $where_vars = array()): int
+ public static function list_getIPMessageCount(string $where, array $where_vars = []): int
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}messages AS m
WHERE {query_see_message_board} AND ' . $where,
- $where_vars
+ $where_vars,
);
list($count) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -481,14 +481,12 @@ protected function __construct()
// have already been loaded. If it isn't, this was called directly.
$this->standalone = !class_exists(__NAMESPACE__ . '\\Profile\\Main', false);
- if ($this->standalone)
- {
+ if ($this->standalone) {
$this->memID = User::$me->id;
- }
- else
- {
- if (!isset(Profile::$member))
+ } else {
+ if (!isset(Profile::$member)) {
Profile::load();
+ }
$this->memID = Profile::$member->id;
}
@@ -496,7 +494,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\TrackIP::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\TrackIP::exportStatic')) {
TrackIP::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Unread.php b/Sources/Actions/Unread.php
index 232bc71641..9219fb24af 100644
--- a/Sources/Actions/Unread.php
+++ b/Sources/Actions/Unread.php
@@ -14,9 +14,9 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
@@ -24,7 +24,6 @@
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Finds and retrieves information about new posts and topics.
@@ -38,12 +37,11 @@ class Unread implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'UnreadTopics',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -55,14 +53,14 @@ class Unread implements ActionInterface
* Ways to sort the posts.
* Keys are requestable methods, values are SQL ORDER BY statements
*/
- public array $sort_methods = array(
+ public array $sort_methods = [
'subject' => 'ms.subject',
'starter' => 'COALESCE(mems.real_name, ms.poster_name)',
'replies' => 't.num_replies',
'views' => 't.num_views',
'first_post' => 't.id_topic',
- 'last_post' => 't.id_last_msg'
- );
+ 'last_post' => 't.id_last_msg',
+ ];
/*********************
* Internal properties
@@ -115,7 +113,7 @@ class Unread implements ActionInterface
*
* The boards to look in.
*/
- protected array $boards = array();
+ protected array $boards = [];
/**
* @var string
@@ -129,7 +127,7 @@ class Unread implements ActionInterface
*
* Parameters for the main query.
*/
- protected array $query_parameters = array();
+ protected array $query_parameters = [];
/**
* @var string
@@ -151,7 +149,7 @@ class Unread implements ActionInterface
* Columns for the SQL SELECT clause. This part is the same for each query.
* More columns will be added at runtime if avatars are shown on indices.
*/
- protected array $selects = array(
+ protected array $selects = [
'ms.subject AS first_subject',
'ms.poster_time AS first_poster_time',
'ms.id_topic',
@@ -183,7 +181,7 @@ class Unread implements ActionInterface
'ml.id_msg_modified',
't.approved',
't.unapproved_posts',
- );
+ ];
/**
* @var int
@@ -245,8 +243,9 @@ public function execute(): void
$this->setPaginationAndLinks();
// If they've read everything, we're done here.
- if (empty($this->num_topics))
+ if (empty($this->num_topics)) {
return;
+ }
$this->getTopics();
$this->buildButtons();
@@ -268,8 +267,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;
}
@@ -295,14 +295,14 @@ protected function __construct()
User::$me->kickIfGuest();
// Prefetching + lots of MySQL work = bad mojo.
- if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
- {
+ if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
ob_end_clean();
Utils::sendHttpStatus(403);
+
die;
}
- Utils::$context['topics'] = array();
+ Utils::$context['topics'] = [];
Utils::$context['showCheckboxes'] = !empty(Theme::$current->options['display_quick_mod']) && Theme::$current->options['display_quick_mod'] == 1;
@@ -319,12 +319,9 @@ protected function __construct()
$this->linktree_name = Lang::$txt['unread_topics_visit'];
$this->action_url = Config::$scripturl . '?action=unread';
- if (Utils::$context['showing_all_topics'])
- {
+ if (Utils::$context['showing_all_topics']) {
$this->checkLoadAverageAll();
- }
- else
- {
+ } else {
$this->checkLoadAverage();
}
@@ -333,10 +330,11 @@ protected function __construct()
Utils::$context['sub_template'] = $this->sub_template;
// Setup the default topic icons... for checking they exist and the like ;)
- Utils::$context['icon_sources'] = array();
+ Utils::$context['icon_sources'] = [];
- foreach (Utils::$context['stable_icons'] as $icon)
+ foreach (Utils::$context['stable_icons'] as $icon) {
Utils::$context['icon_sources'][$icon] = 'images_url';
+ }
}
/**
@@ -344,14 +342,17 @@ protected function __construct()
*/
protected function checkLoadAverage()
{
- if (empty(Utils::$context['load_average']))
+ if (empty(Utils::$context['load_average'])) {
return;
+ }
- if (empty(Config::$modSettings['loadavg_unread']))
+ if (empty(Config::$modSettings['loadavg_unread'])) {
return;
+ }
- if (Utils::$context['load_average'] >= Config::$modSettings['loadavg_unread'])
+ if (Utils::$context['load_average'] >= Config::$modSettings['loadavg_unread']) {
ErrorHandler::fatalLang('loadavg_unread_disabled', false);
+ }
}
/**
@@ -359,14 +360,17 @@ protected function checkLoadAverage()
*/
protected function checkLoadAverageAll()
{
- if (empty(Utils::$context['load_average']))
+ if (empty(Utils::$context['load_average'])) {
return;
+ }
- if (empty(Config::$modSettings['loadavg_allunread']))
+ if (empty(Config::$modSettings['loadavg_allunread'])) {
return;
+ }
- if (Utils::$context['load_average'] >= Config::$modSettings['loadavg_allunread'])
+ if (Utils::$context['load_average'] >= Config::$modSettings['loadavg_allunread']) {
ErrorHandler::fatalLang('loadavg_allunread_disabled', false);
+ }
}
/**
@@ -379,130 +383,133 @@ protected function checkLoadAverageAll()
protected function getBoards()
{
// Are we specifying any specific board?
- if (isset($_REQUEST['children']) && (!empty(Board::$info->id) || !empty($_REQUEST['boards'])))
- {
- if (!empty($_REQUEST['boards']))
- {
+ if (isset($_REQUEST['children']) && (!empty(Board::$info->id) || !empty($_REQUEST['boards']))) {
+ if (!empty($_REQUEST['boards'])) {
$_REQUEST['boards'] = explode(',', $_REQUEST['boards']);
- foreach ($_REQUEST['boards'] as $b)
+ foreach ($_REQUEST['boards'] as $b) {
$this->boards[] = (int) $b;
+ }
}
- if (!empty(Board::$info->id))
+ if (!empty(Board::$info->id)) {
$this->boards[] = (int) Board::$info->id;
+ }
// The easiest thing is to just get all the boards they can see, but since we've specified the top of tree we ignore some of them
- $request = Db::$db->query('', '
- SELECT b.id_board, b.id_parent
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board, b.id_parent
FROM {db_prefix}boards AS b
WHERE {query_wanna_see_board}
AND b.child_level > {int:no_child}
AND b.id_board NOT IN ({array_int:boards})
ORDER BY child_level ASC',
- array(
+ [
'no_child' => 0,
'boards' => $this->boards,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (in_array($row['id_parent'], $this->boards))
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (in_array($row['id_parent'], $this->boards)) {
$this->boards[] = $row['id_board'];
+ }
}
Db::$db->free_result($request);
- if (empty($this->boards))
+ if (empty($this->boards)) {
ErrorHandler::fatalLang('error_no_boards_selected');
+ }
$this->query_this_board = 'id_board IN ({array_int:boards})';
$this->query_parameters['boards'] = $this->boards;
Utils::$context['querystring_board_limits'] = ';boards=' . implode(',', $this->boards) . ';start=%1$d';
- }
- elseif (!empty(Board::$info->id))
- {
+ } elseif (!empty(Board::$info->id)) {
$this->query_this_board = 'id_board = {int:board}';
$this->query_parameters['board'] = Board::$info->id;
Utils::$context['querystring_board_limits'] = ';board=' . Board::$info->id . '.%1$d';
- }
- elseif (!empty($_REQUEST['boards']))
- {
+ } elseif (!empty($_REQUEST['boards'])) {
$_REQUEST['boards'] = explode(',', $_REQUEST['boards']);
- foreach ($_REQUEST['boards'] as $i => $b)
+ foreach ($_REQUEST['boards'] as $i => $b) {
$_REQUEST['boards'][$i] = (int) $b;
+ }
- $request = Db::$db->query('', '
- SELECT b.id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board
FROM {db_prefix}boards AS b
WHERE {query_see_board}
AND b.id_board IN ({array_int:board_list})',
- array(
+ [
'board_list' => $_REQUEST['boards'],
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$this->boards[] = $row['id_board'];
}
Db::$db->free_result($request);
- if (empty($this->boards))
+ if (empty($this->boards)) {
ErrorHandler::fatalLang('error_no_boards_selected');
+ }
$this->query_this_board = 'id_board IN ({array_int:boards})';
$this->query_parameters['boards'] = $this->boards;
Utils::$context['querystring_board_limits'] = ';boards=' . implode(',', $this->boards) . ';start=%1$d';
- }
- elseif (!empty($_REQUEST['c']))
- {
+ } elseif (!empty($_REQUEST['c'])) {
$_REQUEST['c'] = explode(',', $_REQUEST['c']);
- foreach ($_REQUEST['c'] as $i => $c)
+ foreach ($_REQUEST['c'] as $i => $c) {
$_REQUEST['c'][$i] = (int) $c;
+ }
- $request = Db::$db->query('', '
- SELECT b.id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board
FROM {db_prefix}boards AS b
WHERE ' . User::$me->{$this->see_board} . '
AND b.id_cat IN ({array_int:id_cat})',
- array(
+ [
'id_cat' => $_REQUEST['c'],
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$this->boards[] = $row['id_board'];
}
Db::$db->free_result($request);
- if (empty($this->boards))
+ if (empty($this->boards)) {
ErrorHandler::fatalLang('error_no_boards_selected');
+ }
$this->query_this_board = 'id_board IN ({array_int:boards})';
$this->query_parameters['boards'] = $this->boards;
Utils::$context['querystring_board_limits'] = ';c=' . implode(',', $_REQUEST['c']) . ';start=%1$d';
- }
- else
- {
+ } else {
// Don't bother to show deleted posts!
- $request = Db::$db->query('', '
- SELECT b.id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board
FROM {db_prefix}boards AS b
WHERE ' . User::$me->{$this->see_board} . (!empty(Config::$modSettings['recycle_enable']) && Config::$modSettings['recycle_board'] > 0 ? '
AND b.id_board != {int:recycle_board}' : ''),
- array(
+ [
'recycle_board' => (int) Config::$modSettings['recycle_board'],
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$this->boards[] = $row['id_board'];
}
Db::$db->free_result($request);
- if (empty($this->boards))
+ if (empty($this->boards)) {
ErrorHandler::fatalLang('error_no_boards_available', false);
+ }
$this->query_this_board = 'id_board IN ({array_int:boards})';
$this->query_parameters['boards'] = $this->boards;
@@ -516,16 +523,16 @@ protected function getBoards()
*/
protected function getCatName()
{
- if (!empty($_REQUEST['c']) && is_array($_REQUEST['c']) && count($_REQUEST['c']) == 1)
- {
- $request = Db::$db->query('', '
- SELECT name
+ if (!empty($_REQUEST['c']) && is_array($_REQUEST['c']) && count($_REQUEST['c']) == 1) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT name
FROM {db_prefix}categories
WHERE id_cat = {int:id_cat}
LIMIT 1',
- array(
+ [
'id_cat' => (int) $_REQUEST['c'][0],
- )
+ ],
);
list($this->cat_name) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -538,14 +545,12 @@ protected function getCatName()
protected function setSortMethod()
{
// We only know these.
- if (isset($_REQUEST['sort']) && !in_array($_REQUEST['sort'], array_keys($this->sort_methods)))
- {
+ if (isset($_REQUEST['sort']) && !in_array($_REQUEST['sort'], array_keys($this->sort_methods))) {
$_REQUEST['sort'] = 'last_post';
}
// The default is the most logical: newest first.
- if (!isset($_REQUEST['sort']) || !isset($this->sort_methods[$_REQUEST['sort']]))
- {
+ if (!isset($_REQUEST['sort']) || !isset($this->sort_methods[$_REQUEST['sort']])) {
Utils::$context['sort_by'] = 'last_post';
$_REQUEST['sort'] = 't.id_last_msg';
$this->ascending = isset($_REQUEST['asc']);
@@ -553,8 +558,7 @@ protected function setSortMethod()
Utils::$context['querystring_sort_limits'] = $this->ascending ? ';asc' : '';
}
// But, for other methods the default sort is ascending.
- else
- {
+ else {
Utils::$context['sort_by'] = $_REQUEST['sort'];
$_REQUEST['sort'] = $this->sort_methods[$_REQUEST['sort']];
$this->ascending = !isset($_REQUEST['desc']);
@@ -566,8 +570,7 @@ protected function setSortMethod()
Lang::$txt['starter'] = Lang::$txt['started_by'];
- foreach ($this->sort_methods as $key => $val)
- {
+ foreach ($this->sort_methods as $key => $val) {
Utils::$context['topics_headers'][$key] = ' ' . Lang::$txt[$key] . (Utils::$context['sort_by'] == $key ? ' ' : '') . '';
}
}
@@ -580,36 +583,32 @@ protected function setPaginationAndLinks()
$not_first_page = Utils::$context['start'] >= Utils::$context['topics_per_page'];
$not_last_page = Utils::$context['start'] + Utils::$context['topics_per_page'] < $this->num_topics;
- $url_limits = array(
+ $url_limits = [
'first' => sprintf(Utils::$context['querystring_board_limits'], 0) . Utils::$context['querystring_sort_limits'],
'prev' => sprintf(Utils::$context['querystring_board_limits'], Utils::$context['start'] - Utils::$context['topics_per_page']) . Utils::$context['querystring_sort_limits'],
'next' => sprintf(Utils::$context['querystring_board_limits'], Utils::$context['start'] + Utils::$context['topics_per_page']) . Utils::$context['querystring_sort_limits'],
- 'last' => sprintf(Utils::$context['querystring_board_limits'], $this->num_topics - ($this->num_topics % Utils::$context['topics_per_page'])) . Utils::$context['querystring_sort_limits']
- );
+ 'last' => sprintf(Utils::$context['querystring_board_limits'], $this->num_topics - ($this->num_topics % Utils::$context['topics_per_page'])) . Utils::$context['querystring_sort_limits'],
+ ];
- if (isset($this->cat_name))
- {
- Utils::$context['linktree'][] = array(
+ if (isset($this->cat_name)) {
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '#c' . (int) $_REQUEST['c'][0],
'name' => $this->cat_name,
- );
+ ];
}
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => $this->action_url . $url_limits['first'],
'name' => $this->linktree_name,
- );
+ ];
- if (Utils::$context['showing_all_topics'])
- {
- Utils::$context['linktree'][] = array(
+ if (Utils::$context['showing_all_topics']) {
+ Utils::$context['linktree'][] = [
'url' => $this->action_url . ';all' . $url_limits['first'],
'name' => Lang::$txt['unread_topics_all'],
- );
- }
- else
- {
- Lang::$txt['unread_topics_visit_none'] = strtr(sprintf(Lang::$txt['unread_topics_visit_none'], Config::$scripturl), array('?action=unread;all' => '?action=unread;all' . $url_limits['first']));
+ ];
+ } else {
+ Lang::$txt['unread_topics_visit_none'] = strtr(sprintf(Lang::$txt['unread_topics_visit_none'], Config::$scripturl), ['?action=unread;all' => '?action=unread;all' . $url_limits['first']]);
}
// Make sure the starting place makes sense and construct the page index.
@@ -617,18 +616,18 @@ protected function setPaginationAndLinks()
Utils::$context['current_page'] = floor(Utils::$context['start'] / Utils::$context['topics_per_page']);
- Utils::$context['links'] = array(
+ Utils::$context['links'] = [
'first' => $not_first_page ? $this->action_url . (Utils::$context['showing_all_topics'] ? ';all' : '') . $url_limits['first'] : '',
'prev' => $not_first_page ? $this->action_url . (Utils::$context['showing_all_topics'] ? ';all' : '') . $url_limits['prev'] : '',
'next' => $not_last_page ? $this->action_url . (Utils::$context['showing_all_topics'] ? ';all' : '') . $url_limits['next'] : '',
'last' => $not_last_page ? $this->action_url . (Utils::$context['showing_all_topics'] ? ';all' : '') . $url_limits['last'] : '',
'up' => Config::$scripturl,
- );
+ ];
- Utils::$context['page_info'] = array(
+ Utils::$context['page_info'] = [
'current_page' => Utils::$context['current_page'] + 1,
'num_pages' => floor(($this->num_topics - 1) / Utils::$context['topics_per_page']) + 1,
- );
+ ];
}
/**
@@ -637,21 +636,17 @@ protected function setPaginationAndLinks()
protected function setNoTopics()
{
// Is this an all topics query?
- if (Utils::$context['showing_all_topics'])
- {
+ if (Utils::$context['showing_all_topics']) {
// Since there are no unread topics, mark the boards as read!
Board::markBoardsRead(empty($this->boards) ? Board::$info->id : $this->boards);
}
- Utils::$context['topics'] = array();
+ Utils::$context['topics'] = [];
Utils::$context['no_topic_listing'] = true;
- if (Utils::$context['querystring_board_limits'] == ';start=%1$d')
- {
+ if (Utils::$context['querystring_board_limits'] == ';start=%1$d') {
Utils::$context['querystring_board_limits'] = '';
- }
- else
- {
+ } else {
Utils::$context['querystring_board_limits'] = sprintf(Utils::$context['querystring_board_limits'], Utils::$context['start']);
}
}
@@ -661,9 +656,8 @@ protected function setNoTopics()
*/
protected function finalizeSelects()
{
- if (!empty(Theme::$current->settings['avatars_on_indexes']))
- {
- $this->selects = array_merge($this->selects, array(
+ if (!empty(Theme::$current->settings['avatars_on_indexes'])) {
+ $this->selects = array_merge($this->selects, [
'meml.avatar',
'meml.email_address',
'mems.avatar AS first_member_avatar',
@@ -674,7 +668,7 @@ protected function finalizeSelects()
'COALESCE(al.id_attach, 0) AS last_poster_id_attach',
'al.filename AS last_member_filename',
'al.attachment_type AS last_poster_attach_type',
- ));
+ ]);
}
}
@@ -683,70 +677,66 @@ protected function finalizeSelects()
*/
protected function getEarliestMsg()
{
- if (!Utils::$context['showing_all_topics'])
+ if (!Utils::$context['showing_all_topics']) {
return;
+ }
- if (!empty(Board::$info->id))
- {
- $request = Db::$db->query('', '
- SELECT MIN(id_msg)
+ if (!empty(Board::$info->id)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT MIN(id_msg)
FROM {db_prefix}log_mark_read
WHERE id_member = {int:current_member}
AND id_board = {int:current_board}',
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
- )
+ ],
);
list($this->earliest_msg) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- }
- else
- {
- $request = Db::$db->query('', '
- SELECT MIN(lmr.id_msg)
+ } else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT MIN(lmr.id_msg)
FROM {db_prefix}boards AS b
LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = b.id_board AND lmr.id_member = {int:current_member})
WHERE {query_see_board}',
- array(
+ [
'current_member' => User::$me->id,
- )
+ ],
);
list($this->earliest_msg) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
}
// This is needed in case of topics marked unread.
- if (empty($this->earliest_msg))
- {
+ if (empty($this->earliest_msg)) {
$this->earliest_msg = 0;
- }
- else
- {
+ } else {
// Using caching, when possible, to ignore the below slow query.
- if (isset($_SESSION['cached_log_time']) && $_SESSION['cached_log_time'][0] + 45 > time())
- {
+ if (isset($_SESSION['cached_log_time']) && $_SESSION['cached_log_time'][0] + 45 > time()) {
$earliest_msg2 = $_SESSION['cached_log_time'][1];
- }
- else
- {
+ } else {
// This query is pretty slow, but it's needed to ensure nothing crucial is ignored.
- $request = Db::$db->query('', '
- SELECT MIN(id_msg)
+ $request = Db::$db->query(
+ '',
+ 'SELECT MIN(id_msg)
FROM {db_prefix}log_topics
WHERE id_member = {int:current_member}',
- array(
+ [
'current_member' => User::$me->id,
- )
+ ],
);
list($earliest_msg2) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
// In theory this could be zero, if the first ever post is unread, so fudge it ;)
- if ($earliest_msg2 == 0)
+ if ($earliest_msg2 == 0) {
$earliest_msg2 = -1;
+ }
- $_SESSION['cached_log_time'] = array(time(), $earliest_msg2);
+ $_SESSION['cached_log_time'] = [time(), $earliest_msg2];
}
$this->earliest_msg = min($earliest_msg2, $this->earliest_msg);
@@ -758,17 +748,13 @@ protected function getEarliestMsg()
*/
protected function setTopicRequest()
{
- if (Config::$modSettings['totalMessages'] > 100000 && Utils::$context['showing_all_topics'])
- {
+ if (Config::$modSettings['totalMessages'] > 100000 && Utils::$context['showing_all_topics']) {
$this->makeTempTable();
}
- if ($this->have_temp_table)
- {
+ if ($this->have_temp_table) {
$this->getTopicRequestWithTempTable();
- }
- else
- {
+ } else {
$this->getTopicRequestWithoutTempTable();
}
}
@@ -778,15 +764,17 @@ protected function setTopicRequest()
*/
protected function makeTempTable()
{
- Db::$db->query('', '
- DROP TABLE IF EXISTS {db_prefix}log_topics_unread',
- array(
- )
+ Db::$db->query(
+ '',
+ 'DROP TABLE IF EXISTS {db_prefix}log_topics_unread',
+ [
+ ],
);
// Let's copy things out of the log_topics table, to reduce searching.
- $this->have_temp_table = Db::$db->query('', '
- CREATE TEMPORARY TABLE {db_prefix}log_topics_unread (
+ $this->have_temp_table = Db::$db->query(
+ '',
+ 'CREATE TEMPORARY TABLE {db_prefix}log_topics_unread (
PRIMARY KEY (id_topic)
)
SELECT lt.id_topic, lt.id_msg, lt.unwatched
@@ -796,12 +784,12 @@ protected function makeTempTable()
AND t.' . $this->query_this_board . (empty($this->earliest_msg) ? '' : '
AND t.id_last_msg > {int:earliest_msg}') . (Config::$modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved}' : ''),
- array_merge($this->query_parameters, array(
+ array_merge($this->query_parameters, [
'current_member' => User::$me->id,
'earliest_msg' => !empty($this->earliest_msg) ? $this->earliest_msg : 0,
'is_approved' => 1,
'db_error_skip' => true,
- ))
+ ]),
) !== false;
}
@@ -810,8 +798,9 @@ protected function makeTempTable()
*/
protected function getTopicRequestWithTempTable()
{
- $request = Db::$db->query('', '
- SELECT COUNT(*), MIN(t.id_last_msg)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*), MIN(t.id_last_msg)
FROM {db_prefix}topics AS t
LEFT JOIN {db_prefix}log_topics_unread AS lt ON (lt.id_topic = t.id_topic)
LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})
@@ -820,11 +809,11 @@ protected function getTopicRequestWithTempTable()
AND COALESCE(lt.id_msg, lmr.id_msg, 0) < t.id_last_msg' . (Config::$modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved}' : '') . '
AND COALESCE(lt.unwatched, 0) != 1',
- array_merge($this->query_parameters, array(
+ array_merge($this->query_parameters, [
'current_member' => User::$me->id,
'earliest_msg' => !empty($this->earliest_msg) ? $this->earliest_msg : 0,
'is_approved' => 1,
- ))
+ ]),
);
list($num_topics, $min_message) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -832,14 +821,15 @@ protected function getTopicRequestWithTempTable()
$this->num_topics = $num_topics ?? 0;
$this->min_message = $min_message ?? 0;
- if ($this->num_topics == 0)
- {
+ if ($this->num_topics == 0) {
$this->setNoTopics();
+
return;
}
- $this->topic_request = Db::$db->query('substring', '
- SELECT ' . implode(', ', $this->selects) . '
+ $this->topic_request = Db::$db->query(
+ 'substring',
+ 'SELECT ' . implode(', ', $this->selects) . '
FROM {db_prefix}messages AS ms
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ms.id_topic AND t.id_first_msg = ms.id_msg)
INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
@@ -857,14 +847,14 @@ protected function getTopicRequestWithTempTable()
AND COALESCE(lt.unwatched, 0) != 1
ORDER BY {raw:sort}
LIMIT {int:offset}, {int:limit}',
- array_merge($this->query_parameters, array(
+ array_merge($this->query_parameters, [
'current_member' => User::$me->id,
'min_message' => $this->min_message,
'is_approved' => 1,
'sort' => $_REQUEST['sort'] . ($this->ascending ? '' : ' DESC'),
'offset' => Utils::$context['start'],
'limit' => Utils::$context['topics_per_page'],
- ))
+ ]),
);
}
@@ -873,8 +863,9 @@ protected function getTopicRequestWithTempTable()
*/
protected function getTopicRequestWithoutTempTable()
{
- $request = Db::$db->query('', '
- SELECT COUNT(*), MIN(t.id_last_msg)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*), MIN(t.id_last_msg)
FROM {db_prefix}topics AS t' . (!empty($this->have_temp_table) ? '
LEFT JOIN {db_prefix}log_topics_unread AS lt ON (lt.id_topic = t.id_topic)' : '
LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})') . '
@@ -885,12 +876,12 @@ protected function getTopicRequestWithoutTempTable()
AND COALESCE(lt.id_msg, lmr.id_msg, 0) < t.id_last_msg' . (Config::$modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved}' : '') . '
AND COALESCE(lt.unwatched, 0) != 1',
- array_merge($this->query_parameters, array(
+ array_merge($this->query_parameters, [
'current_member' => User::$me->id,
'earliest_msg' => !empty($this->earliest_msg) ? $this->earliest_msg : 0,
'id_msg_last_visit' => $_SESSION['id_msg_last_visit'],
'is_approved' => 1,
- ))
+ ]),
);
list($num_topics, $min_message) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -898,14 +889,15 @@ protected function getTopicRequestWithoutTempTable()
$this->num_topics = $num_topics ?? 0;
$this->min_message = $min_message ?? 0;
- if ($this->num_topics == 0)
- {
+ if ($this->num_topics == 0) {
$this->setNoTopics();
+
return;
}
- $this->topic_request = Db::$db->query('substring', '
- SELECT ' . implode(', ', $this->selects) . '
+ $this->topic_request = Db::$db->query(
+ 'substring',
+ 'SELECT ' . implode(', ', $this->selects) . '
FROM {db_prefix}messages AS ms
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ms.id_topic AND t.id_first_msg = ms.id_msg)
INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
@@ -924,14 +916,14 @@ protected function getTopicRequestWithoutTempTable()
AND COALESCE(lt.unwatched, 0) != 1
ORDER BY {raw:order}
LIMIT {int:offset}, {int:limit}',
- array_merge($this->query_parameters, array(
+ array_merge($this->query_parameters, [
'current_member' => User::$me->id,
'min_message' => $this->min_message,
'is_approved' => 1,
'order' => $_REQUEST['sort'] . ($this->ascending ? '' : ' DESC'),
'offset' => Utils::$context['start'],
'limit' => Utils::$context['topics_per_page'],
- ))
+ ]),
);
}
@@ -940,12 +932,12 @@ protected function getTopicRequestWithoutTempTable()
*/
protected function getTopics()
{
- $topic_ids = array();
+ $topic_ids = [];
- while ($row = Db::$db->fetch_assoc($this->topic_request))
- {
- if ($row['id_poll'] > 0 && Config::$modSettings['pollMode'] == '0')
+ while ($row = Db::$db->fetch_assoc($this->topic_request)) {
+ if ($row['id_poll'] > 0 && Config::$modSettings['pollMode'] == '0') {
continue;
+ }
$topic_ids[] = $row['id_topic'];
@@ -955,12 +947,12 @@ protected function getTopics()
// ... except with a few tweaks.
// Show a link to the board.
- Utils::$context['topics'][$row['id_topic']]['board'] = array(
+ Utils::$context['topics'][$row['id_topic']]['board'] = [
'id' => $row['id_board'],
'name' => $row['bname'],
'href' => Config::$scripturl . '?board=' . $row['id_board'] . '.0',
- 'link' => ' ' . $row['bname'] . ''
- );
+ 'link' => ' ' . $row['bname'] . '',
+ ];
// Adjust the "new" link.
Utils::$context['topics'][$row['id_topic']]['new_href'] = Config::$scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . ';topicseen#new';
@@ -984,25 +976,26 @@ protected function getTopics()
}
Db::$db->free_result($this->topic_request);
- if (!empty(Config::$modSettings['enableParticipation']) && !empty($topic_ids))
- {
- $result = Db::$db->query('', '
- SELECT id_topic
+ if (!empty(Config::$modSettings['enableParticipation']) && !empty($topic_ids)) {
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_topic
FROM {db_prefix}messages
WHERE id_topic IN ({array_int:topic_list})
AND id_member = {int:current_member}
GROUP BY id_topic
LIMIT {int:limit}',
- array(
+ [
'current_member' => User::$me->id,
'topic_list' => $topic_ids,
'limit' => count($topic_ids),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
- if (empty(Utils::$context['topics'][$row['id_topic']]['is_posted_in']))
+
+ while ($row = Db::$db->fetch_assoc($result)) {
+ if (empty(Utils::$context['topics'][$row['id_topic']]['is_posted_in'])) {
Utils::$context['topics'][$row['id_topic']]['is_posted_in'] = true;
+ }
}
Db::$db->free_result($result);
}
@@ -1018,51 +1011,45 @@ protected function getTopics()
protected function buildButtons()
{
// Build the recent button array.
- if ($this->is_topics)
- {
- Utils::$context['recent_buttons'] = array(
- 'markread' => array(
+ if ($this->is_topics) {
+ Utils::$context['recent_buttons'] = [
+ 'markread' => [
'text' => !empty(Utils::$context['no_board_limits']) ? 'mark_as_read' : 'mark_read_short',
'image' => 'markread.png',
'custom' => 'data-confirm="' . Lang::$txt['are_sure_mark_read'] . '"',
'class' => 'you_sure',
'url' => Config::$scripturl . '?action=markasread;sa=' . (!empty(Utils::$context['no_board_limits']) ? 'all' : 'board' . Utils::$context['querystring_board_limits']) . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
- )
- );
+ ],
+ ];
- if (Utils::$context['showCheckboxes'])
- {
- Utils::$context['recent_buttons']['markselectread'] = array(
+ if (Utils::$context['showCheckboxes']) {
+ Utils::$context['recent_buttons']['markselectread'] = [
'text' => 'quick_mod_markread',
'image' => 'markselectedread.png',
'url' => 'javascript:document.quickModForm.submit();',
- );
+ ];
}
- if (!empty(Utils::$context['topics']) && !Utils::$context['showing_all_topics'])
- {
- Utils::$context['recent_buttons']['readall'] = array('text' => 'unread_topics_all', 'image' => 'markreadall.png', 'url' => Config::$scripturl . '?action=unread;all' . Utils::$context['querystring_board_limits'], 'active' => true);
+ if (!empty(Utils::$context['topics']) && !Utils::$context['showing_all_topics']) {
+ Utils::$context['recent_buttons']['readall'] = ['text' => 'unread_topics_all', 'image' => 'markreadall.png', 'url' => Config::$scripturl . '?action=unread;all' . Utils::$context['querystring_board_limits'], 'active' => true];
}
- }
- elseif (!$this->is_topics && isset(Utils::$context['topics_to_mark']))
- {
- Utils::$context['recent_buttons'] = array(
- 'markread' => array(
+ } elseif (!$this->is_topics && isset(Utils::$context['topics_to_mark'])) {
+ Utils::$context['recent_buttons'] = [
+ 'markread' => [
'text' => 'mark_as_read',
'image' => 'markread.png',
'custom' => 'data-confirm="' . Lang::$txt['are_sure_mark_read'] . '"',
'class' => 'you_sure',
'url' => Config::$scripturl . '?action=markasread;sa=unreadreplies;topics=' . Utils::$context['topics_to_mark'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
- )
- );
+ ],
+ ];
- if (Utils::$context['showCheckboxes'])
- {
- Utils::$context['recent_buttons']['markselectread'] = array(
+ if (Utils::$context['showCheckboxes']) {
+ Utils::$context['recent_buttons']['markselectread'] = [
'text' => 'quick_mod_markread',
'image' => 'markselectedread.png',
'url' => 'javascript:document.quickModForm.submit();',
- );
+ ];
}
}
@@ -1072,7 +1059,8 @@ protected function buildButtons()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Unread::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Unread::exportStatic')) {
Unread::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/UnreadReplies.php b/Sources/Actions/UnreadReplies.php
index 939fefe2c8..17bca06ece 100644
--- a/Sources/Actions/UnreadReplies.php
+++ b/Sources/Actions/UnreadReplies.php
@@ -15,12 +15,12 @@
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\Lang;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Finds and retrieves information about replies to the user's posts.
@@ -75,8 +75,9 @@ class UnreadReplies extends Unread
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -113,14 +114,17 @@ protected function __construct()
*/
protected function checkLoadAverage()
{
- if (empty(Utils::$context['load_average']))
+ if (empty(Utils::$context['load_average'])) {
return;
+ }
- if (empty(Config::$modSettings['loadavg_unreadreplies']))
+ if (empty(Config::$modSettings['loadavg_unreadreplies'])) {
return;
+ }
- if (Utils::$context['load_average'] >= Config::$modSettings['loadavg_unreadreplies'])
+ if (Utils::$context['load_average'] >= Config::$modSettings['loadavg_unreadreplies']) {
ErrorHandler::fatalLang('loadavg_unreadreplies_disabled', false);
+ }
}
/**
@@ -128,15 +132,13 @@ protected function checkLoadAverage()
*/
protected function setTopicRequest()
{
- if (Config::$modSettings['totalMessages'] > 100000)
+ if (Config::$modSettings['totalMessages'] > 100000) {
$this->makeTempTable();
+ }
- if ($this->have_temp_table)
- {
+ if ($this->have_temp_table) {
$this->getTopicRequestWithTempTable();
- }
- else
- {
+ } else {
$this->getTopicRequestWithoutTempTable();
}
}
@@ -146,69 +148,72 @@ protected function setTopicRequest()
*/
protected function makeTempTable()
{
- Db::$db->query('', '
- DROP TABLE IF EXISTS {db_prefix}topics_posted_in',
- array(
- )
+ Db::$db->query(
+ '',
+ 'DROP TABLE IF EXISTS {db_prefix}topics_posted_in',
+ [
+ ],
);
- Db::$db->query('', '
- DROP TABLE IF EXISTS {db_prefix}log_topics_posted_in',
- array(
- )
+ Db::$db->query(
+ '',
+ 'DROP TABLE IF EXISTS {db_prefix}log_topics_posted_in',
+ [
+ ],
);
- $sortKey_joins = array(
+ $sortKey_joins = [
'ms.subject' => '
INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)',
'COALESCE(mems.real_name, ms.poster_name)' => '
INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
LEFT JOIN {db_prefix}members AS mems ON (mems.id_member = ms.id_member)',
- );
+ ];
// The main benefit of this temporary table is not that it's faster; it's that it avoids locks later.
- $this->have_temp_table = false !== Db::$db->query('', '
- CREATE TEMPORARY TABLE {db_prefix}topics_posted_in (
+ $this->have_temp_table = false !== Db::$db->query(
+ '',
+ 'CREATE TEMPORARY TABLE {db_prefix}topics_posted_in (
id_topic mediumint(8) unsigned NOT NULL default {string:string_zero},
id_board smallint(5) unsigned NOT NULL default {string:string_zero},
id_last_msg int(10) unsigned NOT NULL default {string:string_zero},
id_msg int(10) unsigned NOT NULL default {string:string_zero},
PRIMARY KEY (id_topic)
)
- SELECT t.id_topic, t.id_board, t.id_last_msg, COALESCE(lmr.id_msg, 0) AS id_msg' . (!in_array($_REQUEST['sort'], array('t.id_last_msg', 't.id_topic')) ? ', ' . $_REQUEST['sort'] . ' AS sort_key' : '') . '
+ SELECT t.id_topic, t.id_board, t.id_last_msg, COALESCE(lmr.id_msg, 0) AS id_msg' . (!in_array($_REQUEST['sort'], ['t.id_last_msg', 't.id_topic']) ? ', ' . $_REQUEST['sort'] . ' AS sort_key' : '') . '
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
LEFT JOIN {db_prefix}log_topics_unread AS lt ON (lt.id_topic = t.id_topic)
- LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})' . (isset($sortKey_joins[$_REQUEST['sort']]) ? $sortKey_joins[$_REQUEST['sort']] : '') . '
+ LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})' . ($sortKey_joins[$_REQUEST['sort']] ?? '') . '
WHERE m.id_member = {int:current_member}' . (!empty(Board::$info->id) ? '
AND t.id_board = {int:current_board}' : '') . (Config::$modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved}' : '') . '
AND COALESCE(lt.unwatched, 0) != 1
GROUP BY m.id_topic',
- array(
+ [
'current_board' => Board::$info->id,
'current_member' => User::$me->id,
'is_approved' => 1,
'string_zero' => '0',
'db_error_skip' => true,
- )
+ ],
);
// If that worked, create a sample of the log_topics table too.
- if ($this->have_temp_table)
- {
- $this->have_temp_table = false !== Db::$db->query('', '
- CREATE TEMPORARY TABLE {db_prefix}log_topics_posted_in (
+ if ($this->have_temp_table) {
+ $this->have_temp_table = false !== Db::$db->query(
+ '',
+ 'CREATE TEMPORARY TABLE {db_prefix}log_topics_posted_in (
PRIMARY KEY (id_topic)
)
SELECT lt.id_topic, lt.id_msg
FROM {db_prefix}log_topics AS lt
INNER JOIN {db_prefix}topics_posted_in AS pi ON (pi.id_topic = lt.id_topic)
WHERE lt.id_member = {int:current_member}',
- array(
+ [
'current_member' => User::$me->id,
'db_error_skip' => true,
- )
+ ],
);
}
}
@@ -218,54 +223,57 @@ protected function makeTempTable()
*/
protected function getTopicRequestWithTempTable()
{
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}topics_posted_in AS pi
LEFT JOIN {db_prefix}log_topics_posted_in AS lt ON (lt.id_topic = pi.id_topic)
WHERE pi.' . $this->query_this_board . '
AND COALESCE(lt.id_msg, pi.id_msg) < pi.id_last_msg',
- array_merge($this->query_parameters, array(
- ))
+ array_merge($this->query_parameters, [
+ ]),
);
list($this->num_topics) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- if ($this->num_topics == 0)
- {
+ if ($this->num_topics == 0) {
$this->setNoTopics();
+
return;
}
- $topics = array();
- $request = Db::$db->query('', '
- SELECT t.id_topic
+ $topics = [];
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_topic
FROM {db_prefix}topics_posted_in AS t
LEFT JOIN {db_prefix}log_topics_posted_in AS lt ON (lt.id_topic = t.id_topic)
WHERE t.' . $this->query_this_board . '
AND COALESCE(lt.id_msg, t.id_msg) < t.id_last_msg
ORDER BY {raw:order}
LIMIT {int:offset}, {int:limit}',
- array_merge($this->query_parameters, array(
- 'order' => (in_array($_REQUEST['sort'], array('t.id_last_msg', 't.id_topic')) ? $_REQUEST['sort'] : 't.sort_key') . ($this->ascending ? '' : ' DESC'),
+ array_merge($this->query_parameters, [
+ 'order' => (in_array($_REQUEST['sort'], ['t.id_last_msg', 't.id_topic']) ? $_REQUEST['sort'] : 't.sort_key') . ($this->ascending ? '' : ' DESC'),
'offset' => Utils::$context['start'],
'limit' => Utils::$context['topics_per_page'],
- ))
+ ]),
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$topics[] = $row['id_topic'];
}
Db::$db->free_result($request);
// Sanity... where have you gone?
- if (empty($topics))
- {
+ if (empty($topics)) {
$this->setNoTopics();
+
return;
}
- $this->topic_request = Db::$db->query('substring', '
- SELECT ' . implode(', ', $this->selects) . '
+ $this->topic_request = Db::$db->query(
+ 'substring',
+ 'SELECT ' . implode(', ', $this->selects) . '
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS ms ON (ms.id_topic = t.id_topic AND ms.id_msg = t.id_first_msg)
INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
@@ -279,12 +287,12 @@ protected function getTopicRequestWithTempTable()
WHERE t.id_topic IN ({array_int:topic_list})
ORDER BY {raw:sort}' . ($this->ascending ? '' : ' DESC') . '
LIMIT {int:limit}',
- array(
+ [
'current_member' => User::$me->id,
'topic_list' => $topics,
'sort' => $_REQUEST['sort'],
'limit' => count($topics),
- )
+ ],
);
}
@@ -293,8 +301,9 @@ protected function getTopicRequestWithTempTable()
*/
protected function getTopicRequestWithoutTempTable()
{
- $request = Db::$db->query('unread_fetch_topic_count', '
- SELECT COUNT(DISTINCT t.id_topic), MIN(t.id_last_msg)
+ $request = Db::$db->query(
+ 'unread_fetch_topic_count',
+ 'SELECT COUNT(DISTINCT t.id_topic), MIN(t.id_last_msg)
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_topic = t.id_topic)
LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
@@ -304,10 +313,10 @@ protected function getTopicRequestWithoutTempTable()
AND COALESCE(lt.id_msg, lmr.id_msg, 0) < t.id_last_msg' . (Config::$modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved}' : '') . '
AND COALESCE(lt.unwatched, 0) != 1',
- array_merge($this->query_parameters, array(
+ array_merge($this->query_parameters, [
'current_member' => User::$me->id,
'is_approved' => 1,
- ))
+ ]),
);
list($num_topics, $min_message) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -315,16 +324,17 @@ protected function getTopicRequestWithoutTempTable()
$this->num_topics = $num_topics ?? 0;
$this->min_message = $min_message ?? 0;
- if ($this->num_topics == 0)
- {
+ if ($this->num_topics == 0) {
$this->setNoTopics();
+
return;
}
- $topics = array();
+ $topics = [];
- $request = Db::$db->query('', '
- SELECT DISTINCT t.id_topic,' . $_REQUEST['sort'] . '
+ $request = Db::$db->query(
+ '',
+ 'SELECT DISTINCT t.id_topic,' . $_REQUEST['sort'] . '
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_topic = t.id_topic AND m.id_member = {int:current_member})' . (strpos($_REQUEST['sort'], 'ms.') === false ? '' : '
INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)') . (strpos($_REQUEST['sort'], 'mems.') === false ? '' : '
@@ -338,7 +348,7 @@ protected function getTopicRequestWithoutTempTable()
AND COALESCE(lt.unwatched, 0) != 1
ORDER BY {raw:order}
LIMIT {int:offset}, {int:limit}',
- array_merge($this->query_parameters, array(
+ array_merge($this->query_parameters, [
'current_member' => User::$me->id,
'min_message' => (int) $this->min_message,
'is_approved' => 1,
@@ -346,23 +356,24 @@ protected function getTopicRequestWithoutTempTable()
'offset' => Utils::$context['start'],
'limit' => Utils::$context['topics_per_page'],
'sort' => $_REQUEST['sort'],
- ))
+ ]),
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$topics[] = $row['id_topic'];
}
Db::$db->free_result($request);
// Sanity... where have you gone?
- if (empty($topics))
- {
+ if (empty($topics)) {
$this->setNoTopics();
+
return;
}
- $this->topic_request = Db::$db->query('substring', '
- SELECT ' . implode(', ', $this->selects) . '
+ $this->topic_request = Db::$db->query(
+ 'substring',
+ 'SELECT ' . implode(', ', $this->selects) . '
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS ms ON (ms.id_topic = t.id_topic AND ms.id_msg = t.id_first_msg)
INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
@@ -376,15 +387,14 @@ protected function getTopicRequestWithoutTempTable()
WHERE t.id_topic IN ({array_int:topic_list})
ORDER BY {raw:sort}' . ($this->ascending ? '' : ' DESC') . '
LIMIT {int:limit}',
- array(
+ [
'current_member' => User::$me->id,
'topic_list' => $topics,
'sort' => $_REQUEST['sort'],
'limit' => count($topics),
- )
+ ],
);
}
-
}
?>
\ No newline at end of file
diff --git a/Sources/Actions/VerificationCode.php b/Sources/Actions/VerificationCode.php
index c8e5b8900f..a99773a91d 100644
--- a/Sources/Actions/VerificationCode.php
+++ b/Sources/Actions/VerificationCode.php
@@ -14,13 +14,12 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
+use SMF\Cache\CacheApi;
use SMF\Config;
use SMF\Lang;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
/**
* Shows the verification code or let it be heard.
@@ -36,12 +35,11 @@ class VerificationCode implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'VerificationCode',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -83,52 +81,48 @@ class VerificationCode implements ActionInterface
public function execute(): void
{
// Somehow no code was generated or the session was lost.
- if (empty($this->code))
- {
+ if (empty($this->code)) {
header('content-type: image/gif');
+
die("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B");
}
+
// Show a window that will play the verification code.
- elseif (isset($_REQUEST['sound']))
- {
+ if (isset($_REQUEST['sound'])) {
Lang::load('Login');
Theme::loadTemplate('Register');
Utils::$context['verification_sound_href'] = Config::$scripturl . '?action=verificationcode;rand=' . Utils::randomBytes(16) . ($this->verification_id ? ';vid=' . $this->verification_id : '') . ';format=.wav';
Utils::$context['sub_template'] = 'verification_sound';
- Utils::$context['template_layers'] = array();
+ Utils::$context['template_layers'] = [];
Utils::obExit();
}
// If we have GD, try the nice code.
- elseif (empty($_REQUEST['format']))
- {
- if (extension_loaded('gd') && !$this->showCodeImage($this->code))
- {
+ elseif (empty($_REQUEST['format'])) {
+ if (extension_loaded('gd') && !$this->showCodeImage($this->code)) {
Utils::sendHttpStatus(400);
}
// Otherwise just show a pre-defined letter.
- elseif (isset($_REQUEST['letter']))
- {
+ elseif (isset($_REQUEST['letter'])) {
$_REQUEST['letter'] = (int) $_REQUEST['letter'];
- if ($_REQUEST['letter'] > 0 && $_REQUEST['letter'] <= strlen($this->code) && !$this->showLetterImage(strtolower($this->code[$_REQUEST['letter'] - 1])))
- {
+ if ($_REQUEST['letter'] > 0 && $_REQUEST['letter'] <= strlen($this->code) && !$this->showLetterImage(strtolower($this->code[$_REQUEST['letter'] - 1]))) {
header('content-type: image/gif');
+
die("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B");
}
}
// You must be up to no good.
- else
- {
+ else {
header('content-type: image/gif');
+
die("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B");
}
- }
- elseif ($_REQUEST['format'] === '.wav')
- {
- if (!$this->createWaveFile($this->code))
+ } elseif ($_REQUEST['format'] === '.wav') {
+ if (!$this->createWaveFile($this->code)) {
Utils::sendHttpStatus(400);
+ }
}
// We all die one day...
@@ -146,8 +140,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;
}
@@ -169,10 +164,9 @@ public static function call(): void
*/
protected function __construct()
{
- $this->verification_id = isset($_GET['vid']) ? $_GET['vid'] : '';
-
- $this->code = $this->verification_id && isset($_SESSION[$this->verification_id . '_vv']) ? $_SESSION[$this->verification_id . '_vv']['code'] : (isset($_SESSION['visual_verification_code']) ? $_SESSION['visual_verification_code'] : '');
+ $this->verification_id = $_GET['vid'] ?? '';
+ $this->code = $this->verification_id && isset($_SESSION[$this->verification_id . '_vv']) ? $_SESSION[$this->verification_id . '_vv']['code'] : ($_SESSION['visual_verification_code'] ?? '');
}
/**
@@ -187,8 +181,9 @@ protected function __construct()
*/
protected function showCodeImage($code): bool
{
- if (!extension_loaded('gd'))
+ if (!extension_loaded('gd')) {
return false;
+ }
// Note: The higher the value of visual_verification_type the harder the verification is - from 0 as disabled through to 4 as "Very hard".
@@ -196,8 +191,9 @@ protected function showCodeImage($code): bool
$image_type = Config::$modSettings['visual_verification_type'];
// Special case to allow the admin center to show samples.
- if (User::$me->is_admin && isset($_GET['type']))
+ if (User::$me->is_admin && isset($_GET['type'])) {
$image_type = (int) $_GET['type'];
+ }
// Some quick references for what we do.
// Do we show no, low or high noise?
@@ -243,87 +239,75 @@ protected function showCodeImage($code): bool
$character_spacing = 1;
// What color is the background - generally white unless we're on "hard".
- if ($simple_bg_color)
- {
- $background_color = array(255, 255, 255);
- }
- else
- {
- $background_color = isset(Theme::$current->settings['verification_background']) ? Theme::$current->settings['verification_background'] : array(236, 237, 243);
+ if ($simple_bg_color) {
+ $background_color = [255, 255, 255];
+ } else {
+ $background_color = Theme::$current->settings['verification_background'] ?? [236, 237, 243];
}
// The color of the characters shown (red, green, blue).
- if ($simple_fg_color)
- {
- $foreground_color = array(0, 0, 0);
- }
- else
- {
- $foreground_color = array(64, 101, 136);
+ if ($simple_fg_color) {
+ $foreground_color = [0, 0, 0];
+ } else {
+ $foreground_color = [64, 101, 136];
// Has the theme author requested a custom color?
- if (isset(Theme::$current->settings['verification_foreground']))
+ if (isset(Theme::$current->settings['verification_foreground'])) {
$foreground_color = Theme::$current->settings['verification_foreground'];
+ }
}
- if (!is_dir(Theme::$current->settings['default_theme_dir'] . '/fonts'))
+ if (!is_dir(Theme::$current->settings['default_theme_dir'] . '/fonts')) {
return false;
+ }
// Get a list of the available fonts.
- $font_list = array();
- $ttfont_list = array();
+ $font_list = [];
+ $ttfont_list = [];
$endian = unpack('v', pack('S', 0x00FF)) === 0x00FF;
$font_dir = dir(Theme::$current->settings['default_theme_dir'] . '/fonts');
- while ($entry = $font_dir->read())
- {
- if (preg_match('~^(.+)\.gdf$~', $entry, $matches) === 1)
- {
- if ($endian ^ (strpos($entry, '_end.gdf') === false))
+ while ($entry = $font_dir->read()) {
+ if (preg_match('~^(.+)\.gdf$~', $entry, $matches) === 1) {
+ if ($endian ^ (strpos($entry, '_end.gdf') === false)) {
$font_list[] = $entry;
- }
- elseif (preg_match('~^(.+)\.ttf$~', $entry, $matches) === 1)
- {
+ }
+ } elseif (preg_match('~^(.+)\.ttf$~', $entry, $matches) === 1) {
$ttfont_list[] = $entry;
}
}
- if (empty($font_list))
+ if (empty($font_list)) {
return false;
+ }
// For non-hard things don't even change fonts.
- if (!$vary_fonts)
- {
- $font_list = array($font_list[0]);
+ if (!$vary_fonts) {
+ $font_list = [$font_list[0]];
- if (in_array('AnonymousPro.ttf', $ttfont_list))
- {
- $ttfont_list = array('AnonymousPro.ttf');
- }
- else
- {
- $ttfont_list = empty($ttfont_list) ? array() : array($ttfont_list[0]);
+ if (in_array('AnonymousPro.ttf', $ttfont_list)) {
+ $ttfont_list = ['AnonymousPro.ttf'];
+ } else {
+ $ttfont_list = empty($ttfont_list) ? [] : [$ttfont_list[0]];
}
}
// Create a list of characters to be shown.
- $characters = array();
- $loaded_fonts = array();
+ $characters = [];
+ $loaded_fonts = [];
- for ($i = 0; $i < strlen($code); $i++)
- {
- $characters[$i] = array(
+ for ($i = 0; $i < strlen($code); $i++) {
+ $characters[$i] = [
'id' => $code[$i],
'font' => array_rand($font_list),
- );
+ ];
$loaded_fonts[$characters[$i]['font']] = null;
}
// Load all fonts and determine the maximum font height.
- foreach ($loaded_fonts as $font_index => $dummy)
- {
+ foreach ($loaded_fonts as $font_index => $dummy) {
$loaded_fonts[$font_index] = imageloadfont(Theme::$current->settings['default_theme_dir'] . '/fonts/' . $font_list[$font_index]);
}
@@ -333,8 +317,7 @@ protected function showCodeImage($code): bool
$total_width = $character_spacing * strlen($code) + $extra;
$max_height = 0;
- foreach ($characters as $char_index => $character)
- {
+ foreach ($characters as $char_index => $character) {
$characters[$char_index]['width'] = imagefontwidth($loaded_fonts[$character['font']]);
$characters[$char_index]['height'] = imagefontheight($loaded_fonts[$character['font']]);
@@ -350,7 +333,7 @@ protected function showCodeImage($code): bool
$code_image,
$background_color[0],
$background_color[1],
- $background_color[2]
+ $background_color[2],
);
imagefilledrectangle(
@@ -359,12 +342,11 @@ protected function showCodeImage($code): bool
0,
$total_width - 1,
$max_height - 1,
- $bg_color
+ $bg_color,
);
// Randomize the foreground color a little.
- for ($i = 0; $i < 3; $i++)
- {
+ for ($i = 0; $i < 3; $i++) {
$foreground_color[$i] = Utils::randomInt(max($foreground_color[$i] - 3, 0), min($foreground_color[$i] + 3, 255));
}
@@ -372,18 +354,14 @@ protected function showCodeImage($code): bool
$code_image,
$foreground_color[0],
$foreground_color[1],
- $foreground_color[2]
+ $foreground_color[2],
);
// Color for the dots.
- for ($i = 0; $i < 3; $i++)
- {
- if ($background_color[$i] < $foreground_color[$i])
- {
+ for ($i = 0; $i < 3; $i++) {
+ if ($background_color[$i] < $foreground_color[$i]) {
$dotbgcolor[$i] = Utils::randomInt(0, max($foreground_color[$i] - 20, 0));
- }
- else
- {
+ } else {
$dotbgcolor[$i] = Utils::randomInt(min($foreground_color[$i] + 20, 255), 255);
}
}
@@ -392,14 +370,12 @@ protected function showCodeImage($code): bool
$code_image,
$dotbgcolor[0],
$dotbgcolor[1],
- $dotbgcolor[2]
+ $dotbgcolor[2],
);
// Some squares/rectangles for new extreme level
- if ($noise_type == 'extreme')
- {
- for ($i = 0; $i < Utils::randomInt(1, 5); $i++)
- {
+ if ($noise_type == 'extreme') {
+ for ($i = 0; $i < Utils::randomInt(1, 5); $i++) {
$x1 = Utils::randomInt(0, $total_width / 4);
$x2 = $x1 + round(rand($total_width / 4, $total_width));
$y1 = Utils::randomInt(0, $max_height);
@@ -411,74 +387,65 @@ protected function showCodeImage($code): bool
$y1,
$x2,
$y2,
- Utils::randomInt(0, 1) ? $fg_color : $randomness_color
+ Utils::randomInt(0, 1) ? $fg_color : $randomness_color,
);
}
}
// Fill in the characters.
- if (!$disable_chars)
- {
+ if (!$disable_chars) {
$cur_x = 0;
- foreach ($characters as $char_index => $character)
- {
+ foreach ($characters as $char_index => $character) {
// Can we use true type fonts?
$can_do_ttf = function_exists('imagettftext');
// How much rotation will we give?
- if ($rotation_type == 'none')
- {
+ if ($rotation_type == 'none') {
$angle = 0;
- }
- else
- {
+ } else {
$angle = Utils::randomInt(-100, 100) / ($rotation_type == 'high' ? 6 : 10);
}
// What color shall we do it?
- if ($font_color_type == 'cyclic')
- {
+ if ($font_color_type == 'cyclic') {
// Here we'll pick from a set of acceptance types.
- $colors = array(
- array(10, 120, 95),
- array(46, 81, 29),
- array(4, 22, 154),
- array(131, 9, 130),
- array(0, 0, 0),
- array(143, 39, 31),
- );
-
- if (!isset($last_index))
+ $colors = [
+ [10, 120, 95],
+ [46, 81, 29],
+ [4, 22, 154],
+ [131, 9, 130],
+ [0, 0, 0],
+ [143, 39, 31],
+ ];
+
+ if (!isset($last_index)) {
$last_index = -1;
+ }
$new_index = $last_index;
- while ($last_index == $new_index)
+ while ($last_index == $new_index) {
$new_index = Utils::randomInt(0, count($colors) - 1);
+ }
$char_fg_color = $colors[$new_index];
$last_index = $new_index;
- }
- elseif ($font_color_type == 'random')
- {
- $char_fg_color = array(
+ } elseif ($font_color_type == 'random') {
+ $char_fg_color = [
Utils::randomInt(max($foreground_color[0] - 2, 0), $foreground_color[0]),
Utils::randomInt(max($foreground_color[1] - 2, 0), $foreground_color[1]),
Utils::randomInt(max($foreground_color[2] - 2, 0), $foreground_color[2]),
- );
- }
- else
- {
- $char_fg_color = array(
+ ];
+ } else {
+ $char_fg_color = [
$foreground_color[0],
$foreground_color[1],
$foreground_color[2],
- );
+ ];
}
- if (!empty($can_do_ttf))
- {
+ if (!empty($can_do_ttf)) {
$font_size = $font_size_random ? Utils::randomInt(17, 19) : 18;
// Work out the sizes - also fix the character width cause TTF not quite so wide!
@@ -486,31 +453,27 @@ protected function showCodeImage($code): bool
$font_y = $max_height - ($font_vert_pos == 'vrandom' ? Utils::randomInt(2, 8) : ($font_vert_pos == 'random' ? Utils::randomInt(3, 5) : 5));
// What font face?
- if (!empty($ttfont_list))
- {
+ if (!empty($ttfont_list)) {
$fontface = Theme::$current->settings['default_theme_dir'] . '/fonts/' . $ttfont_list[Utils::randomInt(0, count($ttfont_list) - 1)];
}
// What color are we to do it in?
$is_reverse = $show_reverse_chars ? Utils::randomInt(0, 1) : false;
- if (function_exists('imagecolorallocatealpha') && $font_transparent)
- {
+ if (function_exists('imagecolorallocatealpha') && $font_transparent) {
$char_color = imagecolorallocatealpha(
$code_image,
$char_fg_color[0],
$char_fg_color[1],
$char_fg_color[2],
- 50
+ 50,
);
- }
- else
- {
+ } else {
$char_color = imagecolorallocate(
$code_image,
$char_fg_color[0],
$char_fg_color[1],
- $char_fg_color[2]
+ $char_fg_color[2],
);
}
@@ -522,15 +485,12 @@ protected function showCodeImage($code): bool
$font_y,
$char_color,
$fontface,
- $character['id']
+ $character['id'],
);
- if (empty($fontcord))
- {
+ if (empty($fontcord)) {
$can_do_ttf = false;
- }
- elseif ($is_reverse)
- {
+ } elseif ($is_reverse) {
imagefilledpolygon($code_image, $fontcord, 4, $fg_color);
// Put the character back!
@@ -542,29 +502,28 @@ protected function showCodeImage($code): bool
$font_y,
$randomness_color,
$fontface,
- $character['id']
+ $character['id'],
);
}
- if ($can_do_ttf)
+ if ($can_do_ttf) {
$cur_x = max($fontcord[2], $fontcord[4]) + ($angle == 0 ? 0 : 3);
+ }
}
- if (!$can_do_ttf)
- {
+ if (!$can_do_ttf) {
// Rotating the characters a little...
- if (function_exists('imagerotate'))
- {
+ if (function_exists('imagerotate')) {
$char_image = imagecreatetruecolor(
$character['width'],
- $character['height']
+ $character['height'],
);
$char_bgcolor = imagecolorallocate(
$char_image,
$background_color[0],
$background_color[1],
- $background_color[2]
+ $background_color[2],
);
imagefilledrectangle(
@@ -573,7 +532,7 @@ protected function showCodeImage($code): bool
0,
$character['width'] - 1,
$character['height'] - 1,
- $char_bgcolor
+ $char_bgcolor,
);
imagechar(
@@ -586,14 +545,14 @@ protected function showCodeImage($code): bool
$char_image,
$char_fg_color[0],
$char_fg_color[1],
- $char_fg_color[2]
- )
+ $char_fg_color[2],
+ ),
);
$rotated_char = imagerotate(
$char_image,
Utils::randomInt(-100, 100) / 10,
- $char_bgcolor
+ $char_bgcolor,
);
imagecopy(
@@ -604,13 +563,12 @@ protected function showCodeImage($code): bool
0,
0,
$character['width'],
- $character['height']
+ $character['height'],
);
}
// Sorry, no rotation available.
- else
- {
+ else {
imagechar(
$code_image,
$loaded_fonts[$character['font']],
@@ -621,8 +579,8 @@ protected function showCodeImage($code): bool
$code_image,
$char_fg_color[0],
$char_fg_color[1],
- $char_fg_color[2]
- )
+ $char_fg_color[2],
+ ),
);
}
@@ -631,46 +589,39 @@ protected function showCodeImage($code): bool
}
}
// If disabled just show a cross.
- else
- {
+ else {
imageline($code_image, 0, 0, $total_width, $max_height, $fg_color);
imageline($code_image, 0, $max_height, $total_width, 0, $fg_color);
}
// Make the background color transparent on the hard image.
- if (!$simple_bg_color)
+ if (!$simple_bg_color) {
imagecolortransparent($code_image, $bg_color);
+ }
- if ($has_border)
+ if ($has_border) {
imagerectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $fg_color);
+ }
// Add some noise to the background?
- if ($noise_type != 'none')
- {
- for ($i = Utils::randomInt(0, 2); $i < $max_height; $i += Utils::randomInt(1, 2))
- {
- for ($j = Utils::randomInt(0, 10); $j < $total_width; $j += Utils::randomInt(1, 10))
- {
+ if ($noise_type != 'none') {
+ for ($i = Utils::randomInt(0, 2); $i < $max_height; $i += Utils::randomInt(1, 2)) {
+ for ($j = Utils::randomInt(0, 10); $j < $total_width; $j += Utils::randomInt(1, 10)) {
imagesetpixel($code_image, $j, $i, Utils::randomInt(0, 1) ? $fg_color : $randomness_color);
}
}
// Put in some lines too?
- if ($noise_type != 'extreme')
- {
+ if ($noise_type != 'extreme') {
$num_lines = $noise_type == 'high' ? Utils::randomInt(3, 7) : Utils::randomInt(2, 5);
- for ($i = 0; $i < $num_lines; $i++)
- {
- if (Utils::randomInt(0, 1))
- {
+ for ($i = 0; $i < $num_lines; $i++) {
+ if (Utils::randomInt(0, 1)) {
$x1 = Utils::randomInt(0, $total_width);
$x2 = Utils::randomInt(0, $total_width);
$y1 = 0;
$y2 = $max_height;
- }
- else
- {
+ } else {
$y1 = Utils::randomInt(0, $max_height);
$y2 = Utils::randomInt(0, $max_height);
$x1 = 0;
@@ -685,17 +636,14 @@ protected function showCodeImage($code): bool
$y1,
$x2,
$y2,
- Utils::randomInt(0, 1) ? $fg_color : $randomness_color
+ Utils::randomInt(0, 1) ? $fg_color : $randomness_color,
);
}
- }
- else
- {
+ } else {
// Put in some ellipse
$num_ellipse = $noise_type == 'extreme' ? Utils::randomInt(6, 12) : Utils::randomInt(2, 6);
- for ($i = 0; $i < $num_ellipse; $i++)
- {
+ for ($i = 0; $i < $num_ellipse; $i++) {
$x1 = round(rand(($total_width / 4) * -1, $total_width + ($total_width / 4)));
$x2 = round(rand($total_width / 2, 2 * $total_width));
$y1 = round(rand(($max_height / 4) * -1, $max_height + ($max_height / 4)));
@@ -707,20 +655,17 @@ protected function showCodeImage($code): bool
$y1,
$x2,
$y2,
- Utils::randomInt(0, 1) ? $fg_color : $randomness_color
+ Utils::randomInt(0, 1) ? $fg_color : $randomness_color,
);
}
}
}
// Show the image.
- if (function_exists('imagegif'))
- {
+ if (function_exists('imagegif')) {
header('content-type: image/gif');
imagegif($code_image);
- }
- else
- {
+ } else {
header('content-type: image/png');
imagepng($code_image);
}
@@ -740,41 +685,40 @@ protected function showCodeImage($code): bool
*/
protected function showLetterImage($letter): bool
{
- if (!is_dir(Theme::$current->settings['default_theme_dir'] . '/fonts'))
+ if (!is_dir(Theme::$current->settings['default_theme_dir'] . '/fonts')) {
return false;
+ }
// Get a list of the available font directories.
$font_dir = dir(Theme::$current->settings['default_theme_dir'] . '/fonts');
- $font_list = array();
+ $font_list = [];
- while ($entry = $font_dir->read())
- {
+ while ($entry = $font_dir->read()) {
if (
$entry[0] !== '.'
&& is_dir(Theme::$current->settings['default_theme_dir'] . '/fonts/' . $entry)
&& file_exists(Theme::$current->settings['default_theme_dir'] . '/fonts/' . $entry . '.gdf')
- )
- {
+ ) {
$font_list[] = $entry;
}
}
- if (empty($font_list))
+ if (empty($font_list)) {
return false;
+ }
// Pick a random font.
$random_font = $font_list[array_rand($font_list)];
// Check if the given letter exists.
- if (!file_exists(Theme::$current->settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . strtoupper($letter) . '.png'))
- {
+ if (!file_exists(Theme::$current->settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . strtoupper($letter) . '.png')) {
return false;
}
// Include it!
header('content-type: image/png');
- include(Theme::$current->settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . strtoupper($letter) . '.png');
+ include Theme::$current->settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . strtoupper($letter) . '.png';
// Nothing more to come.
die();
@@ -786,14 +730,14 @@ protected function showLetterImage($letter): bool
* Used by VerificationCode() (Register.php).
*
* @param string $word
- * @return boolean false on failure
+ * @return bool false on failure
*/
protected function createWaveFile($word)
{
// Allow max 2 requests per 20 seconds.
- if (($ip = CacheApi::get('wave_file/' . User::$me->ip, 20)) > 2 || ($ip2 = CacheApi::get('wave_file/' . User::$me->ip2, 20)) > 2)
- {
+ if (($ip = CacheApi::get('wave_file/' . User::$me->ip, 20)) > 2 || ($ip2 = CacheApi::get('wave_file/' . User::$me->ip2, 20)) > 2) {
Utils::sendHttpStatus(400);
+
die();
}
@@ -805,18 +749,15 @@ protected function createWaveFile($word)
mt_srand(end($tmp));
// Try to see if there's a sound font in the user's language.
- if (file_exists(Theme::$current->settings['default_theme_dir'] . '/fonts/sound/a.' . User::$me->language . '.wav'))
- {
+ if (file_exists(Theme::$current->settings['default_theme_dir'] . '/fonts/sound/a.' . User::$me->language . '.wav')) {
$sound_language = User::$me->language;
}
// English should be there.
- elseif (file_exists(Theme::$current->settings['default_theme_dir'] . '/fonts/sound/a.english.wav'))
- {
+ elseif (file_exists(Theme::$current->settings['default_theme_dir'] . '/fonts/sound/a.english.wav')) {
$sound_language = 'english';
}
// Guess not...
- else
- {
+ else {
return false;
}
@@ -827,30 +768,27 @@ protected function createWaveFile($word)
// Loop through all letters of the word $word.
$sound_word = '';
- for ($i = 0; $i < count($chars); $i++)
- {
+
+ for ($i = 0; $i < count($chars); $i++) {
$sound_letter = implode('', file(Theme::$current->settings['default_theme_dir'] . '/fonts/sound/' . $chars[$i] . '.' . $sound_language . '.wav'));
- if (strpos($sound_letter, 'data') === false)
+ if (strpos($sound_letter, 'data') === false) {
return false;
+ }
$sound_letter = substr($sound_letter, strpos($sound_letter, 'data') + 8);
- switch ($chars[$i] === 's' ? 0 : mt_rand(0, 2))
- {
- case 0 :
- for ($j = 0, $n = strlen($sound_letter); $j < $n; $j++)
- {
- for ($k = 0, $m = round(mt_rand(15, 25) / 10); $k < $m; $k++)
- {
+ switch ($chars[$i] === 's' ? 0 : mt_rand(0, 2)) {
+ case 0:
+ for ($j = 0, $n = strlen($sound_letter); $j < $n; $j++) {
+ for ($k = 0, $m = round(mt_rand(15, 25) / 10); $k < $m; $k++) {
$sound_word .= $chars[$i] === 's' ? $sound_letter[$j] : chr(mt_rand(max(ord($sound_letter[$j]) - 1, 0x00), min(ord($sound_letter[$j]) + 1, 0xFF)));
}
}
break;
case 1:
- for ($j = 0, $n = strlen($sound_letter) - 1; $j < $n; $j += 2)
- {
+ for ($j = 0, $n = strlen($sound_letter) - 1; $j < $n; $j += 2) {
$sound_word .= (mt_rand(0, 3) == 0 ? '' : $sound_letter[$j]) . (mt_rand(0, 3) === 0 ? $sound_letter[$j + 1] : $sound_letter[$j]) . (mt_rand(0, 3) === 0 ? $sound_letter[$j] : $sound_letter[$j + 1]) . $sound_letter[$j + 1] . (mt_rand(0, 3) == 0 ? $sound_letter[$j + 1] : '');
}
$sound_word .= str_repeat($sound_letter[$n], 2);
@@ -858,13 +796,13 @@ protected function createWaveFile($word)
case 2:
$shift = 0;
- for ($j = 0, $n = strlen($sound_letter); $j < $n; $j++)
- {
- if (mt_rand(0, 10) === 0)
+
+ for ($j = 0, $n = strlen($sound_letter); $j < $n; $j++) {
+ if (mt_rand(0, 10) === 0) {
$shift += mt_rand(-3, 3);
+ }
- for ($k = 0, $m = round(mt_rand(15, 25) / 10); $k < $m; $k++)
- {
+ for ($k = 0, $m = round(mt_rand(15, 25) / 10); $k < $m; $k++) {
$sound_word .= chr(min(max(ord($sound_letter[$j]) + $shift, 0x00), 0xFF));
}
}
@@ -891,22 +829,19 @@ protected function createWaveFile($word)
header('content-type: audio/x-wav');
header('expires: ' . gmdate('D, d M Y H:i:s', time() + 525600 * 60) . ' GMT');
- if (isset($_SERVER['HTTP_RANGE']))
- {
- list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
- list($range) = explode(",", $range, 2);
- list($range, $range_end) = explode("-", $range);
+ if (isset($_SERVER['HTTP_RANGE'])) {
+ list($a, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
+ list($range) = explode(',', $range, 2);
+ list($range, $range_end) = explode('-', $range);
$range = intval($range);
$range_end = !$range_end ? $content_length - 1 : intval($range_end);
$new_length = $range_end - $range + 1;
Utils::sendHttpStatus(206);
- header("content-length: $new_length");
- header("content-range: bytes $range-$range_end/$content_length");
- }
- else
- {
- header("content-length: " . $content_length);
+ header("content-length: {$new_length}");
+ header("content-range: bytes {$range}-{$range_end}/{$content_length}");
+ } else {
+ header('content-length: ' . $content_length);
}
echo pack('nnVnnnnnnnnVVnnnnV', 0x5249, 0x4646, $file_size, 0x5741, 0x5645, 0x666D, 0x7420, 0x1000, 0x0000, 0x0100, 0x0100, $sample_rate, $sample_rate, 0x0100, 0x0800, 0x6461, 0x7461, $data_size), $sound_word;
@@ -917,7 +852,8 @@ protected function createWaveFile($word)
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\VerificationCode::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\VerificationCode::exportStatic')) {
VerificationCode::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/ViewQuery.php b/Sources/Actions/ViewQuery.php
index eb6ab75ad9..ce7c8cb3b9 100644
--- a/Sources/Actions/ViewQuery.php
+++ b/Sources/Actions/ViewQuery.php
@@ -14,15 +14,14 @@
namespace SMF\Actions;
use SMF\BackwardCompatibility;
-
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi as Db;
/**
* Provides a way to view database queries. Used for debugging.
@@ -36,12 +35,11 @@ class ViewQuery implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'ViewQuery',
- ),
- );
+ ],
+ ];
/****************************
* Internal static properties
@@ -70,8 +68,7 @@ class ViewQuery implements ActionInterface
public function execute(): void
{
// We should have debug mode enabled, as well as something to display!
- if (!isset(Config::$db_show_debug) || Config::$db_show_debug !== true || !isset($_SESSION['debug']))
- {
+ if (!isset(Config::$db_show_debug) || Config::$db_show_debug !== true || !isset($_SESSION['debug'])) {
ErrorHandler::fatalLang('no_access', false);
}
@@ -79,16 +76,12 @@ public function execute(): void
User::$me->isAllowedTo('admin_forum');
// If we're just hiding/showing, do it now.
- if (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'hide')
- {
+ if (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'hide') {
$_SESSION['view_queries'] = $_SESSION['view_queries'] == 1 ? 0 : 1;
- if (strpos($_SESSION['old_url'], 'action=viewquery') !== false)
- {
+ if (strpos($_SESSION['old_url'], 'action=viewquery') !== false) {
Utils::redirectexit();
- }
- else
- {
+ } else {
Utils::redirectexit($_SESSION['old_url']);
}
}
@@ -120,56 +113,47 @@ public function execute(): void
';
- foreach ($_SESSION['debug'] as $q => $query_data)
- {
+ foreach ($_SESSION['debug'] as $q => $query_data) {
// Fix the indentation....
$query_data['q'] = ltrim(str_replace("\r", '', $query_data['q']), "\n");
$query = explode("\n", $query_data['q']);
$min_indent = 0;
- foreach ($query as $line)
- {
+ foreach ($query as $line) {
preg_match('/^(\t*)/', $line, $temp);
- if (strlen($temp[0]) < $min_indent || $min_indent == 0)
+ if (strlen($temp[0]) < $min_indent || $min_indent == 0) {
$min_indent = strlen($temp[0]);
+ }
}
- foreach ($query as $l => $dummy)
+ foreach ($query as $l => $dummy) {
$query[$l] = substr($dummy, $min_indent);
+ }
$query_data['q'] = implode("\n", $query);
// Make the filenames look a bit better.
- if (isset($query_data['f']))
- {
+ if (isset($query_data['f'])) {
$query_data['f'] = preg_replace('~^' . preg_quote(Config::$boarddir, '~') . '~', '...', $query_data['f']);
}
$is_select_query = substr(trim($query_data['q']), 0, 6) == 'SELECT' || substr(trim($query_data['q']), 0, 4) == 'WITH';
- if ($is_select_query)
- {
+ if ($is_select_query) {
$select = $query_data['q'];
- }
- elseif (preg_match('~^INSERT(?: IGNORE)? INTO \w+(?:\s+\([^)]+\))?\s+(SELECT .+)$~s', trim($query_data['q']), $matches) != 0)
- {
+ } elseif (preg_match('~^INSERT(?: IGNORE)? INTO \w+(?:\s+\([^)]+\))?\s+(SELECT .+)$~s', trim($query_data['q']), $matches) != 0) {
$is_select_query = true;
$select = $matches[1];
- }
- elseif (preg_match('~^CREATE TEMPORARY TABLE .+?(SELECT .+)$~s', trim($query_data['q']), $matches) != 0)
- {
+ } elseif (preg_match('~^CREATE TEMPORARY TABLE .+?(SELECT .+)$~s', trim($query_data['q']), $matches) != 0) {
$is_select_query = true;
$select = $matches[1];
}
// Temporary tables created in earlier queries are not explainable.
- if ($is_select_query)
- {
- foreach (array('log_topics_unread', 'topics_posted_in', 'tmp_log_search_topics', 'tmp_log_search_messages') as $tmp)
- {
- if (strpos($select, $tmp) !== false)
- {
+ if ($is_select_query) {
+ foreach (['log_topics_unread', 'topics_posted_in', 'tmp_log_search_topics', 'tmp_log_search_messages'] as $tmp) {
+ if (strpos($select, $tmp) !== false) {
$is_select_query = false;
break;
}
@@ -182,17 +166,13 @@ public function execute(): void
', nl2br(str_replace("\t", ' ', Utils::htmlspecialchars($query_data['q']))), '
';
- if (!empty($query_data['f']) && !empty($query_data['l']))
- {
+ if (!empty($query_data['f']) && !empty($query_data['l'])) {
echo sprintf(Lang::$txt['debug_query_in_line'], $query_data['f'], $query_data['l']);
}
- if (isset($query_data['s'], $query_data['t']) && isset(Lang::$txt['debug_query_which_took_at']))
- {
+ if (isset($query_data['s'], $query_data['t'], Lang::$txt['debug_query_which_took_at'])) {
echo sprintf(Lang::$txt['debug_query_which_took_at'], round($query_data['t'], 8), round($query_data['s'], 8));
- }
- else
- {
+ } else {
echo sprintf(Lang::$txt['debug_query_which_took'], round($query_data['t'], 8));
}
@@ -200,20 +180,20 @@ public function execute(): void
';
// Explain the query.
- if ($query_id == $q && $is_select_query)
- {
- $result = Db::$db->query('', '
- EXPLAIN ' . (Db::$db->title === POSTGRE_TITLE ? 'ANALYZE ' : '') . $select,
- array(
- )
+ if ($query_id == $q && $is_select_query) {
+ $result = Db::$db->query(
+ '',
+ 'EXPLAIN ' . (Db::$db->title === POSTGRE_TITLE ? 'ANALYZE ' : '') . $select,
+ [
+ ],
);
- if ($result === false)
- {
+ if ($result === false) {
echo '
';
+
continue;
}
@@ -229,8 +209,8 @@ public function execute(): void
| ';
Db::$db->data_seek($result, 0);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
echo '
' . implode(' |
@@ -263,8 +243,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;
}
@@ -290,7 +271,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\ViewQuery::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\ViewQuery::exportStatic')) {
ViewQuery::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/Who.php b/Sources/Actions/Who.php
index f31558d6e6..8d604b3cb7 100644
--- a/Sources/Actions/Who.php
+++ b/Sources/Actions/Who.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\IP;
@@ -25,8 +25,6 @@
use SMF\Time;
use SMF\User;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Db\DatabaseApi as Db;
/**
* Who's online, and what are they doing?
@@ -47,12 +45,12 @@ class Who implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'Who',
- ),
- );
+ 'determineActions' => 'determineActions',
+ ],
+ ];
/*******************
* Public static properties
@@ -63,50 +61,50 @@ class Who implements ActionInterface
*
* Actions that require a specific permission level.
*/
- public static array $allowedActions = array(
- 'admin' => array('moderate_forum', 'manage_membergroups', 'manage_bans', 'admin_forum', 'manage_permissions', 'send_mail', 'manage_attachments', 'manage_smileys', 'manage_boards', 'edit_news'),
- 'ban' => array('manage_bans'),
- 'boardrecount' => array('admin_forum'),
- 'calendar' => array('calendar_view'),
- 'corefeatures' => array('admin_forum'),
- 'editnews' => array('edit_news'),
- 'featuresettings' => array('admin_forum'),
- 'languages' => array('admin_forum'),
- 'logs' => array('admin_forum'),
- 'mailing' => array('send_mail'),
- 'mailqueue' => array('admin_forum'),
- 'maintain' => array('admin_forum'),
- 'manageattachments' => array('manage_attachments'),
- 'manageboards' => array('manage_boards'),
- 'managecalendar' => array('admin_forum'),
- 'managesearch' => array('admin_forum'),
- 'managesmileys' => array('manage_smileys'),
- 'membergroups' => array('manage_membergroups'),
- 'mlist' => array('view_mlist'),
- 'moderate' => array('access_mod_center', 'moderate_forum', 'manage_membergroups'),
- 'modsettings' => array('admin_forum'),
- 'news' => array('edit_news', 'send_mail', 'admin_forum'),
- 'optimizetables' => array('admin_forum'),
- 'packages' => array('admin_forum'),
- 'paidsubscribe' => array('admin_forum'),
- 'permissions' => array('manage_permissions'),
- 'postsettings' => array('admin_forum'),
- 'regcenter' => array('admin_forum', 'moderate_forum'),
- 'repairboards' => array('admin_forum'),
- 'reports' => array('admin_forum'),
- 'scheduledtasks' => array('admin_forum'),
- 'search' => array('search_posts'),
- 'search2' => array('search_posts'),
- 'securitysettings' => array('admin_forum'),
- 'sengines' => array('admin_forum'),
- 'serversettings' => array('admin_forum'),
- 'setcensor' => array('moderate_forum'),
- 'setreserve' => array('moderate_forum'),
- 'stats' => array('view_stats'),
- 'theme' => array('admin_forum'),
- 'viewerrorlog' => array('admin_forum'),
- 'viewmembers' => array('moderate_forum'),
- );
+ public static array $allowedActions = [
+ 'admin' => ['moderate_forum', 'manage_membergroups', 'manage_bans', 'admin_forum', 'manage_permissions', 'send_mail', 'manage_attachments', 'manage_smileys', 'manage_boards', 'edit_news'],
+ 'ban' => ['manage_bans'],
+ 'boardrecount' => ['admin_forum'],
+ 'calendar' => ['calendar_view'],
+ 'corefeatures' => ['admin_forum'],
+ 'editnews' => ['edit_news'],
+ 'featuresettings' => ['admin_forum'],
+ 'languages' => ['admin_forum'],
+ 'logs' => ['admin_forum'],
+ 'mailing' => ['send_mail'],
+ 'mailqueue' => ['admin_forum'],
+ 'maintain' => ['admin_forum'],
+ 'manageattachments' => ['manage_attachments'],
+ 'manageboards' => ['manage_boards'],
+ 'managecalendar' => ['admin_forum'],
+ 'managesearch' => ['admin_forum'],
+ 'managesmileys' => ['manage_smileys'],
+ 'membergroups' => ['manage_membergroups'],
+ 'mlist' => ['view_mlist'],
+ 'moderate' => ['access_mod_center', 'moderate_forum', 'manage_membergroups'],
+ 'modsettings' => ['admin_forum'],
+ 'news' => ['edit_news', 'send_mail', 'admin_forum'],
+ 'optimizetables' => ['admin_forum'],
+ 'packages' => ['admin_forum'],
+ 'paidsubscribe' => ['admin_forum'],
+ 'permissions' => ['manage_permissions'],
+ 'postsettings' => ['admin_forum'],
+ 'regcenter' => ['admin_forum', 'moderate_forum'],
+ 'repairboards' => ['admin_forum'],
+ 'reports' => ['admin_forum'],
+ 'scheduledtasks' => ['admin_forum'],
+ 'search' => ['search_posts'],
+ 'search2' => ['search_posts'],
+ 'securitysettings' => ['admin_forum'],
+ 'sengines' => ['admin_forum'],
+ 'serversettings' => ['admin_forum'],
+ 'setcensor' => ['moderate_forum'],
+ 'setreserve' => ['moderate_forum'],
+ 'stats' => ['view_stats'],
+ 'theme' => ['admin_forum'],
+ 'viewerrorlog' => ['admin_forum'],
+ 'viewmembers' => ['moderate_forum'],
+ ];
/****************************
* Internal static properties
@@ -133,35 +131,36 @@ public function execute(): void
User::$me->isAllowedTo('who_view');
// You can't do anything if this is off.
- if (empty(Config::$modSettings['who_enabled']))
+ if (empty(Config::$modSettings['who_enabled'])) {
ErrorHandler::fatalLang('who_off', false);
+ }
// Discourage robots from indexing this page.
Utils::$context['robot_no_index'] = true;
// Sort out... the column sorting.
- $sort_methods = array(
+ $sort_methods = [
'user' => 'mem.real_name',
- 'time' => 'lo.log_time'
- );
+ 'time' => 'lo.log_time',
+ ];
- $show_methods = array(
+ $show_methods = [
'members' => '(lo.id_member != 0)',
'guests' => '(lo.id_member = 0)',
'all' => '1=1',
- );
+ ];
// Store the sort methods and the show types for use in the template.
- Utils::$context['sort_methods'] = array(
+ Utils::$context['sort_methods'] = [
'user' => Lang::$txt['who_user'],
'time' => Lang::$txt['who_time'],
- );
+ ];
- Utils::$context['show_methods'] = array(
+ Utils::$context['show_methods'] = [
'all' => Lang::$txt['who_show_all'],
'members' => Lang::$txt['who_show_members_only'],
'guests' => Lang::$txt['who_show_guests_only'],
- );
+ ];
// Can they see spiders too?
if (
@@ -171,76 +170,69 @@ public function execute(): void
|| User::$me->allowedTo('admin_forum')
)
&& !empty(Config::$modSettings['spider_name_cache'])
- )
- {
+ ) {
$show_methods['spiders'] = '(lo.id_member = 0 AND lo.id_spider > 0)';
$show_methods['guests'] = '(lo.id_member = 0 AND lo.id_spider = 0)';
Utils::$context['show_methods']['spiders'] = Lang::$txt['who_show_spiders_only'];
- }
- elseif (
+ } elseif (
empty(Config::$modSettings['show_spider_online'])
&& isset($_SESSION['who_online_filter'])
&& $_SESSION['who_online_filter'] == 'spiders'
- )
- {
+ ) {
unset($_SESSION['who_online_filter']);
}
// Does the user prefer a different sort direction?
- if (isset($_REQUEST['sort']) && isset($sort_methods[$_REQUEST['sort']]))
- {
+ if (isset($_REQUEST['sort'], $sort_methods[$_REQUEST['sort']])) {
Utils::$context['sort_by'] = $_SESSION['who_online_sort_by'] = $_REQUEST['sort'];
$sort_method = $sort_methods[$_REQUEST['sort']];
}
// Did we set a preferred sort order earlier in the session?
- elseif (isset($_SESSION['who_online_sort_by']))
- {
+ elseif (isset($_SESSION['who_online_sort_by'])) {
Utils::$context['sort_by'] = $_SESSION['who_online_sort_by'];
$sort_method = $sort_methods[$_SESSION['who_online_sort_by']];
}
// Default to last time online.
- else
- {
+ else {
Utils::$context['sort_by'] = $_SESSION['who_online_sort_by'] = 'time';
$sort_method = 'lo.log_time';
}
Utils::$context['sort_direction'] = isset($_REQUEST['asc']) || (isset($_REQUEST['sort_dir']) && $_REQUEST['sort_dir'] == 'asc') ? 'up' : 'down';
- $conditions = array();
+ $conditions = [];
- if (!User::$me->allowedTo('moderate_forum'))
+ if (!User::$me->allowedTo('moderate_forum')) {
$conditions[] = '(COALESCE(mem.show_online, 1) = 1)';
+ }
// Fallback to top filter?
- if (isset($_REQUEST['submit_top']) && isset($_REQUEST['show_top']))
+ if (isset($_REQUEST['submit_top'], $_REQUEST['show_top'])) {
$_REQUEST['show'] = $_REQUEST['show_top'];
+ }
// Does the user wish to apply a filter?
- if (isset($_REQUEST['show']) && isset($show_methods[$_REQUEST['show']]))
- {
+ if (isset($_REQUEST['show'], $show_methods[$_REQUEST['show']])) {
Utils::$context['show_by'] = $_SESSION['who_online_filter'] = $_REQUEST['show'];
}
// Perhaps we saved a filter earlier in the session?
- elseif (isset($_SESSION['who_online_filter']))
- {
+ elseif (isset($_SESSION['who_online_filter'])) {
Utils::$context['show_by'] = $_SESSION['who_online_filter'];
- }
- else
- {
+ } else {
Utils::$context['show_by'] = 'members';
}
$conditions[] = $show_methods[Utils::$context['show_by']];
// Get the total amount of members online.
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}log_online AS lo
LEFT JOIN {db_prefix}members AS mem ON (lo.id_member = mem.id_member)' . (!empty($conditions) ? '
WHERE ' . implode(' AND ', $conditions) : ''),
- array(
- )
+ [
+ ],
);
list($totalMembers) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -251,12 +243,13 @@ public function execute(): void
Utils::$context['start'] = $_REQUEST['start'];
// Look for people online, provided they don't mind if you see they are.
- Utils::$context['members'] = array();
- $member_ids = array();
- $url_data = array();
+ Utils::$context['members'] = [];
+ $member_ids = [];
+ $url_data = [];
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
lo.log_time, lo.id_member, lo.url, lo.ip AS ip, mem.real_name,
lo.session, mg.online_color, COALESCE(mem.show_online, 1) AS show_online,
lo.id_spider
@@ -266,35 +259,36 @@ public function execute(): void
WHERE ' . implode(' AND ', $conditions) : '') . '
ORDER BY {raw:sort_method} {raw:sort_direction}
LIMIT {int:offset}, {int:limit}',
- array(
+ [
'regular_member' => 0,
'sort_method' => $sort_method,
'sort_direction' => Utils::$context['sort_direction'] == 'up' ? 'ASC' : 'DESC',
'offset' => Utils::$context['start'],
'limit' => Config::$modSettings['defaultMaxMembers'],
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$actions = Utils::jsonDecode($row['url'], true);
- if ($actions === array())
+ if ($actions === []) {
continue;
+ }
// Send the information to the template.
- Utils::$context['members'][$row['session']] = array(
+ Utils::$context['members'][$row['session']] = [
'id' => $row['id_member'],
'ip' => User::$me->allowedTo('moderate_forum') ? new IP($row['ip']) : '',
// It is *going* to be today or yesterday, so why keep that information in there?
- 'time' => strtr(Time::create('@' . $row['log_time'])->format(), array(Lang::$txt['today'] => '', Lang::$txt['yesterday'] => '')),
+ 'time' => strtr(Time::create('@' . $row['log_time'])->format(), [Lang::$txt['today'] => '', Lang::$txt['yesterday'] => '']),
'timestamp' => $row['log_time'],
'query' => $actions,
'is_hidden' => $row['show_online'] == 0,
'id_spider' => $row['id_spider'],
- 'color' => empty($row['online_color']) ? '' : $row['online_color']
- );
+ 'color' => empty($row['online_color']) ? '' : $row['online_color'],
+ ];
- $url_data[$row['session']] = array($row['url'], $row['id_member']);
+ $url_data[$row['session']] = [$row['url'], $row['id_member']];
$member_ids[] = $row['id_member'];
}
Db::$db->free_result($request);
@@ -303,7 +297,7 @@ public function execute(): void
User::load($member_ids);
// Are we showing spiders?
- $spiderFormatted = array();
+ $spiderFormatted = [];
if (
!empty(Config::$modSettings['show_spider_online'])
@@ -312,16 +306,14 @@ public function execute(): void
Config::$modSettings['show_spider_online'] == 2
|| User::$me->allowedTo('admin_forum')
)
- )
- {
- foreach (Utils::jsonDecode(Config::$modSettings['spider_name_cache'], true) as $id => $name)
- {
- $spiderFormatted[$id] = array(
+ ) {
+ foreach (Utils::jsonDecode(Config::$modSettings['spider_name_cache'], true) as $id => $name) {
+ $spiderFormatted[$id] = [
'name' => $name,
'group' => Lang::$txt['spiders'],
'link' => $name,
'email' => $name,
- );
+ ];
}
}
@@ -329,14 +321,13 @@ public function execute(): void
// Setup the linktree and page title (do it down here because the language files are now loaded..)
Utils::$context['page_title'] = Lang::$txt['who_title'];
- Utils::$context['linktree'][] = array(
+ Utils::$context['linktree'][] = [
'url' => Config::$scripturl . '?action=who',
- 'name' => Lang::$txt['who_title']
- );
+ 'name' => Lang::$txt['who_title'],
+ ];
// Put it in the context variables.
- foreach (Utils::$context['members'] as $i => $member)
- {
+ foreach (Utils::$context['members'] as $i => $member) {
$member['id'] = isset(User::$loaded[$member['id']]) ? $member['id'] : 0;
$formatted = User::$loaded[$member['id']]->format();
@@ -344,24 +335,20 @@ public function execute(): void
// Keep the IP that came from the database.
$formatted['ip'] = $member['ip'];
- if ($member['id'] == 0)
- {
- if (isset($spiderFormatted[$member['id_spider']]))
- {
+ if ($member['id'] == 0) {
+ if (isset($spiderFormatted[$member['id_spider']])) {
$formatted = array_merge($formatted, $spiderFormatted[$member['id_spider']]);
- }
- else
- {
- $formatted = array_merge($formatted, array(
+ } else {
+ $formatted = array_merge($formatted, [
'link' => Lang::$txt['guest_title'],
'email' => Lang::$txt['guest_title'],
- ));
+ ]);
}
}
Utils::$context['members'][$i] = array_merge(Utils::$context['members'][$i], $formatted);
- Utils::$context['members'][$i]['action'] = isset($url_data[$i]) ? $url_data[$i] : array('label' => 'who_hidden', 'class' => 'em');
+ Utils::$context['members'][$i]['action'] = $url_data[$i] ?? ['label' => 'who_hidden', 'class' => 'em'];
}
// Some people can't send personal messages...
@@ -369,7 +356,7 @@ public function execute(): void
Utils::$context['can_send_email'] = User::$me->allowedTo('moderate_forum');
// any profile fields disabled?
- Utils::$context['disabled_fields'] = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : array();
+ Utils::$context['disabled_fields'] = isset(Config::$modSettings['disabled_profile_fields']) ? array_flip(explode(',', Config::$modSettings['disabled_profile_fields'])) : [];
}
/***********************
@@ -383,8 +370,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;
}
@@ -418,224 +406,181 @@ public static function call(): void
*/
public static function determineActions($urls, $preferred_prefix = false)
{
- if (!User::$me->allowedTo('who_view'))
- return array();
+ if (!User::$me->allowedTo('who_view')) {
+ return [];
+ }
Lang::load('Who');
- IntegrationHook::call('who_allowed', array(&self::$allowedActions));
+ IntegrationHook::call('who_allowed', [&self::$allowedActions]);
- if (!is_array($urls))
- {
- $url_list = array(array($urls, User::$me->id));
- }
- else
- {
+ if (!is_array($urls)) {
+ $url_list = [[$urls, User::$me->id]];
+ } else {
$url_list = $urls;
}
// These are done to later query these in large chunks. (instead of one by one.)
- $topic_ids = array();
- $profile_ids = array();
- $board_ids = array();
+ $topic_ids = [];
+ $profile_ids = [];
+ $board_ids = [];
- $data = array();
- foreach ($url_list as $k => $url)
- {
+ $data = [];
+
+ foreach ($url_list as $k => $url) {
// Get the request parameters..
$actions = Utils::jsonDecode($url[0], true);
- if ($actions === array())
+ if ($actions === []) {
continue;
+ }
// If it's the admin or moderation center, and there is an area set, use that instead.
- if (isset($actions['action']) && ($actions['action'] == 'admin' || $actions['action'] == 'moderate') && isset($actions['area']))
- {
+ if (isset($actions['action']) && ($actions['action'] == 'admin' || $actions['action'] == 'moderate') && isset($actions['area'])) {
$actions['action'] = $actions['area'];
}
// Check if there was no action or the action is display.
- if (!isset($actions['action']) || $actions['action'] == 'display')
- {
+ if (!isset($actions['action']) || $actions['action'] == 'display') {
// It's a topic! Must be!
- if (isset($actions['topic']))
- {
+ if (isset($actions['topic'])) {
// Assume they can't view it, and queue it up for later.
- $data[$k] = array('label' => 'who_hidden', 'class' => 'em');
+ $data[$k] = ['label' => 'who_hidden', 'class' => 'em'];
$topic_ids[(int) $actions['topic']][$k] = Lang::$txt['who_topic'];
}
// It's a board!
- elseif (isset($actions['board']))
- {
+ elseif (isset($actions['board'])) {
// Hide first, show later.
- $data[$k] = array('label' => 'who_hidden', 'class' => 'em');
+ $data[$k] = ['label' => 'who_hidden', 'class' => 'em'];
$board_ids[$actions['board']][$k] = Lang::$txt['who_board'];
}
// It's the board index!! It must be!
- else
- {
+ else {
$data[$k] = sprintf(Lang::$txt['who_index'], Config::$scripturl, Utils::$context['forum_name_html_safe']);
}
}
// Probably an error or some goon?
- elseif ($actions['action'] == '')
- {
+ elseif ($actions['action'] == '') {
$data[$k] = sprintf(Lang::$txt['who_index'], Config::$scripturl, Utils::$context['forum_name_html_safe']);
}
// Some other normal action...?
- else
- {
+ else {
// Viewing/editing a profile.
- if ($actions['action'] == 'profile')
- {
+ if ($actions['action'] == 'profile') {
// Whose? Their own?
- if (empty($actions['u']))
+ if (empty($actions['u'])) {
$actions['u'] = $url[1];
+ }
- $data[$k] = array('label' => 'who_hidden', 'class' => 'em');
+ $data[$k] = ['label' => 'who_hidden', 'class' => 'em'];
$profile_ids[(int) $actions['u']][$k] = $actions['u'] == $url[1] ? Lang::$txt['who_viewownprofile'] : Lang::$txt['who_viewprofile'];
- }
- elseif (($actions['action'] == 'post' || $actions['action'] == 'post2') && empty($actions['topic']) && isset($actions['board']))
- {
- $data[$k] = array('label' => 'who_hidden', 'class' => 'em');
+ } elseif (($actions['action'] == 'post' || $actions['action'] == 'post2') && empty($actions['topic']) && isset($actions['board'])) {
+ $data[$k] = ['label' => 'who_hidden', 'class' => 'em'];
$board_ids[(int) $actions['board']][$k] = isset($actions['poll']) ? Lang::$txt['who_poll'] : Lang::$txt['who_post'];
}
// A subaction anyone can view... if the language string is there, show it.
- elseif (isset($actions['sa']) && isset(Lang::$txt['whoall_' . $actions['action'] . '_' . $actions['sa']]))
- {
+ elseif (isset($actions['sa'], Lang::$txt['whoall_' . $actions['action'] . '_' . $actions['sa']])) {
$data[$k] = $preferred_prefix && isset(Lang::$txt[$preferred_prefix . $actions['action'] . '_' . $actions['sa']]) ? Lang::$txt[$preferred_prefix . $actions['action'] . '_' . $actions['sa']] : sprintf(Lang::$txt['whoall_' . $actions['action'] . '_' . $actions['sa']], Config::$scripturl);
}
// An action any old fellow can look at. (if ['whoall_' . $action] exists, we know everyone can see it.)
- elseif (isset(Lang::$txt['whoall_' . $actions['action']]))
- {
+ elseif (isset(Lang::$txt['whoall_' . $actions['action']])) {
$data[$k] = $preferred_prefix && isset(Lang::$txt[$preferred_prefix . $actions['action']]) ? Lang::$txt[$preferred_prefix . $actions['action']] : sprintf(Lang::$txt['whoall_' . $actions['action']], Config::$scripturl);
}
// Viewable if and only if they can see the board...
- elseif (isset(Lang::$txt['whotopic_' . $actions['action']]))
- {
+ elseif (isset(Lang::$txt['whotopic_' . $actions['action']])) {
// Find out what topic they are accessing.
- $topic = (int) (isset($actions['topic']) ? $actions['topic'] : (isset($actions['from']) ? $actions['from'] : 0));
+ $topic = (int) ($actions['topic'] ?? ($actions['from'] ?? 0));
- $data[$k] = array('label' => 'who_hidden', 'class' => 'em');
+ $data[$k] = ['label' => 'who_hidden', 'class' => 'em'];
$topic_ids[$topic][$k] = Lang::$txt['whotopic_' . $actions['action']];
- }
- elseif (isset(Lang::$txt['whopost_' . $actions['action']]))
- {
+ } elseif (isset(Lang::$txt['whopost_' . $actions['action']])) {
// Find out what message they are accessing.
- $msgid = (int) (isset($actions['msg']) ? $actions['msg'] : (isset($actions['quote']) ? $actions['quote'] : 0));
+ $msgid = (int) ($actions['msg'] ?? ($actions['quote'] ?? 0));
- $result = Db::$db->query('', '
- SELECT m.id_topic, m.subject
+ $result = Db::$db->query(
+ '',
+ 'SELECT m.id_topic, m.subject
FROM {db_prefix}messages AS m
' . (Config::$modSettings['postmod_active'] ? 'INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic AND t.approved = {int:is_approved})' : '') . '
WHERE m.id_msg = {int:id_msg}
AND {query_see_message_board}' . (Config::$modSettings['postmod_active'] ? '
AND m.approved = {int:is_approved}' : '') . '
LIMIT 1',
- array(
+ [
'is_approved' => 1,
'id_msg' => $msgid,
- )
+ ],
);
list($id_topic, $subject) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
$data[$k] = sprintf(Lang::$txt['whopost_' . $actions['action']], $id_topic, $subject, Config::$scripturl);
- if (empty($id_topic))
- $data[$k] = array('label' => 'who_hidden', 'class' => 'em');
+ if (empty($id_topic)) {
+ $data[$k] = ['label' => 'who_hidden', 'class' => 'em'];
+ }
}
// Viewable only by administrators.. (if it starts with whoadmin, it's admin only!)
- elseif (User::$me->allowedTo('moderate_forum') && isset(Lang::$txt['whoadmin_' . $actions['action']]))
- {
+ elseif (User::$me->allowedTo('moderate_forum') && isset(Lang::$txt['whoadmin_' . $actions['action']])) {
$data[$k] = sprintf(Lang::$txt['whoadmin_' . $actions['action']], Config::$scripturl);
}
// Viewable by permission level.
- elseif (isset(self::$allowedActions[$actions['action']]))
- {
- if (User::$me->allowedTo(self::$allowedActions[$actions['action']]) && !empty(Lang::$txt['whoallow_' . $actions['action']]))
- {
+ elseif (isset(self::$allowedActions[$actions['action']])) {
+ if (User::$me->allowedTo(self::$allowedActions[$actions['action']]) && !empty(Lang::$txt['whoallow_' . $actions['action']])) {
$data[$k] = sprintf(Lang::$txt['whoallow_' . $actions['action']], Config::$scripturl);
- }
- elseif (in_array('moderate_forum', self::$allowedActions[$actions['action']]))
- {
+ } elseif (in_array('moderate_forum', self::$allowedActions[$actions['action']])) {
$data[$k] = Lang::$txt['who_moderate'];
- }
- elseif (in_array('admin_forum', self::$allowedActions[$actions['action']]))
- {
+ } elseif (in_array('admin_forum', self::$allowedActions[$actions['action']])) {
$data[$k] = Lang::$txt['who_admin'];
+ } else {
+ $data[$k] = ['label' => 'who_hidden', 'class' => 'em'];
}
- else
- {
- $data[$k] = array('label' => 'who_hidden', 'class' => 'em');
- }
- }
- elseif (!empty($actions['action']))
- {
+ } elseif (!empty($actions['action'])) {
$data[$k] = Lang::$txt['who_generic'] . ' ' . $actions['action'];
- }
- else
- {
- $data[$k] = array('label' => 'who_unknown', 'class' => 'em');
+ } else {
+ $data[$k] = ['label' => 'who_unknown', 'class' => 'em'];
}
}
- if (isset($actions['error']))
- {
+ if (isset($actions['error'])) {
Lang::load('Errors');
- if (isset(Lang::$txt[$actions['error']]))
- {
+ if (isset(Lang::$txt[$actions['error']])) {
$error_message = str_replace('"', '"', empty($actions['error_params']) ? Lang::$txt[$actions['error']] : vsprintf(Lang::$txt[$actions['error']], (array) $actions['error_params']));
- }
- elseif ($actions['error'] == 'guest_login')
- {
+ } elseif ($actions['error'] == 'guest_login') {
$error_message = str_replace('"', '"', Lang::$txt['who_guest_login']);
- }
- else
- {
+ } else {
$error_message = str_replace('"', '"', $actions['error']);
}
- if (!empty($error_message))
- {
+ if (!empty($error_message)) {
$error_message = ' ';
- if (is_array($data[$k]))
- {
+ if (is_array($data[$k])) {
$data[$k]['error_message'] = $error_message;
- }
- else
- {
+ } else {
$data[$k] .= $error_message;
}
}
}
// Maybe the action is integrated into another system?
- if (count($integrate_actions = IntegrationHook::call('integrate_whos_online', array($actions))) > 0)
- {
- foreach ($integrate_actions as $integrate_action)
- {
- if (!empty($integrate_action))
- {
+ if (count($integrate_actions = IntegrationHook::call('integrate_whos_online', [$actions])) > 0) {
+ foreach ($integrate_actions as $integrate_action) {
+ if (!empty($integrate_action)) {
$data[$k] = $integrate_action;
- if (isset($actions['topic']) && isset($topic_ids[(int) $actions['topic']][$k]))
- {
+ if (isset($actions['topic'], $topic_ids[(int) $actions['topic']][$k])) {
$topic_ids[(int) $actions['topic']][$k] = $integrate_action;
}
- if (isset($actions['board']) && isset($board_ids[(int) $actions['board']][$k]))
- {
+ if (isset($actions['board'], $board_ids[(int) $actions['board']][$k])) {
$board_ids[(int) $actions['board']][$k] = $integrate_action;
}
- if (isset($actions['u']) && isset($profile_ids[(int) $actions['u']][$k]))
- {
+ if (isset($actions['u'], $profile_ids[(int) $actions['u']][$k])) {
$profile_ids[(int) $actions['u']][$k] = $integrate_action;
}
-
break;
}
}
@@ -643,27 +588,26 @@ public static function determineActions($urls, $preferred_prefix = false)
}
// Load topic names.
- if (!empty($topic_ids))
- {
- $result = Db::$db->query('', '
- SELECT t.id_topic, m.subject
+ if (!empty($topic_ids)) {
+ $result = Db::$db->query(
+ '',
+ 'SELECT t.id_topic, m.subject
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
WHERE {query_see_topic_board}
AND t.id_topic IN ({array_int:topic_list})' . (Config::$modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved}' : '') . '
LIMIT {int:limit}',
- array(
+ [
'topic_list' => array_keys($topic_ids),
'is_approved' => 1,
'limit' => count($topic_ids),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
// Show the topic's subject for each of the actions.
- foreach ($topic_ids[$row['id_topic']] as $k => $session_text)
- {
+ foreach ($topic_ids[$row['id_topic']] as $k => $session_text) {
$data[$k] = sprintf($session_text, $row['id_topic'], Lang::censorText($row['subject']), Config::$scripturl);
}
}
@@ -671,24 +615,23 @@ public static function determineActions($urls, $preferred_prefix = false)
}
// Load board names.
- if (!empty($board_ids))
- {
- $result = Db::$db->query('', '
- SELECT b.id_board, b.name
+ if (!empty($board_ids)) {
+ $result = Db::$db->query(
+ '',
+ 'SELECT b.id_board, b.name
FROM {db_prefix}boards AS b
WHERE {query_see_board}
AND b.id_board IN ({array_int:board_list})
LIMIT {int:limit}',
- array(
+ [
'board_list' => array_keys($board_ids),
'limit' => count($board_ids),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
// Put the board name into the string for each member...
- foreach ($board_ids[$row['id_board']] as $k => $session_text)
- {
+ foreach ($board_ids[$row['id_board']] as $k => $session_text) {
$data[$k] = sprintf($session_text, $row['id_board'], $row['name'], Config::$scripturl);
}
}
@@ -699,42 +642,39 @@ public static function determineActions($urls, $preferred_prefix = false)
$allow_view_own = User::$me->allowedTo('is_not_guest');
$allow_view_any = User::$me->allowedTo('profile_view');
- if (!empty($profile_ids) && ($allow_view_any || $allow_view_own))
- {
- $result = Db::$db->query('', '
- SELECT id_member, real_name
+ if (!empty($profile_ids) && ($allow_view_any || $allow_view_own)) {
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_member, real_name
FROM {db_prefix}members
WHERE id_member IN ({array_int:member_list})
LIMIT ' . count($profile_ids),
- array(
+ [
'member_list' => array_keys($profile_ids),
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
// If they aren't allowed to view this person's profile, skip it.
- if (!$allow_view_any && (User::$me->id != $row['id_member']))
+ if (!$allow_view_any && (User::$me->id != $row['id_member'])) {
continue;
+ }
// Set their action on each - session/text to sprintf.
- foreach ($profile_ids[$row['id_member']] as $k => $session_text)
- {
+ foreach ($profile_ids[$row['id_member']] as $k => $session_text) {
$data[$k] = sprintf($session_text, $row['id_member'], $row['real_name'], Config::$scripturl);
}
}
Db::$db->free_result($result);
}
- IntegrationHook::call('whos_online_after', array(&$urls, &$data));
+ IntegrationHook::call('whos_online_after', [&$urls, &$data]);
- if (!is_array($urls))
- {
- return isset($data[0]) ? $data[0] : false;
- }
- else
- {
- return $data;
+ if (!is_array($urls)) {
+ return $data[0] ?? false;
}
+
+ return $data;
}
/******************
@@ -753,7 +693,8 @@ protected function __construct()
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Who::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Who::exportStatic')) {
Who::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/XmlHttp.php b/Sources/Actions/XmlHttp.php
index 96fc712d19..c3775fec62 100644
--- a/Sources/Actions/XmlHttp.php
+++ b/Sources/Actions/XmlHttp.php
@@ -13,11 +13,12 @@
namespace SMF\Actions;
+use SMF\Actions\Admin\News;
use SMF\BackwardCompatibility;
-
use SMF\BBCodeParser;
use SMF\Board;
use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
use SMF\Editor;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
@@ -27,8 +28,6 @@
use SMF\Theme;
use SMF\User;
use SMF\Utils;
-use SMF\Actions\Admin\News;
-use SMF\Db\DatabaseApi as Db;
/**
* Handles XML-based interaction (mainly XMLhttp)
@@ -42,12 +41,14 @@ class XmlHttp implements ActionInterface
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'XMLhttpMain',
- ),
- );
+ 'GetJumpTo' => 'GetJumpTo',
+ 'ListMessageIcons' => 'ListMessageIcons',
+ 'RetrievePreview' => 'RetrievePreview',
+ ],
+ ];
/*******************
* Public properties
@@ -70,11 +71,11 @@ class XmlHttp implements ActionInterface
*
* Available sub-actions.
*/
- public static array $subactions = array(
+ public static array $subactions = [
'jumpto' => 'jumpTo',
'messageicons' => 'messageIcons',
'previews' => 'previews',
- );
+ ];
/****************************
* Internal static properties
@@ -97,34 +98,34 @@ class XmlHttp implements ActionInterface
*/
public function execute(): void
{
- if (!isset($this->subaction))
+ if (!isset($this->subaction)) {
ErrorHandler::fatalLang('no_access', false);
+ }
- $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);
+ }
}
/**
* Get a list of boards and categories used for the jumpto dropdown.
*/
- function jumpTo()
+ public function jumpTo()
{
// Find the boards/categories they can see.
- $boardListOptions = array(
+ $boardListOptions = [
'use_permissions' => true,
- 'selected_board' => isset(Utils::$context['current_board']) ? Utils::$context['current_board'] : 0,
- );
+ 'selected_board' => Utils::$context['current_board'] ?? 0,
+ ];
Utils::$context['jump_to'] = MessageIndex::getBoardList($boardListOptions);
// Make the board safe for display.
- foreach (Utils::$context['jump_to'] as $id_cat => $cat)
- {
+ foreach (Utils::$context['jump_to'] as $id_cat => $cat) {
Utils::$context['jump_to'][$id_cat]['name'] = Utils::htmlspecialcharsDecode(strip_tags($cat['name']));
- foreach ($cat['boards'] as $id_board => $board)
- {
+ foreach ($cat['boards'] as $id_board => $board) {
Utils::$context['jump_to'][$id_cat]['boards'][$id_board]['name'] = Utils::htmlspecialcharsDecode(strip_tags($board['name']));
}
}
@@ -135,7 +136,7 @@ function jumpTo()
/**
* Gets a list of available message icons and sends the info to the template for display
*/
- function messageIcons()
+ public function messageIcons()
{
Utils::$context['icons'] = Editor::getMessageIcons(Board::$info->id);
Utils::$context['sub_template'] = 'message_icons';
@@ -147,73 +148,73 @@ function messageIcons()
*
* @return void|bool Returns false if $_POST['item'] isn't set or isn't valid
*/
- function previews()
+ public function previews()
{
- $items = array(
+ $items = [
'newspreview',
'newsletterpreview',
'sig_preview',
'warning_preview',
- );
+ ];
Utils::$context['sub_template'] = 'generic_xml';
- if (!isset($_POST['item']) || !in_array($_POST['item'], $items))
+ if (!isset($_POST['item']) || !in_array($_POST['item'], $items)) {
return false;
+ }
- call_user_func(array($this, $_POST['item']));
+ call_user_func([$this, $_POST['item']]);
}
/**
* Handles previewing news items
*/
- function newspreview()
+ public function newspreview()
{
- $errors = array();
+ $errors = [];
$news = !isset($_POST['news']) ? '' : Utils::htmlspecialchars($_POST['news'], ENT_QUOTES);
- if (empty($news))
- {
- $errors[] = array('value' => 'no_news');
- }
- else
- {
+ if (empty($news)) {
+ $errors[] = ['value' => 'no_news'];
+ } else {
Msg::preparsecode($news);
}
- Utils::$context['xml_data'] = array(
- 'news' => array(
+ Utils::$context['xml_data'] = [
+ 'news' => [
'identifier' => 'parsedNews',
- 'children' => array(
- array(
+ 'children' => [
+ [
'value' => BBCodeParser::load()->parse($news),
- ),
- ),
- ),
- 'errors' => array(
+ ],
+ ],
+ ],
+ 'errors' => [
'identifier' => 'error',
- 'children' => $errors
- ),
- );
+ 'children' => $errors,
+ ],
+ ];
}
/**
* Handles previewing newsletters
*/
- function newsletterpreview()
+ public function newsletterpreview()
{
Lang::load('Errors');
- Utils::$context['post_error']['messages'] = array();
+ Utils::$context['post_error']['messages'] = [];
Utils::$context['send_pm'] = !empty($_POST['send_pm']) ? 1 : 0;
Utils::$context['send_html'] = !empty($_POST['send_html']) ? 1 : 0;
- if (empty($_POST['subject']))
+ if (empty($_POST['subject'])) {
Utils::$context['post_error']['messages'][] = Lang::$txt['error_no_subject'];
+ }
- if (empty($_POST['message']))
+ if (empty($_POST['message'])) {
Utils::$context['post_error']['messages'][] = Lang::$txt['error_no_message'];
+ }
News::prepareMailingForPreview();
@@ -223,9 +224,9 @@ function newsletterpreview()
/**
* Handles previewing signatures
*/
- function sig_preview()
+ public function sig_preview()
{
- require_once(Config::$sourcedir . '/Profile-Modify.php');
+ require_once Config::$sourcedir . '/Profile-Modify.php';
Lang::load('Profile');
Lang::load('Errors');
@@ -235,20 +236,20 @@ function sig_preview()
// @todo Temporary
// Borrowed from loadAttachmentContext in Display.php
- $can_change = $is_owner ? User::$me->allowedTo(array('profile_extra_any', 'profile_extra_own')) : User::$me->allowedTo('profile_extra_any');
+ $can_change = $is_owner ? User::$me->allowedTo(['profile_extra_any', 'profile_extra_own']) : User::$me->allowedTo('profile_extra_any');
- $errors = array();
+ $errors = [];
- if (!empty($user) && $can_change)
- {
- $request = Db::$db->query('', '
- SELECT signature
+ if (!empty($user) && $can_change) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT signature
FROM {db_prefix}members
WHERE id_member = {int:id_member}
LIMIT 1',
- array(
+ [
'id_member' => $user,
- )
+ ],
);
list($current_signature) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -263,99 +264,83 @@ function sig_preview()
$validation = Profile::validateSignature($preview_signature);
- if ($validation !== true && $validation !== false)
- {
- $errors[] = array('value' => Lang::$txt['profile_error_' . $validation], 'attributes' => array('type' => 'error'));
+ if ($validation !== true && $validation !== false) {
+ $errors[] = ['value' => Lang::$txt['profile_error_' . $validation], 'attributes' => ['type' => 'error']];
}
Lang::censorText($preview_signature);
$preview_signature = BBCodeParser::load()->parse($preview_signature, true, 'sig' . $user, $allowedTags);
- }
- elseif (!$can_change)
- {
- if ($is_owner)
- {
- $errors[] = array('value' => Lang::$txt['cannot_profile_extra_own'], 'attributes' => array('type' => 'error'));
- }
- else
- {
- $errors[] = array('value' => Lang::$txt['cannot_profile_extra_any'], 'attributes' => array('type' => 'error'));
+ } elseif (!$can_change) {
+ if ($is_owner) {
+ $errors[] = ['value' => Lang::$txt['cannot_profile_extra_own'], 'attributes' => ['type' => 'error']];
+ } else {
+ $errors[] = ['value' => Lang::$txt['cannot_profile_extra_any'], 'attributes' => ['type' => 'error']];
}
- }
- else
- {
- $errors[] = array('value' => Lang::$txt['no_user_selected'], 'attributes' => array('type' => 'error'));
+ } else {
+ $errors[] = ['value' => Lang::$txt['no_user_selected'], 'attributes' => ['type' => 'error']];
}
- Utils::$context['xml_data']['signatures'] = array(
+ Utils::$context['xml_data']['signatures'] = [
'identifier' => 'signature',
- 'children' => array()
- );
+ 'children' => [],
+ ];
- if (isset($current_signature))
- {
- Utils::$context['xml_data']['signatures']['children'][] = array(
+ if (isset($current_signature)) {
+ Utils::$context['xml_data']['signatures']['children'][] = [
'value' => $current_signature,
- 'attributes' => array('type' => 'current'),
- );
+ 'attributes' => ['type' => 'current'],
+ ];
}
- if (isset($preview_signature))
- {
- Utils::$context['xml_data']['signatures']['children'][] = array(
+ if (isset($preview_signature)) {
+ Utils::$context['xml_data']['signatures']['children'][] = [
'value' => $preview_signature,
- 'attributes' => array('type' => 'preview'),
- );
+ 'attributes' => ['type' => 'preview'],
+ ];
}
- if (!empty($errors))
- {
- Utils::$context['xml_data']['errors'] = array(
+ if (!empty($errors)) {
+ Utils::$context['xml_data']['errors'] = [
'identifier' => 'error',
'children' => array_merge(
- array(
- array(
+ [
+ [
'value' => Lang::$txt['profile_errors_occurred'],
- 'attributes' => array('type' => 'errors_occurred'),
- ),
- ),
- $errors
+ 'attributes' => ['type' => 'errors_occurred'],
+ ],
+ ],
+ $errors,
),
- );
+ ];
}
}
/**
* Handles previewing user warnings
*/
- function warning_preview()
+ public function warning_preview()
{
Lang::load('Errors');
Lang::load('ModerationCenter');
- Utils::$context['post_error']['messages'] = array();
+ Utils::$context['post_error']['messages'] = [];
- if (User::$me->allowedTo('issue_warning'))
- {
+ if (User::$me->allowedTo('issue_warning')) {
$warning_body = !empty($_POST['body']) ? trim(Lang::censorText($_POST['body'])) : '';
Utils::$context['preview_subject'] = !empty($_POST['title']) ? trim(Utils::htmlspecialchars($_POST['title'])) : '';
- if (isset($_POST['issuing']))
- {
- if (empty($_POST['title']) || empty($_POST['body']))
+ if (isset($_POST['issuing'])) {
+ if (empty($_POST['title']) || empty($_POST['body'])) {
Utils::$context['post_error']['messages'][] = Lang::$txt['warning_notify_blank'];
- }
- else
- {
- if (empty($_POST['title']))
- {
+ }
+ } else {
+ if (empty($_POST['title'])) {
Utils::$context['post_error']['messages'][] = Lang::$txt['mc_warning_template_error_no_title'];
}
- if (empty($_POST['body']))
- {
+ if (empty($_POST['body'])) {
Utils::$context['post_error']['messages'][] = Lang::$txt['mc_warning_template_error_no_body'];
}
@@ -368,35 +353,32 @@ function warning_preview()
* - {SCRIPTURL} - Web address of forum.
* - {REGARDS} - Standard email sign-off.
*/
- $find = array(
+ $find = [
'{MEMBER}',
'{FORUMNAME}',
'{SCRIPTURL}',
'{REGARDS}',
- );
+ ];
- $replace = array(
+ $replace = [
User::$me->name,
Config::$mbname,
Config::$scripturl,
sprintf(Lang::$txt['regards_team'], Utils::$context['forum_name']),
- );
+ ];
$warning_body = str_replace($find, $replace, $warning_body);
}
- if (!empty($_POST['body']))
- {
+ if (!empty($_POST['body'])) {
Msg::preparsecode($warning_body);
$warning_body = BBCodeParser::load()->parse($warning_body);
}
Utils::$context['preview_message'] = $warning_body;
- }
- else
- {
- Utils::$context['post_error']['messages'][] = array('value' => Lang::$txt['cannot_issue_warning'], 'attributes' => array('type' => 'error'));
+ } else {
+ Utils::$context['post_error']['messages'][] = ['value' => Lang::$txt['cannot_issue_warning'], 'attributes' => ['type' => 'error']];
}
Utils::$context['sub_template'] = 'warning';
@@ -413,8 +395,9 @@ function warning_preview()
*/
public static function load(): object
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
return self::$obj;
}
@@ -469,15 +452,17 @@ protected function __construct()
Theme::loadTemplate('Xml');
// Easy adding of sub actions.
- IntegrationHook::call('integrate_XMLhttpMain_subActions', array(&self::$subactions));
+ IntegrationHook::call('integrate_XMLhttpMain_subActions', [&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__ . '\XmlHttp::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\XmlHttp::exportStatic')) {
XmlHttp::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Actions/index.php b/Sources/Actions/index.php
new file mode 100644
index 0000000000..976d292448
--- /dev/null
+++ b/Sources/Actions/index.php
@@ -0,0 +1,9 @@
+
\ No newline at end of file
diff --git a/Sources/Alert.php b/Sources/Alert.php
index 05a5aa1e3f..7109e25b47 100644
--- a/Sources/Alert.php
+++ b/Sources/Alert.php
@@ -20,29 +20,23 @@
*/
class Alert implements \ArrayAccess
{
- use BackwardCompatibility, ArrayAccessHelper;
+ use BackwardCompatibility;
+ use ArrayAccessHelper;
/**
* @var array
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
+ private static $backcompat = [
+ 'func_names' => [
'fetch' => 'fetch_alerts',
'count' => 'alert_count',
'mark' => 'alert_mark',
'delete' => 'alert_delete',
'purge' => 'alert_purge',
- 'create' => false,
- 'createBatch' => false,
- 'load' => false,
- 'loadForMember' => false,
- 'markAll' => false,
- 'markWhere' => false,
- 'deleteWhere' => false,
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -163,7 +157,7 @@ class Alert implements \ArrayAccess
*
* All loaded instances of this class.
*/
- public static array $loaded = array();
+ public static array $loaded = [];
/**
* @var array
@@ -176,28 +170,28 @@ class Alert implements \ArrayAccess
* 'link' and 'text' are the sprintf formats that will be used when
* $this->show_links is true or false, respectively.
*/
- public static $link_formats = array(
- 'msg_msg' => array(
- 'required' => array('content_subject', 'topic', 'msg'),
+ public static $link_formats = [
+ 'msg_msg' => [
+ 'required' => ['content_subject', 'topic', 'msg'],
'link' => '%1$s',
'text' => '%1$s',
- ),
- 'topic_msg' => array(
- 'required' => array('content_subject', 'topic', 'topic_suffix'),
+ ],
+ 'topic_msg' => [
+ 'required' => ['content_subject', 'topic', 'topic_suffix'],
'link' => '%1$s',
'text' => '%1$s',
- ),
- 'board_msg' => array(
- 'required' => array('board_name', 'board'),
+ ],
+ 'board_msg' => [
+ 'required' => ['board_name', 'board'],
'link' => '%1$s',
'text' => '%1$s',
- ),
- 'profile_msg' => array(
- 'required' => array('user_name', 'user_id'),
+ ],
+ 'profile_msg' => [
+ 'required' => ['user_name', 'user_id'],
'link' => '%1$s',
'text' => '%1$s',
- ),
- );
+ ],
+ ];
/*********************
* Internal properties
@@ -208,14 +202,14 @@ class Alert implements \ArrayAccess
*
* Alternate names for some object properties.
*/
- protected array $prop_aliases = array(
+ protected array $prop_aliases = [
'id_alert' => 'id',
'alert_time' => 'timestamp',
'id_member' => 'member',
'id_member_started' => 'member_started',
'sender_id' => 'member_started',
'sender_name' => 'member_name',
- );
+ ];
/****************************
* Internal static properties
@@ -226,7 +220,7 @@ class Alert implements \ArrayAccess
*
* The query_see_board data to use when checking access to content.
*/
- protected static array $qb = array();
+ protected static array $qb = [];
/**
* @var array
@@ -245,7 +239,7 @@ class Alert implements \ArrayAccess
* @param int $id The ID number of the alert.
* @param array $props Properties to set for this alert.
*/
- public function __construct(int $id = 0, array $props = array())
+ public function __construct(int $id = 0, array $props = [])
{
$this->set($props);
$this->id = $id;
@@ -254,25 +248,23 @@ public function __construct(int $id = 0, array $props = array())
$this->show_links = (bool) ($this->extra['show_links'] ?? false);
$this->initial_is_read = $this->is_read;
- if ($this->id === 0)
- {
- while (isset(self::$loaded[$this->id]))
+ if ($this->id === 0) {
+ while (isset(self::$loaded[$this->id])) {
$this->id--;
+ }
}
self::$loaded[$this->id] = $this;
- if (!isset($this->visible))
- {
- switch ($this->content_type)
- {
+ if (!isset($this->visible)) {
+ switch ($this->content_type) {
case 'msg':
- self::checkMsgAccess(array($this->id => $this->content_id), $this->member);
+ self::checkMsgAccess([$this->id => $this->content_id], $this->member);
break;
case 'topic':
case 'board':
- self::checkTopicAccess(array($this->id => $this->content_id), $this->member);
+ self::checkTopicAccess([$this->id => $this->content_id], $this->member);
break;
default:
@@ -281,8 +273,9 @@ public function __construct(int $id = 0, array $props = array())
}
// If not visible, remove from our static array.
- if (!$this->visible)
+ if (!$this->visible) {
unset(self::$loaded[$this->id]);
+ }
}
}
@@ -298,48 +291,48 @@ public function format(bool $with_avatar = false, bool $show_links = false): voi
Utils::$context['avatar_url'] = Config::$modSettings['avatar_url'];
Lang::load('Alerts');
- if (!$this->visible)
+ if (!$this->visible) {
return;
+ }
// Did a mod already take care of this one?
- if (!empty($this->text))
+ if (!empty($this->text)) {
return;
+ }
self::finalizeLinkFormats();
// Are we forcing show_links to be true?
- if ($show_links)
+ if ($show_links) {
$this->show_links = true;
+ }
// Make a nicely formatted version of the time.
$this->time = Time::create('@' . $this->timestamp)->format();
// Load the users we need.
User::load(
- array_filter(array(
+ array_filter([
$this->member_started,
$this->content_type === 'profile' ? $this->content_id : null,
- )),
+ ]),
User::LOAD_BY_ID,
- $with_avatar ? 'basic' : 'minimal'
+ $with_avatar ? 'basic' : 'minimal',
);
// The info in extra might outdated if the topic was moved, the message's subject was changed, etc.
- if (!empty($this->content_data))
- {
+ if (!empty($this->content_data)) {
$data = $this->content_data;
// Make sure msg, topic, and board info are correct.
- $patterns = array();
- $replacements = array();
- foreach (array('msg', 'topic', 'board') as $item)
- {
- if (isset($data['id_' . $item]))
- {
+ $patterns = [];
+ $replacements = [];
+
+ foreach (['msg', 'topic', 'board'] as $item) {
+ if (isset($data['id_' . $item])) {
$separator = $item == 'msg' ? '=?' : '=';
- if (isset($this->extra['content_link']) && strpos($this->extra['content_link'], $item . $separator) !== false && strpos($this->extra['content_link'], $item . $separator . $data['id_' . $item]) === false)
- {
+ if (isset($this->extra['content_link']) && strpos($this->extra['content_link'], $item . $separator) !== false && strpos($this->extra['content_link'], $item . $separator . $data['id_' . $item]) === false) {
$patterns[] = '/\b' . $item . $separator . '\d+/';
$replacements[] = $item . $separator . $data['id_' . $item];
}
@@ -347,80 +340,76 @@ public function format(bool $with_avatar = false, bool $show_links = false): voi
$this->extra[$item] = $data['id_' . $item];
}
}
- if (!empty($patterns))
+
+ if (!empty($patterns)) {
$this->extra['content_link'] = preg_replace($patterns, $replacements, $this->extra['content_link']);
+ }
// Make sure the subject is correct.
- if (isset($data['subject']))
+ if (isset($data['subject'])) {
$this->extra['content_subject'] = $data['subject'];
+ }
// Keep track of this so we can use it below.
- if (isset($data['board_name']))
+ if (isset($data['board_name'])) {
$this->extra['board_name'] = $data['board_name'];
+ }
unset($this->content_data);
}
// Do we want to link to the topic in general or the new messages specifically?
- if (in_array($this->content_type, array('topic', 'board')) && in_array($this->content_action, array('reply', 'topic', 'unapproved_reply')))
- {
+ if (in_array($this->content_type, ['topic', 'board']) && in_array($this->content_action, ['reply', 'topic', 'unapproved_reply'])) {
$this->extra['topic_suffix'] = 'new;topicseen#new';
- }
- elseif (isset($this->extra['topic']))
- {
+ } elseif (isset($this->extra['topic'])) {
$this->extra['topic_suffix'] = '0';
}
// Make sure profile alerts have what they need.
- if ($this->content_type === 'profile')
- {
- if (empty($this->extra['user_id']))
+ if ($this->content_type === 'profile') {
+ if (empty($this->extra['user_id'])) {
$this->extra['user_id'] = $this->content_id;
+ }
- if (isset(User::$loaded[$this->extra['user_id']]))
+ if (isset(User::$loaded[$this->extra['user_id']])) {
$this->extra['user_name'] = User::$loaded[$this->content_id]->name;
+ }
}
// If we loaded the sender's profile, we may as well use it.
- if (isset(User::$loaded[$this->member_started]))
- {
+ if (isset(User::$loaded[$this->member_started])) {
$this->member_name = User::$loaded[$this->member_started]->name;
// If requested, include the sender's avatar data.
- if ($with_avatar)
+ if ($with_avatar) {
$this->sender = User::$loaded[$this->member_started];
+ }
}
// Next, build the message strings.
- foreach (self::$link_formats as $msg_type => $format_info)
- {
+ foreach (self::$link_formats as $msg_type => $format_info) {
// Get the values to use in the formatted string, in the right order.
$msg_values = array_replace(
array_fill_keys($format_info['required'], ''),
- array_intersect_key($this->extra, array_flip($format_info['required']))
+ array_intersect_key($this->extra, array_flip($format_info['required'])),
);
// Assuming all required values are present, build the message.
- if (!in_array('', $msg_values))
- {
+ if (!in_array('', $msg_values)) {
$this->extra[$msg_type] = vsprintf(self::$link_formats[$msg_type][$this->show_links ? 'link' : 'text'], $msg_values);
- }
- elseif (in_array($msg_type, array('msg_msg', 'topic_msg', 'board_msg')))
- {
+ } elseif (in_array($msg_type, ['msg_msg', 'topic_msg', 'board_msg'])) {
$this->extra[$msg_type] = Lang::$txt[$msg_type == 'board_msg' ? 'board_na' : 'topic_na'];
- }
- else
- {
+ } else {
$this->extra[$msg_type] = '(' . Lang::$txt['not_applicable'] . ')';
}
}
// Show the formatted time in alerts about subscriptions.
- if ($this->content_type == 'paidsubs' && isset($this->extra['end_time']))
- {
+ if ($this->content_type == 'paidsubs' && isset($this->extra['end_time'])) {
// If the subscription already expired, say so.
- if ($this->extra['end_time'] < time())
+ if ($this->extra['end_time'] < time()) {
$this->content_action = 'expired';
+ }
// Present a nicely formatted date.
$this->extra['end_time'] = Time::create('@' . $this->extra['end_time'])->format();
@@ -430,20 +419,15 @@ public function format(bool $with_avatar = false, bool $show_links = false): voi
$this->target_href = '';
// Priority goes to explicitly specified links.
- if (isset($this->extra['content_link']))
- {
+ if (isset($this->extra['content_link'])) {
$this->target_href = $this->extra['content_link'];
- }
- elseif (isset($this->extra['report_link']))
- {
+ } elseif (isset($this->extra['report_link'])) {
$this->target_href = Config::$scripturl . $this->extra['report_link'];
}
// Next, try determining the link based on the content action.
- if (empty($this->target_href) && in_array($this->content_action, array('register_approval', 'group_request', 'buddy_request')))
- {
- switch ($this->content_action)
- {
+ if (empty($this->target_href) && in_array($this->content_action, ['register_approval', 'group_request', 'buddy_request'])) {
+ switch ($this->content_action) {
case 'register_approval':
$this->target_href = Config::$scripturl . '?action=admin;area=viewmembers;sa=browse;type=approve';
break;
@@ -453,8 +437,7 @@ public function format(bool $with_avatar = false, bool $show_links = false): voi
break;
case 'buddy_request':
- if (!empty($this->member_started))
- {
+ if (!empty($this->member_started)) {
$this->target_href = Config::$scripturl . '?action=profile;u=' . $this->member_started;
}
break;
@@ -465,27 +448,22 @@ public function format(bool $with_avatar = false, bool $show_links = false): voi
}
// Or maybe we can determine the link based on the content type.
- if (empty($this->target_href) && in_array($this->content_type, array('msg', 'member', 'event')))
- {
- switch ($this->content_type)
- {
+ if (empty($this->target_href) && in_array($this->content_type, ['msg', 'member', 'event'])) {
+ switch ($this->content_type) {
case 'msg':
- if (!empty($this->content_id))
- {
+ if (!empty($this->content_id)) {
$this->target_href = Config::$scripturl . '?msg=' . $this->content_id;
}
break;
case 'member':
- if (!empty($this->member_started))
- {
+ if (!empty($this->member_started)) {
$this->target_href = Config::$scripturl . '?action=profile;u=' . $this->member_started;
}
break;
case 'event':
- if (!empty($this->extra['event_id']))
- {
+ if (!empty($this->extra['event_id'])) {
$this->target_href = Config::$scripturl . '?action=calendar;event=' . $this->extra['event_id'];
}
break;
@@ -498,17 +476,16 @@ public function format(bool $with_avatar = false, bool $show_links = false): voi
// Finally, set this alert's text string.
$txt_key = 'alert_' . $this->content_type . '_' . $this->content_action;
- if (isset(Lang::$txt[$txt_key]))
- {
- $substitutions = array(
+ if (isset(Lang::$txt[$txt_key])) {
+ $substitutions = [
'{scripturl}' => Config::$scripturl,
'{member_link}' => !empty($this->member_started) && $this->show_links ? '' . $this->member_name . '' : '' . $this->member_name . '',
- );
+ ];
- if (is_array($this->extra))
- {
- foreach ($this->extra as $k => $v)
+ if (is_array($this->extra)) {
+ foreach ($this->extra as $k => $v) {
$substitutions['{' . $k . '}'] = $v;
+ }
}
$this->text = strtr(Lang::$txt[$txt_key], $substitutions);
@@ -524,15 +501,16 @@ public function format(bool $with_avatar = false, bool $show_links = false): voi
public function save(bool $update_count = true): void
{
// Don't save it if the member can't see it.
- if (empty($this->visible))
+ if (empty($this->visible)) {
return;
+ }
// Saving a new alert.
- if ($this->id <= 0)
- {
- $this->id = Db::$db->insert('',
+ if ($this->id <= 0) {
+ $this->id = Db::$db->insert(
+ '',
'{db_prefix}user_alerts',
- array(
+ [
'alert_time' => 'int',
'id_member' => 'int',
'id_member_started' => 'int',
@@ -542,8 +520,8 @@ public function save(bool $update_count = true): void
'content_action' => 'string',
'is_read' => 'int',
'extra' => 'string',
- ),
- array(
+ ],
+ [
$this->timestamp,
$this->member,
$this->member_started,
@@ -553,27 +531,26 @@ public function save(bool $update_count = true): void
$this->content_action,
0,
Utils::jsonEncode($this->extra),
- ),
- array('id_alert'),
- 1
+ ],
+ ['id_alert'],
+ 1,
);
// Update the keys in self::$loaded.
self::$loaded = array_combine(
- array_map(fn($alert) => $alert->id, self::$loaded),
- self::$loaded
+ array_map(fn ($alert) => $alert->id, self::$loaded),
+ self::$loaded,
);
- if ($update_count)
- {
- User::updateMemberData($this->member, array('alerts' => '+'));
+ if ($update_count) {
+ User::updateMemberData($this->member, ['alerts' => '+']);
}
}
// Updating an existing alert.
- else
- {
- Db::$db->query('', '
- UPDATE {db_prefix}user_alerts
+ else {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}user_alerts
SET
alert_time = {int:timestamp},
id_member = {int:member},
@@ -585,7 +562,7 @@ public function save(bool $update_count = true): void
is_read = {int:is_read},
extra = {string:extra}
WHERE id_alert = {int:id}',
- array(
+ [
'id' => $this->id,
'timestamp' => $this->timestamp,
'member' => $this->member,
@@ -596,13 +573,12 @@ public function save(bool $update_count = true): void
'content_action' => $this->content_action,
'is_read' => (int) $this->is_read,
'extra' => Utils::jsonEncode($this->extra),
- )
+ ],
);
// Has the is_read value changed since we loaded this alert?
- if ($update_count && $this->is_read !== $this->initial_is_read)
- {
- User::updateMemberData($this->member, array('alerts' => '+'));
+ if ($update_count && $this->is_read !== $this->initial_is_read) {
+ User::updateMemberData($this->member, ['alerts' => '+']);
}
}
}
@@ -615,8 +591,9 @@ public function save(bool $update_count = true): void
*/
public function __set(string $prop, $value): void
{
- if ($prop === 'extra')
+ if ($prop === 'extra') {
$value = (array) Utils::jsonDecode($value ?? '', true);
+ }
$this->customPropertySet($prop, $value);
}
@@ -631,10 +608,11 @@ public function __set(string $prop, $value): void
* @param array $props Properties to set for this alert.
* @return object An instance of this class.
*/
- public static function create(array $props = array()): object
+ public static function create(array $props = []): object
{
$alert = new self(0, $props);
$alert->save();
+
return $alert;
}
@@ -647,21 +625,19 @@ public static function create(array $props = array()): object
* @param array $props_batch Multiple sets of $props.
* @return array An array of instances of this class.
*/
- public static function createBatch(array $props_batch = array()): array
+ public static function createBatch(array $props_batch = []): array
{
- $created = array();
- $inserts = array();
- $members = array();
- $possible_msgs = array();
- $possible_topics = array();
+ $created = [];
+ $inserts = [];
+ $members = [];
+ $possible_msgs = [];
+ $possible_topics = [];
// First, weed out any alerts that wouldn't be visible.
- foreach ($props_batch as $props)
- {
+ foreach ($props_batch as &$props) {
$members[] = $props['id_member'];
- switch ($props['content_type'])
- {
+ switch ($props['content_type']) {
case 'msg':
$props['visible'] = false;
$props['simple_access_check'] = true;
@@ -683,34 +659,31 @@ public static function createBatch(array $props_batch = array()): array
$members = array_unique($members);
- foreach ($members as $memID)
- {
- foreach (array('checkMsgAccess' => 'possible_msgs', 'checkTopicAccess' => 'possible_topics') as $method => $variable)
- {
- $visibility = self::$method(${$variable}[$memID] ?? array(), $memID, true);
+ foreach ($members as $memID) {
+ foreach (['checkMsgAccess' => 'possible_msgs', 'checkTopicAccess' => 'possible_topics'] as $method => $variable) {
+ $visibility = self::$method(${$variable}[$memID] ?? [], $memID, true);
- if (!empty($visibility))
- {
- foreach ($props_batch as &$props)
- {
- if (isset($visibility[$props['id_alert']]))
+ if (!empty($visibility)) {
+ foreach ($props_batch as &$props) {
+ if (isset($visibility[$props['id_alert']])) {
$props['visible'] = $visibility[$props['id_alert']];
+ }
}
}
}
}
// Now create the alert objects and populate the database insert rows.
- foreach ($props_batch as $props)
- {
- if (!$props['visible'])
+ foreach ($props_batch as $props) {
+ if (!$props['visible']) {
continue;
+ }
$alert = new self(0, $props);
$created[$alert->id] = $alert;
- $inserts[$alert->id] = array(
+ $inserts[$alert->id] = [
$alert->timestamp,
$alert->member,
$alert->member_started,
@@ -720,13 +693,14 @@ public static function createBatch(array $props_batch = array()): array
$alert->content_action,
0,
Utils::jsonEncode($alert->extra),
- );
+ ];
}
// Insert the data into the database.
- $ids = Db::$db->insert('',
+ $ids = Db::$db->insert(
+ '',
'{db_prefix}user_alerts',
- array(
+ [
'alert_time' => 'int',
'id_member' => 'int',
'id_member_started' => 'int',
@@ -736,33 +710,34 @@ public static function createBatch(array $props_batch = array()): array
'content_action' => 'string',
'is_read' => 'int',
'extra' => 'string',
- ),
+ ],
$inserts,
- array('id_alert'),
- 2
+ ['id_alert'],
+ 2,
);
// Map our temp IDs to the real IDs.
$ids = array_combine(array_keys($inserts), $ids);
// Change the IDs in the alert objects themselves.
- foreach ($ids as $temp => $real)
+ foreach ($ids as $temp => $real) {
self::$loaded[$temp]->id = $real;
+ }
// Update the keys in self::$loaded.
self::$loaded = array_combine(
- array_map(fn($alert) => $alert->id, self::$loaded),
- self::$loaded
+ array_map(fn ($alert) => $alert->id, self::$loaded),
+ self::$loaded,
);
// Update the keys in $created.
$created = array_combine(
- array_map(fn($alert) => $alert->id, $created),
- $created
+ array_map(fn ($alert) => $alert->id, $created),
+ $created,
);
// Update the alert counts for the members.
- User::updateMemberData($members, array('alerts' => '+'));
+ User::updateMemberData($members, ['alerts' => '+']);
return $created;
}
@@ -777,45 +752,44 @@ public static function createBatch(array $props_batch = array()): array
* Default: false;
* @return array An array of instances of this class.
*/
- public static function load(int|array $ids = array(), array $query_customizations = array(), bool $simple_access_check = false): array
+ public static function load(int|array $ids = [], array $query_customizations = [], bool $simple_access_check = false): array
{
Lang::load('Alerts');
- $loaded = array();
- $possible_msgs = array();
- $possible_topics = array();
- $members = array();
+ $loaded = [];
+ $possible_msgs = [];
+ $possible_topics = [];
+ $members = [];
// Are we being asked for some specific alerts?
$ids = array_filter(array_map('intval', (array) $ids));
// Can't load anything without some sort of criteria.
- if ($ids === array() && $query_customizations === array())
- return array();
+ if ($ids === [] && $query_customizations === []) {
+ return [];
+ }
// Get the basic alert info.
- $selects = $query_customizations['selects'] ?? array('a.*');
- $joins = $query_customizations['joins'] ?? array();
- $where = $query_customizations['where'] ?? array();
- $order = $query_customizations['order'] ?? array('a.id_alert DESC');
+ $selects = $query_customizations['selects'] ?? ['a.*'];
+ $joins = $query_customizations['joins'] ?? [];
+ $where = $query_customizations['where'] ?? [];
+ $order = $query_customizations['order'] ?? ['a.id_alert DESC'];
+ $group = $query_customizations['group'] ?? [];
$limit = $query_customizations['limit'] ?? min(!empty(Config::$modSettings['alerts_per_page']) ? Config::$modSettings['alerts_per_page'] : 1000, 1000);
- $params = $query_customizations['params'] ?? array();
+ $params = $query_customizations['params'] ?? [];
- if (!empty($ids))
- {
+ if (!empty($ids)) {
$where[] = 'a.id_alert IN ({array_int:ids})';
$params['ids'] = $ids;
}
- foreach (self::queryData($selects, $params, $joins, $where, $order, $limit) as $row)
- {
+ foreach (self::queryData($selects, $params, $joins, $where, $order, $limit) as $row) {
$row['id_alert'] = (int) $row['id_alert'];
$members[] = (int) $row['id_member'];
// For some types, we need to check whether they can actually see the content.
- switch ($row['content_type'])
- {
+ switch ($row['content_type']) {
case 'msg':
$row['visible'] = false;
$row['simple_access_check'] = $simple_access_check;
@@ -837,10 +811,9 @@ public static function load(int|array $ids = array(), array $query_customization
$loaded[$row['id_alert']] = new self($row['id_alert'], $row);
}
- foreach (array_unique($members) as $memID)
- {
- self::checkMsgAccess($possible_msgs[$memID] ?? array(), $memID, $simple_access_check);
- self::checkTopicAccess($possible_topics[$memID] ?? array(), $memID, $simple_access_check);
+ foreach (array_unique($members) as $memID) {
+ self::checkMsgAccess($possible_msgs[$memID] ?? [], $memID, $simple_access_check);
+ self::checkTopicAccess($possible_topics[$memID] ?? [], $memID, $simple_access_check);
self::deleteInvisible($loaded, $memID);
}
@@ -861,39 +834,42 @@ public static function load(int|array $ids = array(), array $query_customization
*/
public static function loadForMember(int $memID, bool|array $to_fetch = false, int $limit = 0, int $offset = 0, bool $simple_access_check = false): array
{
- if (empty($memID))
- return array();
+ if (empty($memID)) {
+ return [];
+ }
- $loaded = array();
+ $loaded = [];
// We only want alerts for this member.
- $query_customizations = array(
- 'where' => array(
+ $query_customizations = [
+ 'where' => [
'a.id_member = {int:id_member}',
- ),
+ ],
'limit' => min(!empty($limit) ? $limit : (!empty(Config::$modSettings['alerts_per_page']) ? Config::$modSettings['alerts_per_page'] : 1000), 1000),
- 'params' => array(
+ 'params' => [
'id_member' => $memID,
- ),
- );
+ ],
+ ];
// False means get only the unread alerts.
- if ($to_fetch === false)
+ if ($to_fetch === false) {
$query_customizations['where'][] = 'a.is_read = 0';
+ }
// Are we being asked for some specific alerts?
- $ids = is_bool($to_fetch) ? array() : array_filter(array_map('intval', (array) $to_fetch));
+ $ids = is_bool($to_fetch) ? [] : array_filter(array_map('intval', (array) $to_fetch));
// Don't reload unnecessarily.
- foreach (self::$loaded as $alert)
- {
+ foreach (self::$loaded as $alert) {
// Ignore alerts that belong to a different member.
- if ($alert->member !== $memID)
+ if ($alert->member !== $memID) {
continue;
+ }
// Reload this alert if we need to redo the access check.
- if ((int) $simple_access_check < (int) ($alert->simple_access_check ?? 0))
+ if ((int) $simple_access_check < (int) ($alert->simple_access_check ?? 0)) {
continue;
+ }
// At this point, we can exclude this alert from the ones we need to load.
$loaded[$alert->id] = $alert;
@@ -901,8 +877,7 @@ public static function loadForMember(int $memID, bool|array $to_fetch = false, i
$ids = array_diff($ids, array_keys($loaded));
- if (!empty($loaded))
- {
+ if (!empty($loaded)) {
$query_customizations['where'][] = 'a.id_alert NOT IN ({array_int:already_loaded})';
$query_customizations['params']['already_loaded'] = array_keys($loaded);
}
@@ -910,8 +885,9 @@ public static function loadForMember(int $memID, bool|array $to_fetch = false, i
// Figure out the limit and offset.
$offset = !empty($ids) ? 0 : max(0, (int) $offset);
- if (!empty($offset))
+ if (!empty($offset)) {
$query_customizations['limit'] = $offset . ', ' . $query_customizations['limit'];
+ }
// Load the alerts we need.
$loaded += self::load($ids, $query_customizations);
@@ -948,19 +924,20 @@ public static function fetch(int $memID, bool|array $to_fetch = false, int $limi
// Hooks might want to do something snazzy with their own content types,
// including enforcing permissions if appropriate.
- IntegrationHook::call('integrate_fetch_alerts', array(&$loaded, &self::$link_formats));
+ IntegrationHook::call('integrate_fetch_alerts', [&$loaded, &self::$link_formats]);
// Did a hook remove some of the alerts we loaded?
- if ($loaded_ids !== array_keys($loaded))
- {
+ if ($loaded_ids !== array_keys($loaded)) {
// Remove those alerts from our static array as well.
- foreach (array_diff($loaded_ids, array_keys($loaded)) as $unloaded)
+ foreach (array_diff($loaded_ids, array_keys($loaded)) as $unloaded) {
unset(self::$loaded[$unloaded]);
+ }
}
// Prepare them for the templates.
- foreach ($loaded as $alert)
+ foreach ($loaded as $alert) {
$alert->format($with_avatar, $show_links);
+ }
return $loaded;
}
@@ -981,13 +958,14 @@ public static function count(int $memID, bool $unread = false): int
$count = 0;
- foreach (self::$loaded as $alert)
- {
- if ($alert->member !== $memID)
+ foreach (self::$loaded as $alert) {
+ if ($alert->member !== $memID) {
continue;
+ }
- if ($unread && $alert->is_read > 0)
+ if ($unread && $alert->is_read > 0) {
continue;
+ }
$count++;
}
@@ -1007,30 +985,32 @@ public static function mark(int|array $members, array|int $to_mark, bool $read):
$members = array_filter((array) $members);
$to_mark = array_filter((array) $to_mark);
- if (empty($to_mark) || empty($members))
+ if (empty($to_mark) || empty($members)) {
return;
+ }
$time = $read ? time() : 0;
- Db::$db->query('', '
- UPDATE {db_prefix}user_alerts
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}user_alerts
SET is_read = {int:read}
WHERE id_alert IN ({array_int:to_mark})',
- array(
+ [
'read' => $time,
'to_mark' => $to_mark,
- )
+ ],
);
// First, make sure that all the loaded alerts have the right value.
- foreach ($to_mark as $id)
- {
- if (isset(self::$loaded[$id]))
+ foreach ($to_mark as $id) {
+ if (isset(self::$loaded[$id])) {
self::$loaded[$id]->is_read = $time;
+ }
}
// Now update the members' alert counts in the database.
- User::updateMemberData($members, array('alerts' => $read ? '-' : '+'));
+ User::updateMemberData($members, ['alerts' => $read ? '-' : '+']);
}
/**
@@ -1043,34 +1023,35 @@ public static function markAll(int|array $members, bool $read): void
{
$members = array_filter((array) $members);
- if (empty($members))
+ if (empty($members)) {
return;
+ }
$time = $read ? time() : 0;
- Db::$db->query('', '
- UPDATE {db_prefix}user_alerts
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}user_alerts
SET is_read = {int:read}
WHERE id_member IN ({array_int:members})
AND {raw:condition}',
- array(
+ [
'read' => $time,
'members' => $members,
'condition' => $read ? 'is_read = 0' : 'is_read != 0',
- )
+ ],
);
- if (Db::$db->affected_rows() > 0)
- {
+ if (Db::$db->affected_rows() > 0) {
// First, make sure that all the loaded alerts have the right value.
- foreach (self::$loaded as $alert)
- {
- if (in_array($alert->member, $members) && (!$read || empty($alert->is_read)))
+ foreach (self::$loaded as $alert) {
+ if (in_array($alert->member, $members) && (!$read || empty($alert->is_read))) {
$alert->is_read = $time;
+ }
}
// Now update the members' alert counts in the database.
- User::updateMemberData($members, array('alerts' => $read ? 0 : '+'));
+ User::updateMemberData($members, ['alerts' => $read ? 0 : '+']);
}
}
@@ -1083,28 +1064,28 @@ public static function markAll(int|array $members, bool $read): void
*/
public static function markWhere(array $where, array $params, bool $read): void
{
- $ids = array();
- $members = array();
+ $ids = [];
+ $members = [];
- $selects = array('a.id_alert', 'a.id_member');
+ $selects = ['a.id_alert', 'a.id_member'];
// Do we need to add the condition for is_read status?
$has_read_condition = false;
- foreach ($where as &$condition)
- {
+ foreach ($where as &$condition) {
$condition = trim($condition);
- if (strpos($condition, 'is_read ') === 0)
+ if (strpos($condition, 'is_read ') === 0) {
$has_read_condition = true;
+ }
}
- if (!$has_read_condition)
+ if (!$has_read_condition) {
$where[] = 'is_read ' . ($read ? '' : '!') . '= 0';
+ }
// Find the alerts that match the conditions.
- foreach (self::queryData($selects, $params, array(), $where) as $row)
- {
+ foreach (self::queryData($selects, $params, [], $where) as $row) {
$ids[] = (int) $row['id_alert'];
$members[] = (int) $row['id_member'];
}
@@ -1118,27 +1099,30 @@ public static function markWhere(array $where, array $params, bool $read): void
* @param int|array $ids The IDs of one or more alerts.
* @param int|array $members Members whose alert counts should be updated.
*/
- public static function delete(int|array $ids, int|array $members = array()): void
+ public static function delete(int|array $ids, int|array $members = []): void
{
- if (empty($ids))
+ if (empty($ids)) {
return;
+ }
$ids = (array) $ids;
$members = (array) $members;
- Db::$db->query('', '
- DELETE FROM {db_prefix}user_alerts
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}user_alerts
WHERE id_alert IN ({array_int:ids})',
- array(
+ [
'ids' => $ids,
- )
+ ],
);
- foreach ($ids as $id)
+ foreach ($ids as $id) {
unset(self::$loaded[$id]);
+ }
// Gotta know how many unread alerts are left.
- User::updateMemberData($members, array('alerts' => '-'));
+ User::updateMemberData($members, ['alerts' => '-']);
}
/**
@@ -1154,15 +1138,16 @@ public static function purge(int $memID = 0, int $before = 0): void
$memID = !empty($memID) ? $memID : User::$me->id;
$before = $before > 0 ? $before : time();
- Db::$db->query('', '
- DELETE FROM {db_prefix}user_alerts
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}user_alerts
WHERE is_read > 0
AND is_read < {int:before}' . ($memID > 0 ? '
AND id_member = {int:memID}' : ''),
- array(
+ [
'before' => $before,
'memID' => $memID,
- )
+ ],
);
}
@@ -1175,14 +1160,13 @@ public static function purge(int $memID = 0, int $before = 0): void
*/
public static function deleteWhere(array $where, array $params): void
{
- $ids = array();
- $members = array();
+ $ids = [];
+ $members = [];
- $selects = array('a.id_alert', 'a.id_member');
+ $selects = ['a.id_alert', 'a.id_member'];
// Find the alerts that match the conditions.
- foreach (self::queryData($selects, $params, array(), $where) as $row)
- {
+ foreach (self::queryData($selects, $params, [], $where) as $row) {
$ids[] = (int) $row['id_alert'];
$members[] = (int) $row['id_member'];
}
@@ -1199,13 +1183,11 @@ public static function deleteWhere(array $where, array $params): void
*/
protected function setIcon(): void
{
- switch ($this->content_type)
- {
+ switch ($this->content_type) {
case 'topic':
case 'board':
{
- switch ($this->content_action)
- {
+ switch ($this->content_action) {
case 'reply':
case 'topic':
$class = 'main_icons posts';
@@ -1251,8 +1233,7 @@ protected function setIcon(): void
case 'msg':
{
- switch ($this->content_action)
- {
+ switch ($this->content_action) {
case 'like':
$class = 'main_icons like';
break;
@@ -1283,8 +1264,7 @@ protected function setIcon(): void
case 'member':
{
- switch ($this->content_action)
- {
+ switch ($this->content_action) {
case 'register_standard':
case 'register_approval':
case 'register_activation':
@@ -1332,20 +1312,15 @@ protected function setIcon(): void
break;
}
- if (isset($class))
- {
+ if (isset($class)) {
$this->icon = '';
- }
- elseif (isset($src))
- {
+ } elseif (isset($src)) {
$this->icon = '';
- }
- else
- {
+ } else {
$this->icon = '';
}
- IntegrationHook::call('integrate_alert_icon', array(&$this->icon, (array) $this));
+ IntegrationHook::call('integrate_alert_icon', [&$this->icon, (array) $this]);
}
/*************************
* Internal static methods
@@ -1356,18 +1331,18 @@ protected function setIcon(): void
*/
protected static function finalizeLinkFormats(): void
{
- if (self::$formats_finalized)
+ if (self::$formats_finalized) {
return;
+ }
self::$link_formats = array_map(
- function ($format)
- {
+ function ($format) {
$format['link'] = str_replace('{scripturl}', Config::$scripturl, $format['link']);
$format['text'] = str_replace('{scripturl}', Config::$scripturl, $format['text']);
return $format;
},
- self::$link_formats
+ self::$link_formats,
);
}
@@ -1386,15 +1361,13 @@ protected static function resetLinkFormats(): void
*/
protected static function setQb(int $memID): void
{
- if (!empty(self::$qb[$memID]))
+ if (!empty(self::$qb[$memID])) {
return;
+ }
- if ((User::$me->id ?? NAN) != $memID || !isset(User::$me->query_see_board))
- {
+ if ((User::$me->id ?? NAN) != $memID || !isset(User::$me->query_see_board)) {
self::$qb[$memID] = User::buildQueryBoard($memID);
- }
- else
- {
+ } else {
self::$qb[$memID]['query_see_board'] = '{query_see_board}';
self::$qb[$memID]['query_see_topic_board'] = '{query_see_topic_board}';
self::$qb[$memID]['query_see_message_board'] = '{query_see_message_board}';
@@ -1413,59 +1386,59 @@ protected static function setQb(int $memID): void
*/
protected static function checkMsgAccess(array $possible_msgs, int $memID, bool $simple = false): array
{
- if (empty($possible_msgs))
- return array();
+ if (empty($possible_msgs)) {
+ return [];
+ }
self::setQb($memID);
- $visibility = array();
- $flipped_msgs = array();
- foreach ($possible_msgs as $id_alert => $id_msg)
- {
+ $visibility = [];
+ $flipped_msgs = [];
+
+ foreach ($possible_msgs as $id_alert => $id_msg) {
$visibility[$id_alert] = false;
- if (!isset($flipped_msgs[$id_msg]))
- $flipped_msgs[$id_msg] = array();
+ if (!isset($flipped_msgs[$id_msg])) {
+ $flipped_msgs[$id_msg] = [];
+ }
$flipped_msgs[$id_msg][] = $id_alert;
}
- if ($simple)
- {
- $request = Db::$db->query('', '
- SELECT m.id_msg
+ if ($simple) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg
FROM {db_prefix}messages AS m
WHERE ' . self::$qb[$memID]['query_see_message_board'] . '
AND m.id_msg IN ({array_int:msgs})',
- array(
+ [
'msgs' => $possible_msgs,
- )
+ ],
);
- }
- else
- {
- $request = Db::$db->query('', '
- SELECT m.id_msg, m.id_topic, m.subject, b.id_board, b.name AS board_name
+ } else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg, m.id_topic, m.subject, b.id_board, b.name AS board_name
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}boards AS b ON (m.id_board = b.id_board)
WHERE m.id_msg IN ({array_int:msgs})
AND ' . self::$qb[$memID]['query_see_board'] . '
ORDER BY m.id_msg',
- array(
+ [
'msgs' => $possible_msgs,
- )
+ ],
);
}
- while ($row = Db::$db->fetch_assoc($request))
- {
- foreach ($flipped_msgs[$row['id_msg']] as $id_alert)
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ foreach ($flipped_msgs[$row['id_msg']] as $id_alert) {
$visibility[$id_alert] = true;
- if (isset(self::$loaded[$id_alert]))
- {
- if (!$simple)
+ if (isset(self::$loaded[$id_alert])) {
+ if (!$simple) {
self::$loaded[$id_alert]->content_data = $row;
+ }
self::$loaded[$id_alert]->visible = true;
}
@@ -1479,68 +1452,68 @@ protected static function checkMsgAccess(array $possible_msgs, int $memID, bool
/**
* Checks whether a member can see the topics that some alerts refer to.
*
- * @param array $possible_msgs Key-value pairs of alert IDs and topic IDs.
* @param int $memID ID of the member.
* @param bool $simple If true, do nothing beyond checking the access.
* If false, also get some info about the topic in question.
* Default: false.
+ * @param array $possible_msgs Key-value pairs of alert IDs and topic IDs.
* @return array Key-value pairs of alert IDs and visibility status.
*/
protected static function checkTopicAccess($possible_topics, int $memID, bool $simple = false): array
{
- if (empty($possible_topics))
- return array();
+ if (empty($possible_topics)) {
+ return [];
+ }
self::setQb($memID);
- $visibility = array();
- $flipped_topics = array();
- foreach ($possible_topics as $id_alert => $id_topic)
- {
+ $visibility = [];
+ $flipped_topics = [];
+
+ foreach ($possible_topics as $id_alert => $id_topic) {
$visibility[$id_alert] = false;
- if (!isset($flipped_topics[$id_topic]))
- $flipped_topics[$id_topic] = array();
+ if (!isset($flipped_topics[$id_topic])) {
+ $flipped_topics[$id_topic] = [];
+ }
$flipped_topics[$id_topic][] = $id_alert;
}
- if ($simple)
- {
- $request = Db::$db->query('', '
- SELECT t.id_topic
+ if ($simple) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT t.id_topic
FROM {db_prefix}topics AS t
WHERE ' . self::$qb[$memID]['query_see_topic_board'] . '
AND t.id_topic IN ({array_int:topics})',
- array(
+ [
'topics' => $possible_topics,
- )
+ ],
);
- }
- else
- {
- $request = Db::$db->query('', '
- SELECT m.id_msg, t.id_topic, m.subject, b.id_board, b.name AS board_name
+ } else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg, t.id_topic, m.subject, b.id_board, b.name AS board_name
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (t.id_first_msg = m.id_msg)
INNER JOIN {db_prefix}boards AS b ON (t.id_board = b.id_board)
WHERE t.id_topic IN ({array_int:topics})
AND ' . self::$qb[$memID]['query_see_board'],
- array(
+ [
'topics' => $possible_topics,
- )
+ ],
);
}
- while ($row = Db::$db->fetch_assoc($request))
- {
- foreach ($flipped_topics[$row['id_topic']] as $id_alert)
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ foreach ($flipped_topics[$row['id_topic']] as $id_alert) {
$visibility[$id_alert] = true;
- if (isset(self::$loaded[$id_alert]))
- {
- if (!$simple)
+ if (isset(self::$loaded[$id_alert])) {
+ if (!$simple) {
self::$loaded[$id_alert]->content_data = $row;
+ }
self::$loaded[$id_alert]->visible = true;
}
@@ -1560,19 +1533,19 @@ protected static function checkTopicAccess($possible_topics, int $memID, bool $s
*/
protected static function deleteInvisible(array &$alerts, int $memID): void
{
- $deletes = array();
+ $deletes = [];
$num_unread_deletes = 0;
- foreach ($alerts as $id_alert => $alert)
- {
+ foreach ($alerts as $id_alert => $alert) {
// Only act on the ones that belong to the given member.
- if ($memID !== $alert->member)
+ if ($memID !== $alert->member) {
continue;
+ }
- if (!$alert->visible)
- {
- if (!$alert->is_read)
+ if (!$alert->visible) {
+ if (!$alert->is_read) {
$num_unread_deletes++;
+ }
unset($alerts[$id_alert], self::$loaded[$id_alert]);
$deletes[] = $id_alert;
@@ -1582,29 +1555,29 @@ protected static function deleteInvisible(array &$alerts, int $memID): void
// Delete these orphaned, invisible alerts, otherwise they might hang around forever.
// This can happen if they are deleted or moved to a board this user cannot access.
// Note that unread alerts are never purged.
- if (!empty($deletes))
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}user_alerts
+ if (!empty($deletes)) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}user_alerts
WHERE id_alert IN ({array_int:alerts})',
- array(
+ [
'alerts' => $deletes,
- )
+ ],
);
}
// One last thing: tweak counter on member record.
// Do it directly to avoid creating a loop in User::updateMemberData().
- if ($num_unread_deletes > 0)
- {
- Db::$db->query('', '
- UPDATE {db_prefix}members
+ if ($num_unread_deletes > 0) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}members
SET alerts = GREATEST({int:unread_deletes}, alerts) - {int:unread_deletes}
WHERE id_member = {int:member}',
- array(
+ [
'unread_deletes' => $num_unread_deletes,
'member' => $memID,
- )
+ ],
);
}
}
@@ -1622,25 +1595,29 @@ protected static function deleteInvisible(array &$alerts, int $memID): void
* If this is left empty, no WHERE clause will be used.
* @param array $order Zero or more conditions for the ORDER BY clause.
* If this is left empty, no ORDER BY clause will be used.
+ * @param array $group Zero or more conditions for the GROUP BY clause.
+ * If this is left empty, no GROUP BY clause will be used.
* @param int|string $limit Maximum number of results to retrieve.
* If this is left empty, all results will be retrieved.
*
* @return Generator Iterating over the result gives database rows.
*/
- protected static function queryData(array $selects, array $params = array(), array $joins = array(), array $where = array(), array $order = array(), int|string $limit = 0)
+ protected static function queryData(array $selects, array $params = [], array $joins = [], array $where = [], array $order = [], array $group = [], int|string $limit = 0)
{
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
' . implode(', ', $selects) . '
FROM {db_prefix}user_alerts AS a' . (empty($joins) ? '' : '
' . implode("\n\t\t\t\t", $joins)) . (empty($where) ? '' : '
- WHERE (' . implode(') AND (', $where) . ')') . (empty($order) ? '' : '
+ WHERE (' . implode(') AND (', $where) . ')') . (empty($group) ? '' : '
+ GROUP BY ' . implode(', ', $group)) . (empty($order) ? '' : '
ORDER BY ' . implode(', ', $order)) . (!empty($limit) ? '
LIMIT ' . $limit : ''),
- $params
+ $params,
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
yield $row;
}
Db::$db->free_result($request);
@@ -1648,7 +1625,8 @@ protected static function queryData(array $selects, array $params = array(), arr
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Alert::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Alert::exportStatic')) {
Alert::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Attachment.php b/Sources/Attachment.php
index bbe7fc712a..ab02a559c2 100644
--- a/Sources/Attachment.php
+++ b/Sources/Attachment.php
@@ -14,7 +14,6 @@
namespace SMF;
use SMF\Actions\Admin\ACP;
-use SMF\Cache\CacheApi;
use SMF\Db\DatabaseApi as Db;
use SMF\Graphics\Image;
@@ -26,18 +25,16 @@
*/
class Attachment implements \ArrayAccess
{
- use BackwardCompatibility, ArrayAccessHelper;
+ use BackwardCompatibility;
+ use ArrayAccessHelper;
/**
* @var array
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'load' => false,
- 'loadByMsg' => false,
- 'loadByMember' => false,
+ private static $backcompat = [
+ 'func_names' => [
'automanageCheckDirectory' => 'automanage_attachments_check_directory',
'automanageCreateDirectory' => 'automanage_attachments_create_directory',
'automanageBySpace' => 'automanage_attachments_by_space',
@@ -45,24 +42,30 @@ class Attachment implements \ArrayAccess
'check' => 'attachmentChecks',
'create' => 'createAttachment',
'assign' => 'assignAttachments',
- 'prepareByMsg' => 'prepareAttachsByMsg',
'approve' => 'ApproveAttachments',
'remove' => 'removeAttachments',
- ),
- );
+ 'parseAttachBBC' => 'parseAttachBBC',
+ 'getAttachMsgInfo' => 'getAttachMsgInfo',
+ 'loadAttachmentContext' => 'loadAttachmentContext',
+ 'prepareByMsg' => 'prepareAttachsByMsg',
+ 'createHash' => 'createHash',
+ 'getFilePath' => 'getFilePath',
+ 'getAttachmentFilename' => 'getAttachmentFilename',
+ ],
+ ];
/*****************
* Class constants
*****************/
- const APPROVED_ANY = -1;
- const APPROVED_FALSE = 0;
- const APPROVED_TRUE = 1;
+ public const APPROVED_ANY = -1;
+ public const APPROVED_FALSE = 0;
+ public const APPROVED_TRUE = 1;
- const TYPE_ANY = -1;
- const TYPE_STANDARD = 0;
- const TYPE_AVATAR = 1;
- const TYPE_THUMB = 3;
+ public const TYPE_ANY = -1;
+ public const TYPE_STANDARD = 0;
+ public const TYPE_AVATAR = 1;
+ public const TYPE_THUMB = 3;
/*******************
* Public properties
@@ -288,21 +291,21 @@ class Attachment implements \ArrayAccess
*
* All loaded instances of this class.
*/
- public static array $loaded = array();
+ public static array $loaded = [];
/**
* @var array
*
* Loaded instances of this class, grouped by message.
*/
- public static array $loadedByMsg = array();
+ public static array $loadedByMsg = [];
/**
* @var array
*
* Loaded instances of this class, grouped by member.
*/
- public static array $loadedByMember = array();
+ public static array $loadedByMember = [];
/*********************
* Internal properties
@@ -313,7 +316,7 @@ class Attachment implements \ArrayAccess
*
* Alternate names for some object properties.
*/
- protected array $prop_aliases = array(
+ protected array $prop_aliases = [
'id_attach' => 'id',
'attachID' => 'id',
'id_thumb' => 'thumb',
@@ -328,7 +331,7 @@ class Attachment implements \ArrayAccess
'filesize' => 'size',
'byte_size' => 'size',
'filePath' => 'path',
- );
+ ];
/****************
* Public methods
@@ -341,26 +344,28 @@ class Attachment implements \ArrayAccess
* @param array $props Properties to set for this attachment.
* @return object An instance of this class.
*/
- public function __construct(int $id = 0, array $props = array())
+ public function __construct(int $id = 0, array $props = [])
{
- if (empty($id) && empty($props))
+ if (empty($id) && empty($props)) {
return;
+ }
// Given an ID but no properties, so query for the data.
- if (!empty($id) && empty($props))
- {
- $request = Db::$db->query('', '
- SELECT *
+ if (!empty($id) && empty($props)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT *
FROM {db_prefix}attachments
WHERE id_attach = {int:id}
LIMIT 1',
- array(
+ [
'id' => $this->id,
- )
+ ],
);
- if (Db::$db->num_rows($request) !== 1)
- {
+
+ if (Db::$db->num_rows($request) !== 1) {
Db::$db->free_result($request);
+
return;
}
$props = Db::$db->fetch_assoc($request);
@@ -373,8 +378,7 @@ public function __construct(int $id = 0, array $props = array())
// Is this an image attachment?
$image = new Image($this->path);
- if (!empty($image->source))
- {
+ if (!empty($image->source)) {
$this->is_image = true;
$this->mime_type = $image->mime_type;
$this->width = $image->width;
@@ -385,12 +389,12 @@ public function __construct(int $id = 0, array $props = array())
unset($image);
// If we still don't have a MIME type, get it now.
- if (empty($this->mime_type))
+ if (empty($this->mime_type)) {
$this->mime_type = Utils::getMimeType($this->path, true);
+ }
// SVGs are special.
- if ($this->mime_type === 'image/svg+xml')
- {
+ if ($this->mime_type === 'image/svg+xml') {
// SVG is its own thumbnail.
$this->thumb = $id;
@@ -399,16 +403,18 @@ public function __construct(int $id = 0, array $props = array())
$this->thumb_height = min($this->height, !empty(Config::$modSettings['attachmentThumbHeight']) ? Config::$modSettings['attachmentThumbHeight'] : 1000);
// Must set the thumbnail's CSS dimensions manually.
- addInlineCss('img#thumb_' . $this->thumb . ':not(.original_size) {width: ' . $this->thumb_width . 'px; height: ' . $this->thumb_height . 'px;}');
+ Theme::addInlineCss('img#thumb_' . $this->thumb . ':not(.original_size) {width: ' . $this->thumb_width . 'px; height: ' . $this->thumb_height . 'px;}');
}
self::$loaded[$id] = $this;
- if (!empty($this->msg))
+ if (!empty($this->msg)) {
self::$loadedByMsg[$this->msg][$id] = $this;
+ }
- if (!empty($this->member))
+ if (!empty($this->member)) {
self::$loadedByMember[$this->member][$id] = $this;
+ }
}
/**
@@ -416,21 +422,23 @@ public function __construct(int $id = 0, array $props = array())
*/
public function setFileProperties(): void
{
- if (!isset($this->path))
+ if (!isset($this->path)) {
$this->setPath();
+ }
- if (!isset($this->path))
+ if (!isset($this->path)) {
return;
+ }
$this->exists = file_exists($this->path);
// Ensure variant attachment compatibility.
- if (!$this->exists)
- {
+ if (!$this->exists) {
$pathinfo = pathinfo($this->path);
- if (isset($pathinfo['extension']))
+ if (isset($pathinfo['extension'])) {
$this->path = substr($this->path, 0, -(strlen($pathinfo['extension']) + 1));
+ }
$this->exists = file_exists($this->path);
}
@@ -452,17 +460,16 @@ public function __set(string $prop, $value): void
$this->href = Config::$scripturl . '?action=dlattach;attach=' . $this->id;
- if (in_array($this->prop_aliases[$prop] ?? $prop, array('id', 'file_hash', 'folder')))
+ if (in_array($this->prop_aliases[$prop] ?? $prop, ['id', 'file_hash', 'folder'])) {
$this->setPath();
+ }
- if (($this->prop_aliases[$prop] ?? $prop) === 'filename')
- {
+ if (($this->prop_aliases[$prop] ?? $prop) === 'filename') {
$this->name = Utils::htmlspecialchars($value);
$this->link = '' . $this->name . '';
}
- if (($this->prop_aliases[$prop] ?? $prop) === 'size')
- {
+ if (($this->prop_aliases[$prop] ?? $prop) === 'size') {
Lang::load('index');
$this->formatted_size = ($this->size < 1024000) ? round($this->size / 1024, 2) . ' ' . Lang::$txt['kilobyte'] : round($this->size / 1024 / 1024, 2) . ' ' . Lang::$txt['megabyte'];
@@ -488,66 +495,60 @@ public function __set(string $prop, $value): void
public static function load(array|int $ids, int $approval_status = self::APPROVED_ANY, int $type = self::TYPE_ANY, bool $get_thumbs = true): array
{
// Keep track of the ones we load during this call.
- $loaded = array();
+ $loaded = [];
$ids = array_filter(array_map('intval', (array) $ids));
- $approval_status = !in_array($approval_status, array(self::APPROVED_TRUE, self::APPROVED_FALSE)) ? self::APPROVED_ANY : $approval_status;
+ $approval_status = !in_array($approval_status, [self::APPROVED_TRUE, self::APPROVED_FALSE]) ? self::APPROVED_ANY : $approval_status;
- if (empty($ids))
+ if (empty($ids)) {
return $loaded;
+ }
// Don't reload unnecessarily.
- foreach ($ids as $key => $id)
- {
- if (isset(self::$loaded[$id]))
- {
+ foreach ($ids as $key => $id) {
+ if (isset(self::$loaded[$id])) {
$loaded[$id] = self::$loaded[$id];
unset($ids[$key]);
}
}
// Load whatever hasn't been loaded already.
- if (!empty($ids))
- {
- $selects = array(
+ if (!empty($ids)) {
+ $selects = [
'a.*',
'COALESCE (m.id_topic, 0) AS id_topic',
'COALESCE (m.id_board, 0) AS id_board',
- );
+ ];
$from = '{db_prefix}attachments AS a';
- $joins = array('LEFT JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)');
- $where = array('a.id_attach IN ({array_int:ids})');
- $order = array();
+ $joins = ['LEFT JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)'];
+ $where = ['a.id_attach IN ({array_int:ids})'];
+ $order = [];
$limit = 0;
- $params = array('ids' => $ids);
+ $params = ['ids' => $ids];
- if ($type !== self::TYPE_ANY)
- {
+ if ($type !== self::TYPE_ANY) {
$where[] = 'a.attachment_type = {int:type}';
$params['type'] = $type;
}
- if ($approval_status !== self::APPROVED_ANY)
- {
+ if ($approval_status !== self::APPROVED_ANY) {
$where[] = 'a.approved = {int:approved}';
$params['approved'] = $approval_status;
}
- if ($get_thumbs)
- {
+ if ($get_thumbs) {
$selects[] = 'thumb.width AS thumb_width';
$selects[] = 'thumb.height AS thumb_height';
$joins[] = 'LEFT JOIN {db_prefix}attachments AS thumb ON (a.id_thumb = thumb.id_attach)';
}
- IntegrationHook::call('integrate_attachment_load', array(&$selects, &$params, &$from, &$joins, &$where, &$order, &$limit));
+ IntegrationHook::call('integrate_attachment_load', [&$selects, &$params, &$from, &$joins, &$where, &$order, &$limit]);
- foreach (self::queryData($selects, $params, $from, $joins, $where, $order, $limit) as $props)
- {
+ foreach (self::queryData($selects, $params, $from, $joins, $where, $order, $limit) as $props) {
$id = (int) $props['id_attach'];
- $props = array_filter($props, fn($prop) => !is_null($prop));
+ $props = array_filter($props, fn ($prop) => !is_null($prop));
$loaded[$id] = new self($id, $props);
}
@@ -574,61 +575,55 @@ public static function load(array|int $ids, int $approval_status = self::APPROVE
*/
public static function loadByMsg(array|int $msgs, int $approval_status = self::APPROVED_TRUE, int $type = self::TYPE_STANDARD, bool $get_thumbs = true): array
{
- $loaded = array();
+ $loaded = [];
$msgs = array_filter(array_map('intval', (array) $msgs));
- $approval_status = !in_array($approval_status, array(self::APPROVED_TRUE, self::APPROVED_FALSE)) ? self::APPROVED_ANY : $approval_status;
+ $approval_status = !in_array($approval_status, [self::APPROVED_TRUE, self::APPROVED_FALSE]) ? self::APPROVED_ANY : $approval_status;
- if (empty($msgs))
+ if (empty($msgs)) {
return $loaded;
+ }
- $selects = array(
+ $selects = [
'a.*',
'm.id_topic',
- 'm.id_board'
- );
+ 'm.id_board',
+ ];
$from = '{db_prefix}attachments AS a';
- $joins = array('INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)');
- $where = array('a.id_msg IN ({array_int:msgs})');
- $order = array();
+ $joins = ['INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)'];
+ $where = ['a.id_msg IN ({array_int:msgs})'];
+ $order = [];
$limit = 0;
- $params = array('msgs' => $msgs);
+ $params = ['msgs' => $msgs];
- if ($type !== self::TYPE_ANY)
- {
+ if ($type !== self::TYPE_ANY) {
$where[] = 'a.attachment_type = {int:type}';
$params['type'] = $type;
}
- if ($approval_status !== self::APPROVED_ANY)
- {
+ if ($approval_status !== self::APPROVED_ANY) {
$where[] = 'a.approved = {int:approved}';
$params['approved'] = $approval_status;
}
- if ($get_thumbs)
- {
+ if ($get_thumbs) {
$selects[] = 'thumb.width AS thumb_width';
$selects[] = 'thumb.height AS thumb_height';
$joins[] = 'LEFT JOIN {db_prefix}attachments AS thumb ON (a.id_thumb = thumb.id_attach)';
}
- IntegrationHook::call('integrate_attachment_loadbymsg', array(&$selects, &$params, &$from, &$joins, &$where, &$order, &$limit));
+ IntegrationHook::call('integrate_attachment_loadbymsg', [&$selects, &$params, &$from, &$joins, &$where, &$order, &$limit]);
- foreach (self::queryData($selects, $params, $from, $joins, $where, $order, $limit) as $props)
- {
+ foreach (self::queryData($selects, $params, $from, $joins, $where, $order, $limit) as $props) {
$id = (int) $props['id_attach'];
- $props = array_filter($props, fn($prop) => !is_null($prop));
+ $props = array_filter($props, fn ($prop) => !is_null($prop));
// Don't reload unnecessarily.
- if (isset(self::$loaded[$id]))
- {
+ if (isset(self::$loaded[$id])) {
$loaded[$id] = self::$loaded[$id];
- }
- else
- {
+ } else {
$loaded[$id] = new self($id, $props);
}
}
@@ -641,59 +636,54 @@ public static function loadByMsg(array|int $msgs, int $approval_status = self::A
/**
* Loads existing attachments by member ID.
*
- * @param array|int $ids The ID numbers of one or more members.
* @param int $approval_status One of this class's APPROVED_* constants.
* Default: self::APPROVED_TRUE.
* @param bool $get_thumbs Whether to get the thumbnail image dimensions.
* Default: true.
+ * @param array|int $ids The ID numbers of one or more members.
* @return array Instances of this class for the loaded attachments.
*/
public static function loadByMember(array|int $members, int $approval_status = self::APPROVED_TRUE, bool $get_thumbs = true): array
{
- $loaded = array();
+ $loaded = [];
$members = array_filter(array_map('intval', (array) $members));
- $approval_status = !in_array($approval_status, array(self::APPROVED_TRUE, self::APPROVED_FALSE)) ? self::APPROVED_ANY : $approval_status;
+ $approval_status = !in_array($approval_status, [self::APPROVED_TRUE, self::APPROVED_FALSE]) ? self::APPROVED_ANY : $approval_status;
- if (empty($members))
+ if (empty($members)) {
return $loaded;
+ }
- $selects = array('a.*');
+ $selects = ['a.*'];
$from = '{db_prefix}attachments AS a';
- $joins = array();
- $where = array('a.id_member IN ({array_int:members})');
- $order = array();
+ $joins = [];
+ $where = ['a.id_member IN ({array_int:members})'];
+ $order = [];
$limit = 0;
- $params = array('members' => $members);
+ $params = ['members' => $members];
- if ($approval_status !== self::APPROVED_ANY)
- {
+ if ($approval_status !== self::APPROVED_ANY) {
$where[] = 'a.approved = {int:approved}';
$params['approved'] = $approval_status;
}
- if ($get_thumbs)
- {
+ if ($get_thumbs) {
$selects[] = 'thumb.width AS thumb_width';
$selects[] = 'thumb.height AS thumb_height';
$joins[] = 'LEFT JOIN {db_prefix}attachments AS thumb ON (a.id_thumb = thumb.id_attach)';
}
- IntegrationHook::call('integrate_attachment_loadbymember', array(&$selects, &$params, &$from, &$joins, &$where, &$order, &$limit));
+ IntegrationHook::call('integrate_attachment_loadbymember', [&$selects, &$params, &$from, &$joins, &$where, &$order, &$limit]);
- foreach (self::queryData($selects, $params, $from, $joins, $where, $order, $limit) as $props)
- {
+ foreach (self::queryData($selects, $params, $from, $joins, $where, $order, $limit) as $props) {
$id = (int) $props['id_attach'];
- $props = array_filter($props, fn($prop) => !is_null($prop));
+ $props = array_filter($props, fn ($prop) => !is_null($prop));
// Don't reload unnecessarily.
- if (isset(self::$loaded[$id]))
- {
+ if (isset(self::$loaded[$id])) {
$loaded[$id] = self::$loaded[$id];
- }
- else
- {
+ } else {
$loaded[$id] = new self($id, $props);
}
}
@@ -712,30 +702,24 @@ public static function loadByMember(array|int $members, int $approval_status = s
public static function automanageCheckDirectory()
{
// Not pretty, but since we don't want folders created for every post. It'll do unless a better solution can be found.
- if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'admin')
- {
+ if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'admin') {
$doit = true;
- }
- elseif (empty(Config::$modSettings['automanage_attachments']) || !isset($_FILES))
- {
+ } elseif (empty(Config::$modSettings['automanage_attachments']) || !isset($_FILES)) {
$doit = false;
- }
- elseif (isset($_FILES['attachment']))
- {
+ } elseif (isset($_FILES['attachment'])) {
$doit = false;
- foreach ($_FILES['attachment']['tmp_name'] as $dummy)
- {
- if (!empty($dummy))
- {
+ foreach ($_FILES['attachment']['tmp_name'] as $dummy) {
+ if (!empty($dummy)) {
$doit = true;
break;
}
}
}
- if (!$doit)
+ if (!$doit) {
return;
+ }
$year = date('Y');
$month = date('m');
@@ -744,42 +728,39 @@ public static function automanageCheckDirectory()
$rand1 = $rand[1];
$rand = $rand[0];
- if (!empty(Config::$modSettings['attachment_basedirectories']) && !empty(Config::$modSettings['use_subdirectories_for_attachments']))
- {
- if (!is_array(Config::$modSettings['attachment_basedirectories']))
- {
+ if (!empty(Config::$modSettings['attachment_basedirectories']) && !empty(Config::$modSettings['use_subdirectories_for_attachments'])) {
+ if (!is_array(Config::$modSettings['attachment_basedirectories'])) {
Config::$modSettings['attachment_basedirectories'] = Utils::jsonDecode(Config::$modSettings['attachment_basedirectories'], true);
}
$base_dir = array_search(Config::$modSettings['basedirectory_for_attachments'], Config::$modSettings['attachment_basedirectories']);
- }
- else
- {
+ } else {
$base_dir = 0;
}
- if (Config::$modSettings['automanage_attachments'] == 1)
- {
- if (!isset(Config::$modSettings['last_attachments_directory']))
- Config::$modSettings['last_attachments_directory'] = array();
+ if (Config::$modSettings['automanage_attachments'] == 1) {
+ if (!isset(Config::$modSettings['last_attachments_directory'])) {
+ Config::$modSettings['last_attachments_directory'] = [];
+ }
- 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);
+ }
- if (!isset(Config::$modSettings['last_attachments_directory'][$base_dir]))
+ if (!isset(Config::$modSettings['last_attachments_directory'][$base_dir])) {
Config::$modSettings['last_attachments_directory'][$base_dir] = 0;
+ }
}
$basedirectory = (!empty(Config::$modSettings['use_subdirectories_for_attachments']) ? (Config::$modSettings['basedirectory_for_attachments']) : Config::$boarddir);
- //Just to be sure: I don't want directory separators at the end
- $sep = (DIRECTORY_SEPARATOR === '\\') ? '\/' : DIRECTORY_SEPARATOR;
+ // Just to be sure: I don't want directory separators at the end
+ $sep = (DIRECTORY_SEPARATOR === '\\') ? '\\/' : DIRECTORY_SEPARATOR;
$basedirectory = rtrim($basedirectory, $sep);
- switch (Config::$modSettings['automanage_attachments'])
- {
+ switch (Config::$modSettings['automanage_attachments']) {
case 1:
- $updir = $basedirectory . DIRECTORY_SEPARATOR . 'attachments_' . (isset(Config::$modSettings['last_attachments_directory'][$base_dir]) ? Config::$modSettings['last_attachments_directory'][$base_dir] : 0);
+ $updir = $basedirectory . DIRECTORY_SEPARATOR . 'attachments_' . (Config::$modSettings['last_attachments_directory'][$base_dir] ?? 0);
break;
case 2:
@@ -798,32 +779,27 @@ public static function automanageCheckDirectory()
$updir = $basedirectory . DIRECTORY_SEPARATOR . (empty(Config::$modSettings['use_subdirectories_for_attachments']) ? 'attachments-' : 'random_') . $rand . DIRECTORY_SEPARATOR . $rand1;
break;
- default :
+ default:
$updir = '';
}
- if (!is_array(Config::$modSettings['attachmentUploadDir']))
- {
+ if (!is_array(Config::$modSettings['attachmentUploadDir'])) {
Config::$modSettings['attachmentUploadDir'] = Utils::jsonDecode(Config::$modSettings['attachmentUploadDir'], true);
}
- if (!in_array($updir, Config::$modSettings['attachmentUploadDir']) && !empty($updir))
- {
+ if (!in_array($updir, Config::$modSettings['attachmentUploadDir']) && !empty($updir)) {
$outputCreation = self::automanageCreateDirectory($updir);
- }
- elseif (in_array($updir, Config::$modSettings['attachmentUploadDir']))
- {
+ } elseif (in_array($updir, Config::$modSettings['attachmentUploadDir'])) {
$outputCreation = true;
}
- if ($outputCreation)
- {
+ if ($outputCreation) {
Config::$modSettings['currentAttachmentUploadDir'] = array_search($updir, Config::$modSettings['attachmentUploadDir']);
Utils::$context['attach_dir'] = Config::$modSettings['attachmentUploadDir'][Config::$modSettings['currentAttachmentUploadDir']];
- Config::updateModSettings(array(
+ Config::updateModSettings([
'currentAttachmentUploadDir' => Config::$modSettings['currentAttachmentUploadDir'],
- ));
+ ]);
}
return $outputCreation;
@@ -842,27 +818,26 @@ public static function automanageCreateDirectory($updir)
$count = count($tree);
$directory = self::initDir($tree, $count);
- if ($directory === false)
- {
+
+ if ($directory === false) {
// Maybe it's just the folder name
$tree = self::getDirectoryTreeElements(Config::$boarddir . DIRECTORY_SEPARATOR . $updir);
$count = count($tree);
$directory = self::initDir($tree, $count);
- if ($directory === false)
+ if ($directory === false) {
return false;
+ }
}
$directory .= DIRECTORY_SEPARATOR . array_shift($tree);
- while ($count != -1)
- {
- if (self::isPathAllowed($directory) && !@is_dir($directory))
- {
- if (!@mkdir($directory, 0755))
- {
+ while ($count != -1) {
+ if (self::isPathAllowed($directory) && !@is_dir($directory)) {
+ if (!@mkdir($directory, 0755)) {
Utils::$context['dir_creation_error'] = 'attachments_no_create';
+
return false;
}
}
@@ -872,30 +847,30 @@ public static function automanageCreateDirectory($updir)
}
// Check if the dir is writable.
- if (!Utils::makeWritable($directory))
- {
+ if (!Utils::makeWritable($directory)) {
Utils::$context['dir_creation_error'] = 'attachments_no_write';
+
return false;
}
// Everything seems fine...let's create the .htaccess
- if (!file_exists($directory . DIRECTORY_SEPARATOR . '.htaccess'))
+ if (!file_exists($directory . DIRECTORY_SEPARATOR . '.htaccess')) {
Security::secureDirectory($updir, true);
+ }
- $sep = (DIRECTORY_SEPARATOR === '\\') ? '\/' : DIRECTORY_SEPARATOR;
+ $sep = (DIRECTORY_SEPARATOR === '\\') ? '\\/' : DIRECTORY_SEPARATOR;
$updir = rtrim($updir, $sep);
// Only update if it's a new directory
- if (!in_array($updir, Config::$modSettings['attachmentUploadDir']))
- {
+ if (!in_array($updir, Config::$modSettings['attachmentUploadDir'])) {
Config::$modSettings['currentAttachmentUploadDir'] = max(array_keys(Config::$modSettings['attachmentUploadDir'])) + 1;
Config::$modSettings['attachmentUploadDir'][Config::$modSettings['currentAttachmentUploadDir']] = $updir;
- Config::updateModSettings(array(
+ Config::updateModSettings([
'attachmentUploadDir' => Utils::jsonEncode(Config::$modSettings['attachmentUploadDir']),
'currentAttachmentUploadDir' => Config::$modSettings['currentAttachmentUploadDir'],
- ), true);
+ ], true);
Config::$modSettings['attachmentUploadDir'] = Utils::jsonDecode(Config::$modSettings['attachmentUploadDir'], true);
}
@@ -913,31 +888,26 @@ public static function automanageCreateDirectory($updir)
*/
public static function automanageBySpace()
{
- if (!isset(Config::$modSettings['automanage_attachments']) || (!empty(Config::$modSettings['automanage_attachments']) && Config::$modSettings['automanage_attachments'] != 1))
- {
+ if (!isset(Config::$modSettings['automanage_attachments']) || (!empty(Config::$modSettings['automanage_attachments']) && Config::$modSettings['automanage_attachments'] != 1)) {
return;
}
$basedirectory = !empty(Config::$modSettings['use_subdirectories_for_attachments']) ? Config::$modSettings['basedirectory_for_attachments'] : Config::$boarddir;
// Just to be sure: I don't want directory separators at the end
- $sep = (DIRECTORY_SEPARATOR === '\\') ? '\/' : DIRECTORY_SEPARATOR;
+ $sep = (DIRECTORY_SEPARATOR === '\\') ? '\\/' : DIRECTORY_SEPARATOR;
$basedirectory = rtrim($basedirectory, $sep);
// Get the current base directory
- if (!empty(Config::$modSettings['use_subdirectories_for_attachments']) && !empty(Config::$modSettings['attachment_basedirectories']))
- {
+ if (!empty(Config::$modSettings['use_subdirectories_for_attachments']) && !empty(Config::$modSettings['attachment_basedirectories'])) {
$base_dir = array_search(Config::$modSettings['basedirectory_for_attachments'], Config::$modSettings['attachment_basedirectories']);
$base_dir = !empty(Config::$modSettings['automanage_attachments']) ? $base_dir : 0;
- }
- else
- {
+ } else {
$base_dir = 0;
}
// Get the last attachment directory for that base directory
- if (empty(Config::$modSettings['last_attachments_directory'][$base_dir]))
- {
+ if (empty(Config::$modSettings['last_attachments_directory'][$base_dir])) {
Config::$modSettings['last_attachments_directory'][$base_dir] = 0;
}
@@ -946,23 +916,20 @@ public static function automanageBySpace()
$updir = $basedirectory . DIRECTORY_SEPARATOR . 'attachments_' . Config::$modSettings['last_attachments_directory'][$base_dir];
- if (self::automanageCreateDirectory($updir))
- {
+ if (self::automanageCreateDirectory($updir)) {
Config::$modSettings['currentAttachmentUploadDir'] = array_search($updir, Config::$modSettings['attachmentUploadDir']);
- Config::updateModSettings(array(
+ Config::updateModSettings([
'last_attachments_directory' => Utils::jsonEncode(Config::$modSettings['last_attachments_directory']),
'currentAttachmentUploadDir' => Config::$modSettings['currentAttachmentUploadDir'],
- ));
+ ]);
Config::$modSettings['last_attachments_directory'] = Utils::jsonDecode(Config::$modSettings['last_attachments_directory'], true);
return true;
}
- else
- {
- return false;
- }
+
+ return false;
}
/**
@@ -971,192 +938,178 @@ public static function automanageBySpace()
public static function process()
{
// Make sure we're uploading to the right place.
- if (!empty(Config::$modSettings['automanage_attachments']))
+ if (!empty(Config::$modSettings['automanage_attachments'])) {
automanage_attachments_check_directory();
+ }
- if (!is_array(Config::$modSettings['attachmentUploadDir']))
- {
+ if (!is_array(Config::$modSettings['attachmentUploadDir'])) {
Config::$modSettings['attachmentUploadDir'] = Utils::jsonDecode(Config::$modSettings['attachmentUploadDir'], true);
}
Utils::$context['attach_dir'] = Config::$modSettings['attachmentUploadDir'][Config::$modSettings['currentAttachmentUploadDir']];
// Is the attachments folder actually there?
- if (!empty(Utils::$context['dir_creation_error']))
- {
+ if (!empty(Utils::$context['dir_creation_error'])) {
$initial_error = Utils::$context['dir_creation_error'];
- }
- elseif (!is_dir(Utils::$context['attach_dir']))
- {
+ } elseif (!is_dir(Utils::$context['attach_dir'])) {
$initial_error = 'attach_folder_warning';
ErrorHandler::log(sprintf(Lang::$txt['attach_folder_admin_warning'], Utils::$context['attach_dir']), 'critical');
}
- if (!isset($initial_error) && !isset(Utils::$context['attachments']))
- {
+ if (!isset($initial_error) && !isset(Utils::$context['attachments'])) {
// If this isn't a new post, check the current attachments.
- if (isset($_REQUEST['msg']))
- {
- $request = Db::$db->query('', '
- SELECT COUNT(*), SUM(size)
+ if (isset($_REQUEST['msg'])) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*), SUM(size)
FROM {db_prefix}attachments
WHERE id_msg = {int:id_msg}
AND attachment_type = {int:attachment_type}',
- array(
+ [
'id_msg' => (int) $_REQUEST['msg'],
'attachment_type' => 0,
- )
+ ],
);
- list (Utils::$context['attachments']['quantity'], Utils::$context['attachments']['total_size']) = Db::$db->fetch_row($request);
+ list(Utils::$context['attachments']['quantity'], Utils::$context['attachments']['total_size']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
- }
- else
- {
- Utils::$context['attachments'] = array(
+ } else {
+ Utils::$context['attachments'] = [
'quantity' => 0,
'total_size' => 0,
- );
+ ];
}
}
// Hmm. There are still files in session.
$ignore_temp = false;
- if (!empty($_SESSION['temp_attachments']['post']['files']) && count($_SESSION['temp_attachments']) > 1)
- {
+
+ if (!empty($_SESSION['temp_attachments']['post']['files']) && count($_SESSION['temp_attachments']) > 1) {
// Let's try to keep them. But...
$ignore_temp = true;
// If new files are being added. We can't ignore those
- foreach ($_FILES['attachment']['tmp_name'] as $dummy)
- {
- if (!empty($dummy))
- {
+ foreach ($_FILES['attachment']['tmp_name'] as $dummy) {
+ if (!empty($dummy)) {
$ignore_temp = false;
break;
}
}
// Need to make space for the new files. So, bye bye.
- if (!$ignore_temp)
- {
- foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
- {
- if (strpos($attachID, 'post_tmp_' . User::$me->id) !== false)
+ if (!$ignore_temp) {
+ foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
+ if (strpos($attachID, 'post_tmp_' . User::$me->id) !== false) {
unlink($attachment['tmp_name']);
+ }
}
Utils::$context['we_are_history'] = Lang::$txt['error_temp_attachments_flushed'];
- $_SESSION['temp_attachments'] = array();
+ $_SESSION['temp_attachments'] = [];
}
}
- if (!isset($_FILES['attachment']['name']))
- $_FILES['attachment']['tmp_name'] = array();
+ if (!isset($_FILES['attachment']['name'])) {
+ $_FILES['attachment']['tmp_name'] = [];
+ }
- if (!isset($_SESSION['temp_attachments']))
- $_SESSION['temp_attachments'] = array();
+ if (!isset($_SESSION['temp_attachments'])) {
+ $_SESSION['temp_attachments'] = [];
+ }
// Remember where we are at. If it's anywhere at all.
- if (!$ignore_temp)
- {
- $_SESSION['temp_attachments']['post'] = array(
+ if (!$ignore_temp) {
+ $_SESSION['temp_attachments']['post'] = [
'msg' => !empty($_REQUEST['msg']) ? $_REQUEST['msg'] : 0,
'last_msg' => !empty($_REQUEST['last_msg']) ? $_REQUEST['last_msg'] : 0,
'topic' => !empty($topic) ? $topic : 0,
'board' => !empty($board) ? $board : 0,
- );
+ ];
}
// If we have an initial error, lets just display it.
- if (!empty($initial_error))
- {
+ if (!empty($initial_error)) {
$_SESSION['temp_attachments']['initial_error'] = $initial_error;
// And delete the files 'cos they ain't going nowhere.
- foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
- {
- if (file_exists($_FILES['attachment']['tmp_name'][$n]))
+ foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy) {
+ if (file_exists($_FILES['attachment']['tmp_name'][$n])) {
unlink($_FILES['attachment']['tmp_name'][$n]);
+ }
}
- $_FILES['attachment']['tmp_name'] = array();
+ $_FILES['attachment']['tmp_name'] = [];
}
// Loop through $_FILES['attachment'] array and move each file to the current attachments folder.
- foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
- {
- if ($_FILES['attachment']['name'][$n] == '')
+ foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy) {
+ if ($_FILES['attachment']['name'][$n] == '') {
continue;
+ }
// First, let's first check for PHP upload errors.
- $errors = array();
- if (!empty($_FILES['attachment']['error'][$n]))
- {
- if ($_FILES['attachment']['error'][$n] == 2)
- {
- $errors[] = array('file_too_big', array(Config::$modSettings['attachmentSizeLimit']));
- }
- elseif ($_FILES['attachment']['error'][$n] == 6)
- {
+ $errors = [];
+
+ if (!empty($_FILES['attachment']['error'][$n])) {
+ if ($_FILES['attachment']['error'][$n] == 2) {
+ $errors[] = ['file_too_big', [Config::$modSettings['attachmentSizeLimit']]];
+ } elseif ($_FILES['attachment']['error'][$n] == 6) {
ErrorHandler::log($_FILES['attachment']['name'][$n] . ': ' . Lang::$txt['php_upload_error_6'], 'critical');
- }
- else
- {
+ } else {
ErrorHandler::log($_FILES['attachment']['name'][$n] . ': ' . Lang::$txt['php_upload_error_' . $_FILES['attachment']['error'][$n]]);
}
- if (empty($errors))
+ if (empty($errors)) {
$errors[] = 'attach_php_error';
+ }
}
// Try to move and rename the file before doing any more checks on it.
$attachID = 'post_tmp_' . User::$me->id . '_' . md5(mt_rand());
$destName = Utils::$context['attach_dir'] . '/' . $attachID;
- if (empty($errors))
- {
+ if (empty($errors)) {
// The reported MIME type of the attachment might not be reliable.
$detected_mime_type = Utils::getMimeType($_FILES['attachment']['tmp_name'][$n], true);
- if ($detected_mime_type !== false)
+ if ($detected_mime_type !== false) {
$_FILES['attachment']['type'][$n] = $detected_mime_type;
+ }
- $_SESSION['temp_attachments'][$attachID] = array(
+ $_SESSION['temp_attachments'][$attachID] = [
'name' => Utils::htmlspecialchars(basename($_FILES['attachment']['name'][$n])),
'tmp_name' => $destName,
'size' => $_FILES['attachment']['size'][$n],
'type' => $_FILES['attachment']['type'][$n],
'id_folder' => Config::$modSettings['currentAttachmentUploadDir'],
- 'errors' => array(),
- );
+ 'errors' => [],
+ ];
// Move the file to the attachments folder with a temp name for now.
- if (@move_uploaded_file($_FILES['attachment']['tmp_name'][$n], $destName))
- {
+ if (@move_uploaded_file($_FILES['attachment']['tmp_name'][$n], $destName)) {
Utils::makeWritable($destName, 0644);
- }
- else
- {
+ } else {
$_SESSION['temp_attachments'][$attachID]['errors'][] = 'attach_timeout';
- if (file_exists($_FILES['attachment']['tmp_name'][$n]))
+ if (file_exists($_FILES['attachment']['tmp_name'][$n])) {
unlink($_FILES['attachment']['tmp_name'][$n]);
+ }
}
- }
- else
- {
- $_SESSION['temp_attachments'][$attachID] = array(
+ } else {
+ $_SESSION['temp_attachments'][$attachID] = [
'name' => Utils::htmlspecialchars(basename($_FILES['attachment']['name'][$n])),
'tmp_name' => $destName,
'errors' => $errors,
- );
+ ];
- if (file_exists($_FILES['attachment']['tmp_name'][$n]))
+ if (file_exists($_FILES['attachment']['tmp_name'][$n])) {
unlink($_FILES['attachment']['tmp_name'][$n]);
+ }
}
+
// If there's no errors to this point. We still do need to apply some additional checks before we are finished.
- if (empty($_SESSION['temp_attachments'][$attachID]['errors']))
+ if (empty($_SESSION['temp_attachments'][$attachID]['errors'])) {
self::check($attachID);
+ }
}
// Mod authors, finally a hook to hang an alternate attachment upload system upon
// Upload to the current attachment folder with the file name $attachID or 'post_tmp_' . User::$me->id . '_' . md5(mt_rand())
@@ -1168,7 +1121,7 @@ public static function process()
// id_folder => Config::$modSettings['currentAttachmentUploadDir']
// errors => An array of errors (use the index of the Lang::$txt variable for that error).
// Template changes can be done using "integrate_upload_template".
- IntegrationHook::call('integrate_attachment_upload', array());
+ IntegrationHook::call('integrate_attachment_upload', []);
}
/**
@@ -1181,31 +1134,25 @@ public static function process()
public static function check($attachID)
{
// No data or missing data .... Not necessarily needed, but in case a mod author missed something.
- if (empty($_SESSION['temp_attachments'][$attachID]))
- {
+ if (empty($_SESSION['temp_attachments'][$attachID])) {
$error = '$_SESSION[\'temp_attachments\'][$attachID]';
- }
- elseif (empty($attachID))
- {
+ } elseif (empty($attachID)) {
$error = '$attachID';
- }
- elseif (empty(Utils::$context['attachments']))
- {
+ } elseif (empty(Utils::$context['attachments'])) {
$error = 'Utils::$context[\'attachments\']';
- }
- elseif (empty(Utils::$context['attach_dir']))
- {
+ } elseif (empty(Utils::$context['attach_dir'])) {
$error = 'Utils::$context[\'attach_dir\']';
}
// Let's get their attention.
- if (!empty($error))
- ErrorHandler::fatalLang('attach_check_nag', 'debug', array($error));
+ if (!empty($error)) {
+ ErrorHandler::fatalLang('attach_check_nag', 'debug', [$error]);
+ }
// Just in case this slipped by the first checks, we stop it here and now
- if ($_SESSION['temp_attachments'][$attachID]['size'] == 0)
- {
+ if ($_SESSION['temp_attachments'][$attachID]['size'] == 0) {
$_SESSION['temp_attachments'][$attachID]['errors'][] = 'attach_0_byte_file';
+
return false;
}
@@ -1213,13 +1160,12 @@ public static function check($attachID)
$image = new Image($_SESSION['temp_attachments'][$attachID]['tmp_name']);
// Source will be empty if this attachment is not an image.
- if (!empty($image->source) && !$image->check(!empty(Config::$modSettings['attachment_image_paranoid'])))
- {
+ if (!empty($image->source) && !$image->check(!empty(Config::$modSettings['attachment_image_paranoid']))) {
// It's bad. Last chance, maybe we can re-encode it?
- if (empty(Config::$modSettings['attachment_image_reencode']) || !$image->reencode())
- {
+ if (empty(Config::$modSettings['attachment_image_reencode']) || !$image->reencode()) {
// Nothing to do: not allowed or not successful re-encoding it.
$_SESSION['temp_attachments'][$attachID]['errors'][] = 'bad_attachment';
+
return false;
}
@@ -1231,20 +1177,19 @@ public static function check($attachID)
unset($image);
// Is there room for this sucker?
- if (!empty(Config::$modSettings['attachmentDirSizeLimit']) || !empty(Config::$modSettings['attachmentDirFileLimit']))
- {
+ if (!empty(Config::$modSettings['attachmentDirSizeLimit']) || !empty(Config::$modSettings['attachmentDirFileLimit'])) {
// Check the folder size and count. If it hasn't been done already.
- if (empty(Utils::$context['dir_size']) || empty(Utils::$context['dir_files']))
- {
- $request = Db::$db->query('', '
- SELECT COUNT(*), SUM(size)
+ if (empty(Utils::$context['dir_size']) || empty(Utils::$context['dir_files'])) {
+ $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(Utils::$context['dir_files'], Utils::$context['dir_size']) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -1263,10 +1208,9 @@ public static function check($attachID)
&& Config::$modSettings['attachmentDirFileLimit'] * .95 < Utils::$context['dir_files']
&& Config::$modSettings['attachmentDirFileLimit'] > 500
)
- )
- {
+ ) {
ACP::emailAdmins('admin_attachments_full');
- Config::updateModSettings(array('attachment_full_notified' => 1));
+ Config::updateModSettings(['attachment_full_notified' => 1]);
}
// // No room left.... What to do now???
@@ -1277,13 +1221,10 @@ public static function check($attachID)
!empty(Config::$modSettings['attachmentDirSizeLimit'])
&& Utils::$context['dir_size'] > Config::$modSettings['attachmentDirSizeLimit'] * 1024
)
- )
- {
- if (!empty(Config::$modSettings['automanage_attachments']) && Config::$modSettings['automanage_attachments'] == 1)
- {
+ ) {
+ if (!empty(Config::$modSettings['automanage_attachments']) && Config::$modSettings['automanage_attachments'] == 1) {
// Move it to the new folder if we can.
- if (self::automanageBySpace())
- {
+ if (self::automanageBySpace()) {
rename($_SESSION['temp_attachments'][$attachID]['tmp_name'], Utils::$context['attach_dir'] . '/' . $attachID);
$_SESSION['temp_attachments'][$attachID]['tmp_name'] = Utils::$context['attach_dir'] . '/' . $attachID;
$_SESSION['temp_attachments'][$attachID]['id_folder'] = Config::$modSettings['currentAttachmentUploadDir'];
@@ -1291,20 +1232,14 @@ public static function check($attachID)
Utils::$context['dir_files'] = 0;
}
// Or, let the user know that it ain't gonna happen.
- else
- {
- if (isset(Utils::$context['dir_creation_error']))
- {
+ else {
+ if (isset(Utils::$context['dir_creation_error'])) {
$_SESSION['temp_attachments'][$attachID]['errors'][] = Utils::$context['dir_creation_error'];
- }
- else
- {
+ } else {
$_SESSION['temp_attachments'][$attachID]['errors'][] = 'ran_out_of_space';
}
}
- }
- else
- {
+ } else {
$_SESSION['temp_attachments'][$attachID]['errors'][] = 'ran_out_of_space';
}
}
@@ -1313,54 +1248,50 @@ public static function check($attachID)
// Is the file too big?
Utils::$context['attachments']['total_size'] += $_SESSION['temp_attachments'][$attachID]['size'];
- if (!empty(Config::$modSettings['attachmentSizeLimit']) && $_SESSION['temp_attachments'][$attachID]['size'] > Config::$modSettings['attachmentSizeLimit'] * 1024)
- {
- $_SESSION['temp_attachments'][$attachID]['errors'][] = array('file_too_big', array(Lang::numberFormat(Config::$modSettings['attachmentSizeLimit'], 0)));
+ if (!empty(Config::$modSettings['attachmentSizeLimit']) && $_SESSION['temp_attachments'][$attachID]['size'] > Config::$modSettings['attachmentSizeLimit'] * 1024) {
+ $_SESSION['temp_attachments'][$attachID]['errors'][] = ['file_too_big', [Lang::numberFormat(Config::$modSettings['attachmentSizeLimit'], 0)]];
}
// Check the total upload size for this post...
- if (!empty(Config::$modSettings['attachmentPostLimit']) && Utils::$context['attachments']['total_size'] > Config::$modSettings['attachmentPostLimit'] * 1024)
- {
- $_SESSION['temp_attachments'][$attachID]['errors'][] = array('attach_max_total_file_size', array(Lang::numberFormat(Config::$modSettings['attachmentPostLimit'], 0), Lang::numberFormat(Config::$modSettings['attachmentPostLimit'] - ((Utils::$context['attachments']['total_size'] - $_SESSION['temp_attachments'][$attachID]['size']) / 1024), 0)));
+ if (!empty(Config::$modSettings['attachmentPostLimit']) && Utils::$context['attachments']['total_size'] > Config::$modSettings['attachmentPostLimit'] * 1024) {
+ $_SESSION['temp_attachments'][$attachID]['errors'][] = ['attach_max_total_file_size', [Lang::numberFormat(Config::$modSettings['attachmentPostLimit'], 0), Lang::numberFormat(Config::$modSettings['attachmentPostLimit'] - ((Utils::$context['attachments']['total_size'] - $_SESSION['temp_attachments'][$attachID]['size']) / 1024), 0)]];
}
// Have we reached the maximum number of files we are allowed?
Utils::$context['attachments']['quantity']++;
// Set a max limit if none exists
- if (empty(Config::$modSettings['attachmentNumPerPostLimit']) && Utils::$context['attachments']['quantity'] >= 50)
- {
+ if (empty(Config::$modSettings['attachmentNumPerPostLimit']) && Utils::$context['attachments']['quantity'] >= 50) {
Config::$modSettings['attachmentNumPerPostLimit'] = 50;
}
- if (!empty(Config::$modSettings['attachmentNumPerPostLimit']) && Utils::$context['attachments']['quantity'] > Config::$modSettings['attachmentNumPerPostLimit'])
- {
- $_SESSION['temp_attachments'][$attachID]['errors'][] = array('attachments_limit_per_post', array(Config::$modSettings['attachmentNumPerPostLimit']));
+ if (!empty(Config::$modSettings['attachmentNumPerPostLimit']) && Utils::$context['attachments']['quantity'] > Config::$modSettings['attachmentNumPerPostLimit']) {
+ $_SESSION['temp_attachments'][$attachID]['errors'][] = ['attachments_limit_per_post', [Config::$modSettings['attachmentNumPerPostLimit']]];
}
// File extension check
- if (!empty(Config::$modSettings['attachmentCheckExtensions']))
- {
+ if (!empty(Config::$modSettings['attachmentCheckExtensions'])) {
$allowed = explode(',', strtolower(Config::$modSettings['attachmentExtensions']));
- foreach ($allowed as $k => $dummy)
+ foreach ($allowed as $k => $dummy) {
$allowed[$k] = trim($dummy);
+ }
- if (!in_array(strtolower(substr(strrchr($_SESSION['temp_attachments'][$attachID]['name'], '.'), 1)), $allowed))
- {
- $allowed_extensions = strtr(strtolower(Config::$modSettings['attachmentExtensions']), array(',' => ', '));
- $_SESSION['temp_attachments'][$attachID]['errors'][] = array('cant_upload_type', array($allowed_extensions));
+ if (!in_array(strtolower(substr(strrchr($_SESSION['temp_attachments'][$attachID]['name'], '.'), 1)), $allowed)) {
+ $allowed_extensions = strtr(strtolower(Config::$modSettings['attachmentExtensions']), [',' => ', ']);
+ $_SESSION['temp_attachments'][$attachID]['errors'][] = ['cant_upload_type', [$allowed_extensions]];
}
}
// Undo the math if there's an error
- if (!empty($_SESSION['temp_attachments'][$attachID]['errors']))
- {
- if (isset(Utils::$context['dir_size']))
+ if (!empty($_SESSION['temp_attachments'][$attachID]['errors'])) {
+ if (isset(Utils::$context['dir_size'])) {
Utils::$context['dir_size'] -= $_SESSION['temp_attachments'][$attachID]['size'];
+ }
- if (isset(Utils::$context['dir_files']))
+ if (isset(Utils::$context['dir_files'])) {
Utils::$context['dir_files']--;
+ }
Utils::$context['attachments']['total_size'] -= $_SESSION['temp_attachments'][$attachID]['size'];
@@ -1387,8 +1318,7 @@ public static function create(&$attachmentOptions)
$image = new Image($attachmentOptions['tmp_name']);
// Source is empty for non-images.
- if (!empty($image->source))
- {
+ if (!empty($image->source)) {
// Make sure the MIME type is correct.
$attachmentOptions['mime_type'] = $image->mime_type;
@@ -1396,8 +1326,7 @@ public static function create(&$attachmentOptions)
$attachmentOptions['width'] = $image->width;
$attachmentOptions['height'] = $image->height;
- if (in_array($image->orientation, array(5, 6, 7, 8)))
- {
+ if (in_array($image->orientation, [5, 6, 7, 8])) {
$attachmentOptions['width'] = $image->height;
$attachmentOptions['height'] = $image->width;
}
@@ -1406,13 +1335,10 @@ public static function create(&$attachmentOptions)
$attachmentOptions['fileext'] = ltrim(image_type_to_extension($image->type), '.');
// Special exception: allow both 'jpg' and 'jpeg'.
- if ($attachmentOptions['fileext'] === 'jpeg' && strtolower(pathinfo($attachmentOptions['name'], PATHINFO_EXTENSION)) === 'jpg')
- {
+ if ($attachmentOptions['fileext'] === 'jpeg' && strtolower(pathinfo($attachmentOptions['name'], PATHINFO_EXTENSION)) === 'jpg') {
$attachmentOptions['fileext'] = pathinfo($attachmentOptions['name'], PATHINFO_EXTENSION);
}
- }
- else
- {
+ } else {
$attachmentOptions['width'] = 0;
$attachmentOptions['height'] = 0;
}
@@ -1422,90 +1348,86 @@ public static function create(&$attachmentOptions)
// Fix up the supplied file name and extension.
$name_info = array_filter(pathinfo($attachmentOptions['name']), 'strlen');
- if (strlen($attachmentOptions['fileext'] ?? '') > 8)
+ if (strlen($attachmentOptions['fileext'] ?? '') > 8) {
$attachmentOptions['fileext'] = '';
+ }
- if (strlen($attachmentOptions['fileext'] ?? '') === 0)
- {
+ if (strlen($attachmentOptions['fileext'] ?? '') === 0) {
$attachmentOptions['fileext'] = isset($name_info['extension']) && strlen($name_info['extension']) <= 8 ? $name_info['extension'] : '';
}
$attachmentOptions['name'] = ($name_info['filename'] ?? bin2hex(Utils::randomBytes(4))) . (strlen($attachmentOptions['fileext']) > 0 ? '.' . $attachmentOptions['fileext'] : '');
// Get the hash if no hash has been given yet.
- if (empty($attachmentOptions['file_hash']))
- {
+ if (empty($attachmentOptions['file_hash'])) {
$attachmentOptions['file_hash'] = self::createHash($attachmentOptions['tmp_name']);
}
// This defines which options to use for which columns in the insert query.
// Mods using the hook can add columns and even change the properties of existing columns,
// but if they delete one of these columns, it will be reset to the default defined here.
- $attachmentStandardInserts = $attachmentInserts = array(
+ $attachmentStandardInserts = $attachmentInserts = [
// Format: 'column' => array('type', 'option')
- 'id_folder' => array('int', 'id_folder'),
- 'id_msg' => array('int', 'post'),
- 'filename' => array('string-255', 'name'),
- 'file_hash' => array('string-40', 'file_hash'),
- 'fileext' => array('string-8', 'fileext'),
- 'size' => array('int', 'size'),
- 'width' => array('int', 'width'),
- 'height' => array('int', 'height'),
- 'mime_type' => array('string-20', 'mime_type'),
- 'approved' => array('int', 'approved'),
- );
+ 'id_folder' => ['int', 'id_folder'],
+ 'id_msg' => ['int', 'post'],
+ 'filename' => ['string-255', 'name'],
+ 'file_hash' => ['string-40', 'file_hash'],
+ 'fileext' => ['string-8', 'fileext'],
+ 'size' => ['int', 'size'],
+ 'width' => ['int', 'width'],
+ 'height' => ['int', 'height'],
+ 'mime_type' => ['string-20', 'mime_type'],
+ 'approved' => ['int', 'approved'],
+ ];
// Last chance to change stuff!
- IntegrationHook::call('integrate_createAttachment', array(&$attachmentOptions, &$attachmentInserts));
+ IntegrationHook::call('integrate_createAttachment', [&$attachmentOptions, &$attachmentInserts]);
// Make sure the folder is valid...
$tmp = is_array(Config::$modSettings['attachmentUploadDir']) ? Config::$modSettings['attachmentUploadDir'] : Utils::jsonDecode(Config::$modSettings['attachmentUploadDir'], true);
$folders = array_keys($tmp);
- if (empty($attachmentOptions['id_folder']) || !in_array($attachmentOptions['id_folder'], $folders))
- {
+ if (empty($attachmentOptions['id_folder']) || !in_array($attachmentOptions['id_folder'], $folders)) {
$attachmentOptions['id_folder'] = Config::$modSettings['currentAttachmentUploadDir'];
}
// Make sure all required columns are present, in case a mod screwed up.
- foreach ($attachmentStandardInserts as $column => $insert_info)
- {
- if (!isset($attachmentInserts[$column]))
+ foreach ($attachmentStandardInserts as $column => $insert_info) {
+ if (!isset($attachmentInserts[$column])) {
$attachmentInserts[$column] = $insert_info;
+ }
}
// Set up the columns and values to insert, in the correct order.
- $attachmentColumns = array();
- $attachmentValues = array();
- foreach ($attachmentInserts as $column => $insert_info)
- {
+ $attachmentColumns = [];
+ $attachmentValues = [];
+
+ foreach ($attachmentInserts as $column => $insert_info) {
$attachmentColumns[$column] = $insert_info[0];
- if (!empty($insert_info[0]) && $insert_info[0] == 'int')
- {
+ if (!empty($insert_info[0]) && $insert_info[0] == 'int') {
$attachmentValues[] = (int) $attachmentOptions[$insert_info[1]];
- }
- else
- {
+ } else {
$attachmentValues[] = $attachmentOptions[$insert_info[1]];
}
}
// Create the attachment in the database.
- $attachmentOptions['id'] = Db::$db->insert('',
+ $attachmentOptions['id'] = Db::$db->insert(
+ '',
'{db_prefix}attachments',
$attachmentColumns,
$attachmentValues,
- array('id_attach'),
- 1
+ ['id_attach'],
+ 1,
);
// Attachment couldn't be created.
- if (empty($attachmentOptions['id']))
- {
+ if (empty($attachmentOptions['id'])) {
Lang::load('Errors');
ErrorHandler::log(Lang::$txt['attachment_not_created'], 'general');
+
return false;
}
@@ -1514,57 +1436,48 @@ public static function create(&$attachmentOptions)
rename($attachmentOptions['tmp_name'], $attachmentOptions['destination']);
// If it's not approved then add to the approval queue.
- if (!$attachmentOptions['approved'])
- {
- Db::$db->insert('',
+ if (!$attachmentOptions['approved']) {
+ Db::$db->insert(
+ '',
'{db_prefix}approval_queue',
- array(
+ [
'id_attach' => 'int', 'id_msg' => 'int',
- ),
- array(
+ ],
+ [
$attachmentOptions['id'], (int) $attachmentOptions['post'],
- ),
- array()
+ ],
+ [],
);
// Queue background notification task.
Db::$db->insert(
'insert',
'{db_prefix}background_tasks',
- array(
- 'task_file' => 'string',
+ [
'task_class' => 'string',
'task_data' => 'string',
- 'claimed_time' => 'int'
- ),
- array(
- '$sourcedir/tasks/CreateAttachment_Notify.php',
- 'SMF\Tasks\CreateAttachment_Notify',
- Utils::jsonEncode(
- array(
- 'id' => $attachmentOptions['id'],
- )
- ),
- 0
- ),
- array(
- 'id_task'
- )
+ 'claimed_time' => 'int',
+ ],
+ [
+ 'SMF\\Tasks\\CreateAttachment_Notify',
+ Utils::jsonEncode(['id' => $attachmentOptions['id']]),
+ 0,
+ ],
+ [
+ 'id_task',
+ ],
);
}
- if (!$this->is_image || empty(Config::$modSettings['attachmentThumbnails']) || (empty($attachmentOptions['width']) && empty($attachmentOptions['height'])))
- {
+ if (!$this->is_image || empty(Config::$modSettings['attachmentThumbnails']) || (empty($attachmentOptions['width']) && empty($attachmentOptions['height']))) {
return true;
}
// Like thumbnails, do we?
- if (!empty(Config::$modSettings['attachmentThumbWidth']) && !empty(Config::$modSettings['attachmentThumbHeight']) && ($attachmentOptions['width'] > Config::$modSettings['attachmentThumbWidth'] || $attachmentOptions['height'] > Config::$modSettings['attachmentThumbHeight']))
- {
+ if (!empty(Config::$modSettings['attachmentThumbWidth']) && !empty(Config::$modSettings['attachmentThumbHeight']) && ($attachmentOptions['width'] > Config::$modSettings['attachmentThumbWidth'] || $attachmentOptions['height'] > Config::$modSettings['attachmentThumbHeight'])) {
$image = new Image($attachmentOptions['destination'], true);
- if (($thumb = $image->createThumbnail(Config::$modSettings['attachmentThumbWidth'], Config::$modSettings['attachmentThumbHeight'])) !== false)
- {
+ if (($thumb = $image->createThumbnail(Config::$modSettings['attachmentThumbWidth'], Config::$modSettings['attachmentThumbHeight'])) !== false) {
// Propagate our special handling for JPEGs to the thumbnail's extension, too.
$thumb_ext = $image->type === $thumb->type ? $attachmentOptions['fileext'] : ltrim(image_type_to_extension($thumb->type), '.');
@@ -1574,17 +1487,14 @@ public static function create(&$attachmentOptions)
&& Config::$modSettings['automanage_attachments'] == 1
&& !empty(Config::$modSettings['attachmentDirSizeLimit'])
|| !empty(Config::$modSettings['attachmentDirFileLimit'])
- )
- {
+ ) {
Utils::$context['dir_size'] = isset(Utils::$context['dir_size']) ? Utils::$context['dir_size'] += $thumb->filesize : Utils::$context['dir_size'] = 0;
Utils::$context['dir_files'] = isset(Utils::$context['dir_files']) ? Utils::$context['dir_files']++ : Utils::$context['dir_files'] = 0;
// If the folder is full, try to create a new one and move the thumb to it.
- if (Utils::$context['dir_size'] > Config::$modSettings['attachmentDirSizeLimit'] * 1024 || Utils::$context['dir_files'] + 2 > Config::$modSettings['attachmentDirFileLimit'])
- {
- if (self::automanageBySpace())
- {
+ if (Utils::$context['dir_size'] > Config::$modSettings['attachmentDirSizeLimit'] * 1024 || Utils::$context['dir_files'] + 2 > Config::$modSettings['attachmentDirFileLimit']) {
+ if (self::automanageBySpace()) {
$thumb->move(Utils::$context['attach_dir'] . '/' . $thumb->pathinfo['basename']);
Utils::$context['dir_size'] = 0;
@@ -1594,15 +1504,15 @@ public static function create(&$attachmentOptions)
}
// If a new folder has been already created. Gotta move this thumb there then.
- if (Config::$modSettings['currentAttachmentUploadDir'] != $attachmentOptions['id_folder'])
- {
+ if (Config::$modSettings['currentAttachmentUploadDir'] != $attachmentOptions['id_folder']) {
$thumb->move(Utils::$context['attach_dir'] . '/' . $thumb->pathinfo['basename']);
}
// To the database we go!
- $attachmentOptions['thumb'] = Db::$db->insert('',
+ $attachmentOptions['thumb'] = Db::$db->insert(
+ '',
'{db_prefix}attachments',
- array(
+ [
'id_folder' => 'int',
'id_msg' => 'int',
'attachment_type' => 'int',
@@ -1614,8 +1524,8 @@ public static function create(&$attachmentOptions)
'height' => 'int',
'mime_type' => 'string-20',
'approved' => 'int',
- ),
- array(
+ ],
+ [
Config::$modSettings['currentAttachmentUploadDir'],
(int) $attachmentOptions['post'],
3,
@@ -1627,21 +1537,21 @@ public static function create(&$attachmentOptions)
$thumb->height,
$thumb->mime_type,
(int) $attachmentOptions['approved'],
- ),
- array('id_attach'),
- 1
+ ],
+ ['id_attach'],
+ 1,
);
- if (!empty($attachmentOptions['thumb']))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}attachments
+ if (!empty($attachmentOptions['thumb'])) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}attachments
SET id_thumb = {int:id_thumb}
WHERE id_attach = {int:id_attach}',
- array(
+ [
'id_thumb' => $attachmentOptions['thumb'],
'id_attach' => $attachmentOptions['id'],
- )
+ ],
);
$thumb->move(self::getFilePath($attachmentOptions['thumb']));
@@ -1658,30 +1568,33 @@ public static function create(&$attachmentOptions)
* @param $attachIDs array of attachment IDs to assign.
* @param $msgID integer the message ID.
*
- * @return boolean false on error or missing params.
+ * @return bool false on error or missing params.
*/
- public static function assign($attachIDs = array(), $msgID = 0)
+ public static function assign($attachIDs = [], $msgID = 0)
{
// Oh, come on!
- if (empty($attachIDs) || empty($msgID))
+ if (empty($attachIDs) || empty($msgID)) {
return false;
+ }
// "I see what is right and approve, but I do what is wrong."
- IntegrationHook::call('integrate_assign_attachments', array(&$attachIDs, &$msgID));
+ IntegrationHook::call('integrate_assign_attachments', [&$attachIDs, &$msgID]);
// One last check
- if (empty($attachIDs))
+ if (empty($attachIDs)) {
return false;
+ }
// Perform.
- Db::$db->query('', '
- UPDATE {db_prefix}attachments
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}attachments
SET id_msg = {int:id_msg}
WHERE id_attach IN ({array_int:attach_ids})',
- array(
+ [
'id_msg' => $msgID,
'attach_ids' => $attachIDs,
- )
+ ],
);
return true;
@@ -1695,81 +1608,88 @@ public static function assign($attachIDs = array(), $msgID = 0)
*/
public static function approve($attachments): bool
{
- if (empty($attachments))
+ if (empty($attachments)) {
return false;
+ }
// For safety, check for thumbnails...
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
a.id_attach, a.id_member, COALESCE(thumb.id_attach, 0) AS id_thumb
FROM {db_prefix}attachments AS a
LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
WHERE a.id_attach IN ({array_int:attachments})
AND a.attachment_type = {int:attachment_type}',
- array(
+ [
'attachments' => $attachments,
'attachment_type' => 0,
- )
+ ],
);
- $attachments = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ $attachments = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Update the thumbnail too...
- if (!empty($row['id_thumb']))
+ if (!empty($row['id_thumb'])) {
$attachments[] = $row['id_thumb'];
+ }
$attachments[] = $row['id_attach'];
}
Db::$db->free_result($request);
- if (empty($attachments))
+ if (empty($attachments)) {
return false;
+ }
// Approving an attachment is not hard - it's easy.
- Db::$db->query('', '
- UPDATE {db_prefix}attachments
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}attachments
SET approved = {int:is_approved}
WHERE id_attach IN ({array_int:attachments})',
- array(
+ [
'attachments' => $attachments,
'is_approved' => 1,
- )
+ ],
);
// In order to log the attachments, we really need their message and filename
- $request = Db::$db->query('', '
- SELECT m.id_msg, a.filename
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg, a.filename
FROM {db_prefix}attachments AS a
INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)
WHERE a.id_attach IN ({array_int:attachments})
AND a.attachment_type = {int:attachment_type}',
- array(
+ [
'attachments' => $attachments,
'attachment_type' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Logging::logAction(
'approve_attach',
- array(
+ [
'message' => $row['id_msg'],
- 'filename' => preg_replace('~&#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '\\1;', Utils::htmlspecialchars($row['filename'])),
- )
+ 'filename' => preg_replace('~&#(\d{1,7}|x[0-9a-fA-F]{1,6});~', '$1;', Utils::htmlspecialchars($row['filename'])),
+ ],
);
}
Db::$db->free_result($request);
// Remove from the approval queue.
- Db::$db->query('', '
- DELETE FROM {db_prefix}approval_queue
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}approval_queue
WHERE id_attach IN ({array_int:attachments})',
- array(
+ [
'attachments' => $attachments,
- )
+ ],
);
- IntegrationHook::call('integrate_approve_attachments', array($attachments));
+ IntegrationHook::call('integrate_approve_attachments', [$attachments]);
return true;
}
@@ -1791,62 +1711,51 @@ public static function approve($attachments): bool
public static function remove($condition, $query_type = '', $return_affected_messages = false, $autoThumbRemoval = true)
{
// @todo This might need more work!
- $new_condition = array();
- $query_parameter = array(
+ $new_condition = [];
+ $query_parameter = [
'thumb_attachment_type' => 3,
- );
- $do_logging = array();
+ ];
+ $do_logging = [];
- if (is_array($condition))
- {
- foreach ($condition as $real_type => $restriction)
- {
+ if (is_array($condition)) {
+ foreach ($condition as $real_type => $restriction) {
// Doing a NOT?
$is_not = substr($real_type, 0, 4) == 'not_';
$type = $is_not ? substr($real_type, 4) : $real_type;
- if (in_array($type, array('id_member', 'id_attach', 'id_msg')))
- {
+ if (in_array($type, ['id_member', 'id_attach', 'id_msg'])) {
$new_condition[] = 'a.' . $type . ($is_not ? ' NOT' : '') . ' IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
- }
- elseif ($type == 'attachment_type')
- {
+ } elseif ($type == 'attachment_type') {
$new_condition[] = 'a.attachment_type = {int:' . $real_type . '}';
- }
- elseif ($type == 'poster_time')
- {
+ } elseif ($type == 'poster_time') {
$new_condition[] = 'm.poster_time < {int:' . $real_type . '}';
- }
- elseif ($type == 'last_login')
- {
+ } elseif ($type == 'last_login') {
$new_condition[] = 'mem.last_login < {int:' . $real_type . '}';
- }
- elseif ($type == 'size')
- {
+ } elseif ($type == 'size') {
$new_condition[] = 'a.size > {int:' . $real_type . '}';
- }
- elseif ($type == 'id_topic')
- {
+ } elseif ($type == 'id_topic') {
$new_condition[] = 'm.id_topic IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
}
// Add the parameter!
$query_parameter[$real_type] = $restriction;
- if ($type == 'do_logging')
+ if ($type == 'do_logging') {
$do_logging = $condition['id_attach'];
+ }
}
$condition = implode(' AND ', $new_condition);
}
// Delete it only if it exists...
- $msgs = array();
- $attach = array();
- $parents = array();
+ $msgs = [];
+ $attach = [];
+ $parents = [];
// Get all the attachment names and id_msg's.
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
a.id_folder, a.filename, a.file_hash, a.attachment_type, a.id_attach, a.id_member' . ($query_type == 'messages' ? ', m.id_msg' : ', a.id_msg') . ',
thumb.id_folder AS thumb_folder, COALESCE(thumb.id_attach, 0) AS id_thumb, thumb.filename AS thumb_filename, thumb.file_hash AS thumb_file_hash, thumb_parent.id_attach AS id_parent
FROM {db_prefix}attachments AS a' . ($query_type == 'members' ? '
@@ -1855,30 +1764,27 @@ public static function remove($condition, $query_type = '', $return_affected_mes
LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
LEFT JOIN {db_prefix}attachments AS thumb_parent ON (thumb.attachment_type = {int:thumb_attachment_type} AND thumb_parent.id_thumb = a.id_attach)
WHERE ' . $condition,
- $query_parameter
+ $query_parameter,
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Figure out the "encrypted" filename and unlink it ;).
- if ($row['attachment_type'] == 1)
- {
+ if ($row['attachment_type'] == 1) {
// if attachment_type = 1, it's... an avatar in a custom avatars directory.
// wasn't it obvious? :P
// @todo look again at this.
@unlink(Config::$modSettings['custom_avatar_dir'] . '/' . $row['filename']);
- }
- else
- {
+ } else {
$filename = Attachment::getFilePath($row['id_attach']);
@unlink($filename);
// If this was a thumb, the parent attachment should know about it.
- if (!empty($row['id_parent']))
+ if (!empty($row['id_parent'])) {
$parents[] = $row['id_parent'];
+ }
// If this attachments has a thumb, remove it as well.
- if (!empty($row['id_thumb']) && $autoThumbRemoval)
- {
+ if (!empty($row['id_thumb']) && $autoThumbRemoval) {
$thumb_filename = Attachment::getFilePath($row['id_thumb']);
@unlink($thumb_filename);
$attach[] = $row['id_thumb'];
@@ -1886,8 +1792,9 @@ public static function remove($condition, $query_type = '', $return_affected_mes
}
// Make a list.
- if ($return_affected_messages && empty($row['attachment_type']))
+ if ($return_affected_messages && empty($row['attachment_type'])) {
$msgs[] = $row['id_msg'];
+ }
$attach[] = $row['id_attach'];
}
@@ -1896,61 +1803,62 @@ public static function remove($condition, $query_type = '', $return_affected_mes
// Removed attachments don't have to be updated anymore.
$parents = array_diff($parents, $attach);
- if (!empty($parents))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}attachments
+ if (!empty($parents)) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}attachments
SET id_thumb = {int:no_thumb}
WHERE id_attach IN ({array_int:parent_attachments})',
- array(
+ [
'parent_attachments' => $parents,
'no_thumb' => 0,
- )
+ ],
);
}
- if (!empty($do_logging))
- {
+ if (!empty($do_logging)) {
// In order to log the attachments, we really need their message and filename
- $request = Db::$db->query('', '
- SELECT m.id_msg, a.filename
+ $request = Db::$db->query(
+ '',
+ 'SELECT m.id_msg, a.filename
FROM {db_prefix}attachments AS a
INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)
WHERE a.id_attach IN ({array_int:attachments})
AND a.attachment_type = {int:attachment_type}',
- array(
+ [
'attachments' => $do_logging,
'attachment_type' => 0,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
Logging::logAction(
'remove_attach',
- array(
+ [
'message' => $row['id_msg'],
- 'filename' => preg_replace('~&#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '\\1;', Utils::htmlspecialchars($row['filename'])),
- )
+ 'filename' => preg_replace('~&#(\d{1,7}|x[0-9a-fA-F]{1,6});~', '$1;', Utils::htmlspecialchars($row['filename'])),
+ ],
);
}
Db::$db->free_result($request);
}
- if (!empty($attach))
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}attachments
+ if (!empty($attach)) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}attachments
WHERE id_attach IN ({array_int:attachment_list})',
- array(
+ [
'attachment_list' => $attach,
- )
+ ],
);
}
- IntegrationHook::call('integrate_remove_attachments', array($attach));
+ IntegrationHook::call('integrate_remove_attachments', [$attach]);
- if ($return_affected_messages)
+ if ($return_affected_messages) {
return array_unique($msgs);
+ }
}
/**
@@ -1964,39 +1872,41 @@ public static function parseAttachBBC($attachID = 0)
{
static $view_attachment_boards;
- if (!isset($view_attachment_boards))
+ if (!isset($view_attachment_boards)) {
$view_attachment_boards = User::$me->boardsAllowedTo('view_attachments');
+ }
// Meh...
- if (empty($attachID))
+ if (empty($attachID)) {
return 'attachments_no_data_loaded';
+ }
// Make it easy.
$msgID = !empty($_REQUEST['msg']) ? (int) $_REQUEST['msg'] : 0;
// Perhaps someone else wants to do the honors? Yes, this also includes dealing with previews ;)
- $externalParse = IntegrationHook::call('integrate_pre_parseAttachBBC', array($attachID, $msgID));
+ $externalParse = IntegrationHook::call('integrate_pre_parseAttachBBC', [$attachID, $msgID]);
// "I am innocent of the blood of this just person: see ye to it."
- if (!empty($externalParse) && (is_string($externalParse) || is_array($externalParse)))
+ if (!empty($externalParse) && (is_string($externalParse) || is_array($externalParse))) {
return $externalParse;
+ }
// Are attachments enabled?
- if (empty(Config::$modSettings['attachmentEnable']))
+ if (empty(Config::$modSettings['attachmentEnable'])) {
return 'attachments_not_enable';
+ }
- $check_board_perms = !isset($_SESSION['attachments_can_preview'][$attachID]) && $view_attachment_boards !== array(0);
+ $check_board_perms = !isset($_SESSION['attachments_can_preview'][$attachID]) && $view_attachment_boards !== [0];
// There is always the chance someone else has already done our dirty work...
// If so, all pertinent checks were already done. Hopefully...
- if (!empty(Utils::$context['current_attachments']) && !empty(Utils::$context['current_attachments'][$attachID]))
- {
+ if (!empty(Utils::$context['current_attachments']) && !empty(Utils::$context['current_attachments'][$attachID])) {
return Utils::$context['current_attachments'][$attachID];
}
// Can the user view attachments on this board?
- if ($check_board_perms && !empty(Board::$info->id) && !in_array(Board::$info->id, $view_attachment_boards))
- {
+ if ($check_board_perms && !empty(Board::$info->id) && !in_array(Board::$info->id, $view_attachment_boards)) {
return 'attachments_not_allowed_to_see';
}
@@ -2004,30 +1914,32 @@ public static function parseAttachBBC($attachID = 0)
$attachInfo = self::getAttachMsgInfo($attachID);
// There is always the chance this attachment no longer exists or isn't associated to a message anymore...
- if (!isset($attachInfo['id']))
+ if (!isset($attachInfo['id'])) {
return 'attachments_no_data_loaded';
+ }
- if (empty($attachInfo['msg']) && empty(Utils::$context['preview_message']))
+ if (empty($attachInfo['msg']) && empty(Utils::$context['preview_message'])) {
return 'attachments_no_msg_associated';
+ }
// Can the user view attachments on the board that holds the attachment's original post?
// (This matters when one post quotes another on a different board.)
- if ($check_board_perms && !in_array($attachInfo['board'], $view_attachment_boards))
+ if ($check_board_perms && !in_array($attachInfo['board'], $view_attachment_boards)) {
return 'attachments_not_allowed_to_see';
+ }
- if (empty(Utils::$context['loaded_attachments'][$attachInfo['msg']]))
- self::prepareByMsg(array($attachInfo['msg']));
+ if (empty(Utils::$context['loaded_attachments'][$attachInfo['msg']])) {
+ self::prepareByMsg([$attachInfo['msg']]);
+ }
- if (isset(Utils::$context['loaded_attachments'][$attachInfo['msg']][$attachID]))
+ if (isset(Utils::$context['loaded_attachments'][$attachInfo['msg']][$attachID])) {
$attachContext = Utils::$context['loaded_attachments'][$attachInfo['msg']][$attachID];
+ }
// In case the user manually typed the thumbnail's ID into the BBC
- elseif (!empty(Utils::$context['loaded_attachments'][$attachInfo['msg']]))
- {
- foreach (Utils::$context['loaded_attachments'][$attachInfo['msg']] as $foundAttachID => $foundAttach)
- {
- if (array_key_exists('id_thumb', $foundAttach) && $foundAttach['id_thumb'] == $attachID)
- {
+ elseif (!empty(Utils::$context['loaded_attachments'][$attachInfo['msg']])) {
+ foreach (Utils::$context['loaded_attachments'][$attachInfo['msg']] as $foundAttachID => $foundAttach) {
+ if (array_key_exists('id_thumb', $foundAttach) && $foundAttach['id_thumb'] == $attachID) {
$attachContext = Utils::$context['loaded_attachments'][$attachInfo['msg']][$foundAttachID];
$attachID = $foundAttachID;
break;
@@ -2036,48 +1948,42 @@ public static function parseAttachBBC($attachID = 0)
}
// Load this particular attach's context.
- if (!empty($attachContext))
- {
+ if (!empty($attachContext)) {
// Skip unapproved attachment, unless they belong to the user or the user can approve them.
if (
!Utils::$context['loaded_attachments'][$attachInfo['msg']][$attachID]['approved']
&& Config::$modSettings['postmod_active']
&& !User::$me->allowedTo('approve_posts')
&& Utils::$context['loaded_attachments'][$attachInfo['msg']][$attachID]['id_member'] != User::$me->id
- )
- {
+ ) {
unset(Utils::$context['loaded_attachments'][$attachInfo['msg']][$attachID]);
+
return 'attachments_unapproved';
}
$attachLoaded = self::loadAttachmentContext($attachContext['id_msg'], Utils::$context['loaded_attachments']);
- }
- else
- {
+ } else {
return 'attachments_no_data_loaded';
}
- if (empty($attachLoaded))
- {
+ if (empty($attachLoaded)) {
return 'attachments_no_data_loaded';
}
- else
- {
- $attachContext = $attachLoaded[$attachID];
- }
+
+ $attachContext = $attachLoaded[$attachID];
// It's theoretically possible that prepareByMsg() changed the board id, so check again.
- if ($check_board_perms && !in_array($attachContext['board'], $view_attachment_boards))
+ if ($check_board_perms && !in_array($attachContext['board'], $view_attachment_boards)) {
return 'attachments_not_allowed_to_see';
+ }
// You may or may not want to show this under the post.
- if (!empty(Config::$modSettings['dont_show_attach_under_post']) && !isset(Utils::$context['show_attach_under_post'][$attachID]))
- {
+ if (!empty(Config::$modSettings['dont_show_attach_under_post']) && !isset(Utils::$context['show_attach_under_post'][$attachID])) {
Utils::$context['show_attach_under_post'][$attachID] = $attachID;
}
// Last minute changes?
- IntegrationHook::call('integrate_post_parseAttachBBC', array(&$attachContext));
+ IntegrationHook::call('integrate_post_parseAttachBBC', [&$attachContext]);
// Don't do any logic with the loaded data, leave it to whoever called this function.
return $attachContext;
@@ -2091,15 +1997,17 @@ public static function parseAttachBBC($attachID = 0)
*/
public static function getAttachMsgInfo($attachID)
{
- if (empty($attachID))
- return array();
+ if (empty($attachID)) {
+ return [];
+ }
- if (!isset(Utils::$context['loaded_attachments']))
- Utils::$context['loaded_attachments'] = array();
+ if (!isset(Utils::$context['loaded_attachments'])) {
+ Utils::$context['loaded_attachments'] = [];
+ }
self::load($attachID);
- return self::$loaded[$attachID] ?? array();
+ return self::$loaded[$attachID] ?? [];
}
/**
@@ -2114,18 +2022,17 @@ public static function getAttachMsgInfo($attachID)
*/
public static function loadAttachmentContext($id_msg, $attachments)
{
- if (empty($attachments) || empty($attachments[$id_msg]))
- return array();
+ if (empty($attachments) || empty($attachments[$id_msg])) {
+ return [];
+ }
// Set up the attachment info - based on code by Meriadoc.
- $attachmentData = array();
+ $attachmentData = [];
$have_unapproved = false;
- if (isset($attachments[$id_msg]) && !empty(Config::$modSettings['attachmentEnable']))
- {
- foreach ($attachments[$id_msg] as $i => $attachment)
- {
- $attachmentData[$i] = array(
+ if (isset($attachments[$id_msg]) && !empty(Config::$modSettings['attachmentEnable'])) {
+ foreach ($attachments[$id_msg] as $i => $attachment) {
+ $attachmentData[$i] = [
'id' => $attachment['id_attach'],
'name' => Utils::entityFix(Utils::htmlspecialchars(Utils::htmlspecialcharsDecode($attachment['filename']))),
'downloads' => $attachment['downloads'],
@@ -2138,14 +2045,16 @@ public static function loadAttachmentContext($id_msg, $attachments)
'topic' => $attachment['topic'],
'board' => $attachment['board'],
'mime_type' => $attachment['mime_type'],
- );
+ ];
// If something is unapproved we'll note it so we can sort them.
- if (!$attachment['approved'])
+ if (!$attachment['approved']) {
$have_unapproved = true;
+ }
- if (!$attachmentData[$i]['is_image'])
+ if (!$attachmentData[$i]['is_image']) {
continue;
+ }
$attachmentData[$i]['real_width'] = $attachment['width'];
$attachmentData[$i]['width'] = $attachment['width'];
@@ -2162,8 +2071,7 @@ public static function loadAttachmentContext($id_msg, $attachments)
$attachment['width'] > Config::$modSettings['attachmentThumbWidth']
|| $attachment['height'] > Config::$modSettings['attachmentThumbHeight']
)
- && strlen($attachment['filename']) < 249)
- {
+ && strlen($attachment['filename']) < 249) {
// A proper thumb doesn't exist yet? Create one!
if (
empty($attachment['id_thumb'])
@@ -2173,26 +2081,20 @@ public static function loadAttachmentContext($id_msg, $attachments)
$attachment['thumb_width'] < Config::$modSettings['attachmentThumbWidth']
&& $attachment['thumb_height'] < Config::$modSettings['attachmentThumbHeight']
)
- )
- {
+ ) {
$filename = self::getFilePath($attachment['id_attach']);
$image = new Image($filename, true);
- if (!empty($image->source) && ($thumb = $image->createThumbnail(Config::$modSettings['attachmentThumbWidth'], Config::$modSettings['attachmentThumbHeight'])) !== false)
- {
+ if (!empty($image->source) && ($thumb = $image->createThumbnail(Config::$modSettings['attachmentThumbWidth'], Config::$modSettings['attachmentThumbHeight'])) !== false) {
// So what folder are we putting this image in?
- if (!empty(Config::$modSettings['currentAttachmentUploadDir']))
- {
- if (!is_array(Config::$modSettings['attachmentUploadDir']))
- {
+ if (!empty(Config::$modSettings['currentAttachmentUploadDir'])) {
+ if (!is_array(Config::$modSettings['attachmentUploadDir'])) {
Config::$modSettings['attachmentUploadDir'] = Utils::jsonDecode(Config::$modSettings['attachmentUploadDir'], true);
}
$id_folder_thumb = Config::$modSettings['currentAttachmentUploadDir'];
- }
- else
- {
+ } else {
$id_folder_thumb = 1;
}
@@ -2204,9 +2106,10 @@ public static function loadAttachmentContext($id_msg, $attachments)
$thumb_ext = $image->type === $thumb->type ? $attachment['fileext'] : ltrim(image_type_to_extension($thumb->type), '.');
// Add this beauty to the database.
- $attachment['id_thumb'] = Db::$db->insert('',
+ $attachment['id_thumb'] = Db::$db->insert(
+ '',
'{db_prefix}attachments',
- array(
+ [
'id_folder' => 'int',
'id_msg' => 'int',
'attachment_type' => 'int',
@@ -2217,8 +2120,8 @@ public static function loadAttachmentContext($id_msg, $attachments)
'height' => 'int',
'fileext' => 'string',
'mime_type' => 'string',
- ),
- array(
+ ],
+ [
$id_folder_thumb,
$id_msg,
3,
@@ -2229,48 +2132,45 @@ public static function loadAttachmentContext($id_msg, $attachments)
$thumb->height,
$thumb_ext,
$thumb->mime_type,
- ),
- array('id_attach'),
- 1
+ ],
+ ['id_attach'],
+ 1,
);
- if (!empty($attachment['id_thumb']))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}attachments
+ if (!empty($attachment['id_thumb'])) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}attachments
SET id_thumb = {int:id_thumb}
WHERE id_attach = {int:id_attach}',
- array(
+ [
'id_thumb' => $attachment['id_thumb'],
'id_attach' => $attachment['id_attach'],
- )
+ ],
);
$thumb->move(self::getFilePath($attachment['id_thumb']));
// Do we need to remove an old thumbnail?
- if (!empty($old_id_thumb))
- {
- self::remove(array('id_attach' => $old_id_thumb), '', false, false);
+ if (!empty($old_id_thumb)) {
+ self::remove(['id_attach' => $old_id_thumb], '', false, false);
}
}
}
}
// Only adjust dimensions on successful thumbnail creation.
- if (!empty($attachment['thumb_width']) && !empty($attachment['thumb_height']))
- {
+ if (!empty($attachment['thumb_width']) && !empty($attachment['thumb_height'])) {
$attachmentData[$i]['width'] = $attachment['thumb_width'];
$attachmentData[$i]['height'] = $attachment['thumb_height'];
}
}
- if (!empty($attachment['id_thumb']))
- {
- $attachmentData[$i]['thumbnail'] = array(
+ if (!empty($attachment['id_thumb'])) {
+ $attachmentData[$i]['thumbnail'] = [
'id' => $attachment['id_thumb'],
'href' => Config::$scripturl . '?action=dlattach;attach=' . $attachment['id_thumb'] . ';image;thumb',
- );
+ ];
}
$attachmentData[$i]['thumbnail']['has_thumb'] = !empty($attachment['id_thumb']);
@@ -2288,27 +2188,21 @@ public static function loadAttachmentContext($id_msg, $attachments)
&& $attachment['height'] > Config::$modSettings['max_image_height']
)
)
- )
- {
+ ) {
if (
!empty(Config::$modSettings['max_image_width'])
&& (
empty(Config::$modSettings['max_image_height'])
|| $attachment['height'] * Config::$modSettings['max_image_width'] / $attachment['width'] <= Config::$modSettings['max_image_height']
)
- )
- {
+ ) {
$attachmentData[$i]['width'] = Config::$modSettings['max_image_width'];
$attachmentData[$i]['height'] = floor($attachment['height'] * Config::$modSettings['max_image_width'] / $attachment['width']);
- }
- elseif (!empty(Config::$modSettings['max_image_width']))
- {
+ } elseif (!empty(Config::$modSettings['max_image_width'])) {
$attachmentData[$i]['width'] = floor($attachment['width'] * Config::$modSettings['max_image_height'] / $attachment['height']);
$attachmentData[$i]['height'] = Config::$modSettings['max_image_height'];
}
- }
- elseif ($attachmentData[$i]['thumbnail']['has_thumb'])
- {
+ } elseif ($attachmentData[$i]['thumbnail']['has_thumb']) {
// If the image is too large to show inline, make it a popup.
if (
(
@@ -2319,25 +2213,21 @@ public static function loadAttachmentContext($id_msg, $attachments)
!empty(Config::$modSettings['max_image_height'])
&& $attachmentData[$i]['real_height'] > Config::$modSettings['max_image_height']
)
- )
- {
+ ) {
$attachmentData[$i]['thumbnail']['javascript'] = 'return reqWin(\'' . $attachmentData[$i]['href'] . ';image\', ' . ($attachment['width'] + 20) . ', ' . ($attachment['height'] + 20) . ', true);';
- }
- else
- {
+ } else {
$attachmentData[$i]['thumbnail']['javascript'] = 'return expandThumb(' . $attachment['id_attach'] . ');';
}
}
- if (!$attachmentData[$i]['thumbnail']['has_thumb'])
+ if (!$attachmentData[$i]['thumbnail']['has_thumb']) {
$attachmentData[$i]['downloads']++;
+ }
// Describe undefined dimensions as "unknown".
// This can happen if an uploaded SVG is missing some key data.
- foreach (array('real_width', 'real_height') as $key)
- {
- if (!isset($attachmentData[$i][$key]) || $attachmentData[$i][$key] === INF)
- {
+ foreach (['real_width', 'real_height'] as $key) {
+ if (!isset($attachmentData[$i][$key]) || $attachmentData[$i][$key] === INF) {
loadLanguage('Admin');
$attachmentData[$i][$key] = ' (' . $txt['unknown'] . ') ';
}
@@ -2346,17 +2236,16 @@ public static function loadAttachmentContext($id_msg, $attachments)
}
// Do we need to instigate a sort?
- if ($have_unapproved)
- {
+ if ($have_unapproved) {
uasort(
$attachmentData,
- function($a, $b)
- {
- if ($a['is_approved'] == $b['is_approved'])
+ function ($a, $b) {
+ if ($a['is_approved'] == $b['is_approved']) {
return 0;
+ }
return $a['is_approved'] > $b['is_approved'] ? -1 : 1;
- }
+ },
);
}
@@ -2368,41 +2257,37 @@ function($a, $b)
*
* @param int array $msgIDs the message ID to load info from.
*
- * @return void
*/
public static function prepareByMsg($msgIDs)
{
- if (empty(Utils::$context['loaded_attachments']))
- {
- Utils::$context['loaded_attachments'] = array();
+ if (empty(Utils::$context['loaded_attachments'])) {
+ Utils::$context['loaded_attachments'] = [];
}
// Remove all $msgIDs that we already processed
- else
- {
- $msgIDs = array_diff($msgIDs, array_keys(Utils::$context['loaded_attachments']), array(0));
+ else {
+ $msgIDs = array_diff($msgIDs, array_keys(Utils::$context['loaded_attachments']), [0]);
}
// Ensure that $msgIDs doesn't contain zero or non-integers.
$msgIDs = array_filter(array_map('intval', $msgIDs));
- if (!empty($msgIDs) || !empty($_SESSION['attachments_can_preview']))
- {
+ if (!empty($msgIDs) || !empty($_SESSION['attachments_can_preview'])) {
$get_thumbs = !empty(Config::$modSettings['attachmentShowImages']) && !empty(Config::$modSettings['attachmentThumbnails']);
- if (!empty($msgIDs))
- {
+ if (!empty($msgIDs)) {
$loaded = self::loadByMsg($msgIDs, self::APPROVED_TRUE, self::TYPE_STANDARD, $get_thumbs);
- foreach ($loaded as $id => $attachment)
+ foreach ($loaded as $id => $attachment) {
Utils::$context['loaded_attachments'][$attachment->msg][$id] = $attachment;
+ }
}
- if (!empty($_SESSION['attachments_can_preview']))
- {
+ if (!empty($_SESSION['attachments_can_preview'])) {
$loaded = self::load(array_keys(array_filter($_SESSION['attachments_can_preview'])), self::APPROVED_TRUE, self::TYPE_STANDARD, $get_thumbs);
- foreach ($loaded as $id => $attachment)
+ foreach ($loaded as $id => $attachment) {
Utils::$context['loaded_attachments'][$attachment->msg][$id] = $attachment;
+ }
}
}
}
@@ -2419,16 +2304,11 @@ public static function prepareByMsg($msgIDs)
*/
public static function createHash(string $input = ''): string
{
- if (is_file($input))
- {
+ if (is_file($input)) {
$hash = hash_hmac_file('sha1', $input, Config::$image_proxy_secret);
- }
- elseif (strlen($input) > 0)
- {
+ } elseif (strlen($input) > 0) {
$hash = hash_hmac('sha1', $input, Config::$image_proxy_secret);
- }
- else
- {
+ } else {
$hash = bin2hex(Utils::randomBytes(20));
}
@@ -2473,8 +2353,9 @@ public static function getFilePath(int $id): string
public static function getAttachmentFilename($filename, $attachment_id, $dir = null, $new = false, $file_hash = '')
{
// Just make up a nice hash...
- if ($new || empty($attachment_id))
+ if ($new || empty($attachment_id)) {
return self::createHash();
+ }
return self::getFilePath($attachment_id);
}
@@ -2488,28 +2369,27 @@ public static function getAttachmentFilename($filename, $attachment_id, $dir = n
*/
protected function setPath(): void
{
- if (empty($this->id) || empty($this->file_hash))
+ if (empty($this->id) || empty($this->file_hash)) {
return;
+ }
// Decode the JSON string to an array.
- if (!is_array(Config::$modSettings['attachmentUploadDir']))
- {
+ if (!is_array(Config::$modSettings['attachmentUploadDir'])) {
$temp = Utils::jsonDecode(Config::$modSettings['attachmentUploadDir'], true);
- if (!is_null($temp))
+ if (!is_null($temp)) {
Config::$modSettings['attachmentUploadDir'] = $temp;
+ }
}
// Are we using multiple directories?
- if (is_array(Config::$modSettings['attachmentUploadDir']))
- {
- if (!isset(Config::$modSettings['attachmentUploadDir'][$this->folder]))
+ if (is_array(Config::$modSettings['attachmentUploadDir'])) {
+ if (!isset(Config::$modSettings['attachmentUploadDir'][$this->folder])) {
return;
+ }
$dir = Config::$modSettings['attachmentUploadDir'][$this->folder];
- }
- else
- {
+ } else {
$dir = Config::$modSettings['attachmentUploadDir'];
}
@@ -2532,15 +2412,16 @@ protected static function isPathAllowed($path)
{
$open_basedir = ini_get('open_basedir');
- if (empty($open_basedir))
+ if (empty($open_basedir)) {
return true;
+ }
$restricted_paths = explode(PATH_SEPARATOR, $open_basedir);
- foreach ($restricted_paths as $restricted_path)
- {
- if (mb_strpos($path, $restricted_path) === 0)
+ foreach ($restricted_paths as $restricted_path) {
+ if (mb_strpos($path, $restricted_path) === 0) {
return true;
+ }
}
return false;
@@ -2562,17 +2443,16 @@ protected static function getDirectoryTreeElements($directory)
* in Windows we need to explode for both \ and /
* while in linux should be safe to explode only for / (aka DIRECTORY_SEPARATOR)
*/
- if (DIRECTORY_SEPARATOR === '\\')
- {
+ if (DIRECTORY_SEPARATOR === '\\') {
$tree = preg_split('#[\\\/]#', $directory);
- }
- else
- {
- if (substr($directory, 0, 1) != DIRECTORY_SEPARATOR)
+ } else {
+ if (substr($directory, 0, 1) != DIRECTORY_SEPARATOR) {
return false;
+ }
$tree = explode(DIRECTORY_SEPARATOR, trim($directory, DIRECTORY_SEPARATOR));
}
+
return $tree;
}
@@ -2590,22 +2470,19 @@ protected static function initDir(&$tree, &$count)
$directory = '';
// If on Windows servers the first part of the path is the drive (e.g. "C:")
- if (DIRECTORY_SEPARATOR === '\\')
- {
+ if (DIRECTORY_SEPARATOR === '\\') {
// Better be sure that the first part of the path is actually a drive letter...
// ...even if, I should check this in the admin page...isn't it?
// ...NHAAA Let's leave space for users' complains! :P
- if (preg_match('/^[a-z]:$/i', $tree[0]))
- {
+ if (preg_match('/^[a-z]:$/i', $tree[0])) {
$directory = array_shift($tree);
- }
- else
- {
+ } else {
return false;
}
$count--;
}
+
return $directory;
}
@@ -2627,27 +2504,28 @@ protected static function initDir(&$tree, &$count)
*
* @return Generator Iterating over the result gives database rows.
*/
- protected static function queryData(array $selects, array $params = array(), string $from = '{db_prefix}attachments AS a', array $joins = array(), array $where = array(), array $order = array(), int $limit = 0)
+ protected static function queryData(array $selects, array $params = [], string $from = '{db_prefix}attachments AS a', array $joins = [], array $where = [], array $order = [], int $limit = 0)
{
- $request = Db::$db->query('', '
- SELECT ' . implode(', ', $selects) . '
- FROM ' . implode("\n\t\t\t\t\t", array_merge(array($from), $joins)) . (empty($where) ? '' : '
+ $request = Db::$db->query(
+ '',
+ 'SELECT ' . implode(', ', $selects) . '
+ FROM ' . implode("\n\t\t\t\t\t", array_merge([$from], $joins)) . (empty($where) ? '' : '
WHERE (' . implode(') AND (', $where) . ')') . (empty($order) ? '' : '
ORDER BY ' . implode(', ', $order)) . ($limit > 0 ? '
LIMIT ' . $limit : ''),
- $params
+ $params,
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
yield $row;
}
Db::$db->free_result($request);
}
-
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Attachment::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Attachment::exportStatic')) {
Attachment::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Autoloader.php b/Sources/Autoloader.php
index d5ca77cfc9..7587143848 100644
--- a/Sources/Autoloader.php
+++ b/Sources/Autoloader.php
@@ -13,16 +13,15 @@
namespace SMF;
-/**
+/*
* An autoloader for certain classes.
*
* @param string $class The fully-qualified class name.
*/
-spl_autoload_register(function ($class)
-{
+spl_autoload_register(function ($class) {
static $hook_value = '';
- static $class_map = array(
+ static $class_map = [
// Some special cases.
'ReCaptcha\\' => 'ReCaptcha/',
'MatthiasMullie\\Minify\\' => 'minify/src/',
@@ -30,37 +29,36 @@
// In general, the SMF namespace maps to $sourcedir.
'SMF\\' => '',
- );
+ ];
// Ensure $sourcedir is set to something valid.
- if (class_exists('SMF\\Config', false) && isset(Config::$sourcedir))
+ if (class_exists('SMF\\Config', false) && isset(Config::$sourcedir)) {
$sourcedir = Config::$sourcedir;
+ }
- if (empty($sourcedir) || !is_dir($sourcedir))
+ if (empty($sourcedir) || !is_dir($sourcedir)) {
$sourcedir = __DIR__;
+ }
// Do any third-party scripts want in on the fun?
- if (class_exists('SMF\\Config', false) && $hook_value !== (Config::$modSettings['integrate_autoload'] ?? ''))
- {
- if (!class_exists('SMF\\IntegrationHook', false) && is_file($sourcedir . '/IntegrationHook.php'))
- {
+ if (!defined('SMF_INSTALLING') && class_exists('SMF\\Config', false) && $hook_value !== (Config::$modSettings['integrate_autoload'] ?? '')) {
+ if (!class_exists('SMF\\IntegrationHook', false) && is_file($sourcedir . '/IntegrationHook.php')) {
require_once $sourcedir . '/IntegrationHook.php';
}
- if (class_exists('SMF\\IntegrationHook', false))
- {
+ if (class_exists('SMF\\IntegrationHook', false)) {
$hook_value = Config::$modSettings['integrate_autoload'];
- IntegrationHook::call('integrate_autoload', array(&$class_map));
+ IntegrationHook::call('integrate_autoload', [&$class_map]);
}
}
- foreach ($class_map as $prefix => $dirname)
- {
+ foreach ($class_map as $prefix => $dirname) {
// Does the class use the namespace prefix?
$len = strlen($prefix);
- if (strncmp($prefix, $class, $len) !== 0)
+ if (strncmp($prefix, $class, $len) !== 0) {
continue;
+ }
// Get the relative class name.
$relative_class = substr($class, $len);
@@ -71,13 +69,14 @@
$filename = $dirname . strtr($relative_class, '\\', '/') . '.php';
// Failsafe: Never load a file named index.php.
- if (basename($filename) === 'index.php')
+ if (basename($filename) === 'index.php') {
return;
+ }
// If the file exists, require it.
- if (file_exists($filename = $sourcedir . '/' . $filename))
- {
+ if (file_exists($filename = $sourcedir . '/' . $filename)) {
require $filename;
+
return;
}
}
diff --git a/Sources/BBCodeParser.php b/Sources/BBCodeParser.php
index c8757cc974..572d82707b 100644
--- a/Sources/BBCodeParser.php
+++ b/Sources/BBCodeParser.php
@@ -58,16 +58,15 @@ class BBCodeParser
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_prefix' => 'bbcodeparser_',
- 'func_names' => array(
+ private static $backcompat = [
+ 'func_names' => [
+ 'getSigTags' => 'get_signature_allowed_bbc_tags',
'highlightPhpCode' => 'highlight_php_code',
'sanitizeMSCutPaste' => 'sanitizeMSCutPaste',
'backcompatParseBbc' => 'parse_bbc',
'backcompatParseSmileys' => 'parseSmileys',
- 'getSigTags' => 'get_signature_allowed_bbc_tags',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -78,7 +77,7 @@ class BBCodeParser
*
* If not empty, only these BBCode tags will be parsed.
*/
- public $parse_tags = array();
+ public $parse_tags = [];
/**
* @var bool
@@ -99,7 +98,7 @@ class BBCodeParser
*
* List of disabled BBCode tags.
*/
- public $disabled = array();
+ public $disabled = [];
/**
* @var bool
@@ -192,7 +191,6 @@ class BBCodeParser
* want to read this list. Calling the method will ensure that any BBCodes
* added by modifications are included in the returned array.
*
- *
* The BBCode definitions are formatted as an array, with keys as follows:
*
* tag: The tag's name - should be lowercase!
@@ -281,125 +279,125 @@ class BBCodeParser
* parsed_tags_allowed: An array restricting what BBC can be in the
* parsed_equals parameter, if desired.
*/
- public static $codes = array(
- array(
+ public static $codes = [
+ [
'tag' => 'abbr',
'type' => 'unparsed_equals',
'before' => '',
'after' => '',
'quoted' => 'optional',
'disabled_after' => ' ($1)',
- ),
+ ],
// Legacy (and just an alias for [abbr] even when enabled)
- array(
+ [
'tag' => 'acronym',
'type' => 'unparsed_equals',
'before' => '',
'after' => '',
'quoted' => 'optional',
'disabled_after' => ' ($1)',
- ),
- array(
+ ],
+ [
'tag' => 'anchor',
'type' => 'unparsed_equals',
'test' => '[#]?([A-Za-z][A-Za-z0-9_\-]*)\]',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'attach',
'type' => 'unparsed_content',
- 'parameters' => array(
- 'id' => array('match' => '(\d+)'),
- 'alt' => array('optional' => true),
- 'width' => array('optional' => true, 'match' => '(\d+)'),
- 'height' => array('optional' => true, 'match' => '(\d+)'),
- 'display' => array('optional' => true, 'match' => '(link|embed)'),
- ),
+ 'parameters' => [
+ 'id' => ['match' => '(\d+)'],
+ 'alt' => ['optional' => true],
+ 'width' => ['optional' => true, 'match' => '(\d+)'],
+ 'height' => ['optional' => true, 'match' => '(\d+)'],
+ 'display' => ['optional' => true, 'match' => '(link|embed)'],
+ ],
'content' => '$1',
'validate' => __CLASS__ . '::attachValidate',
- ),
- array(
+ ],
+ [
'tag' => 'b',
'before' => '',
'after' => '',
- ),
+ ],
// Legacy (equivalent to [ltr] or [rtl])
- array(
+ [
'tag' => 'bdo',
'type' => 'unparsed_equals',
'before' => '',
'after' => '',
'test' => '(rtl|ltr)\]',
'block_level' => true,
- ),
+ ],
// Legacy (alias of [color=black])
- array(
+ [
'tag' => 'black',
'before' => '',
'after' => '',
- ),
+ ],
// Legacy (alias of [color=blue])
- array(
+ [
'tag' => 'blue',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'br',
'type' => 'closed',
'content' => ' ',
- ),
- array(
+ ],
+ [
'tag' => 'center',
'before' => '',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'code',
'type' => 'unparsed_content',
'content' => '$1 ',
'validate' => __CLASS__ . '::codeValidate',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'code',
'type' => 'unparsed_equals_content',
'content' => '$1 ',
'validate' => __CLASS__ . '::codeValidate',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'color',
'type' => 'unparsed_equals',
'test' => '(#[\da-fA-F]{3}|#[\da-fA-F]{6}|[A-Za-z]{1,20}|rgb\((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\s?,\s?){2}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\))\]',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'email',
'type' => 'unparsed_content',
'content' => '$1',
'validate' => __CLASS__ . '::emailValidate',
- ),
- array(
+ ],
+ [
'tag' => 'email',
'type' => 'unparsed_equals',
'before' => '',
'after' => '',
- 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
+ 'disallow_children' => ['email', 'ftp', 'url', 'iurl'],
'disabled_after' => ' ($1)',
- ),
+ ],
// Legacy (and just a link even when not disabled)
- array(
+ [
'tag' => 'flash',
'type' => 'unparsed_commas_content',
'test' => '\d+,\d+\]',
'content' => '$1',
'validate' => __CLASS__ . '::flashValidate',
- ),
- array(
+ ],
+ [
'tag' => 'float',
'type' => 'unparsed_equals',
'test' => '(left|right)(\s+max=\d+(?:%|px|em|rem|ex|pt|pc|ch|vw|vh|vmin|vmax|cm|mm|in)?)?\]',
@@ -408,140 +406,140 @@ class BBCodeParser
'validate' => __CLASS__ . '::floatValidate',
'trim' => 'outside',
'block_level' => true,
- ),
+ ],
// Legacy (alias of [url] with an FTP URL)
- array(
+ [
'tag' => 'ftp',
'type' => 'unparsed_content',
'content' => '$1',
'validate' => __CLASS__ . '::ftpValidate',
- ),
+ ],
// Legacy (alias of [url] with an FTP URL)
- array(
+ [
'tag' => 'ftp',
'type' => 'unparsed_equals',
'before' => '',
'after' => '',
'validate' => __CLASS__ . '::ftpValidate',
- 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
+ 'disallow_children' => ['email', 'ftp', 'url', 'iurl'],
'disabled_after' => ' ($1)',
- ),
- array(
+ ],
+ [
'tag' => 'font',
'type' => 'unparsed_equals',
'test' => '[A-Za-z0-9_,\-\s]+?\]',
'before' => '',
'after' => '',
- ),
+ ],
// Legacy (one of those things that should not be done)
- array(
+ [
'tag' => 'glow',
'type' => 'unparsed_commas',
'test' => '[#0-9a-zA-Z\-]{3,12},([012]\d{1,2}|\d{1,2})(,[^]]+)?\]',
'before' => '',
'after' => '',
- ),
+ ],
// Legacy (alias of [color=green])
- array(
+ [
'tag' => 'green',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'html',
'type' => 'unparsed_content',
'content' => '$1 ',
'block_level' => true,
'disabled_content' => '$1',
- ),
- array(
+ ],
+ [
'tag' => 'hr',
'type' => 'closed',
'content' => ' ',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'i',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'img',
'type' => 'unparsed_content',
- 'parameters' => array(
- 'alt' => array('optional' => true),
- 'title' => array('optional' => true),
- 'width' => array('optional' => true, 'value' => ' width="$1"', 'match' => '(\d+)'),
- 'height' => array('optional' => true, 'value' => ' height="$1"', 'match' => '(\d+)'),
- ),
+ 'parameters' => [
+ 'alt' => ['optional' => true],
+ 'title' => ['optional' => true],
+ 'width' => ['optional' => true, 'value' => ' width="$1"', 'match' => '(\d+)'],
+ 'height' => ['optional' => true, 'value' => ' height="$1"', 'match' => '(\d+)'],
+ ],
'content' => '$1',
'validate' => __CLASS__ . '::imgValidate',
'disabled_content' => '($1)',
- ),
- array(
+ ],
+ [
'tag' => 'iurl',
'type' => 'unparsed_content',
'content' => '$1',
'validate' => __CLASS__ . '::urlValidate',
- ),
- array(
+ ],
+ [
'tag' => 'iurl',
'type' => 'unparsed_equals',
'quoted' => 'optional',
'before' => '',
'after' => '',
'validate' => __CLASS__ . '::urlValidate',
- 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
+ 'disallow_children' => ['email', 'ftp', 'url', 'iurl'],
'disabled_after' => ' ($1)',
- ),
- array(
+ ],
+ [
'tag' => 'justify',
'before' => '',
'after' => ' ',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'left',
'before' => '',
'after' => ' ',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'li',
'before' => '',
'after' => '',
'trim' => 'outside',
- 'require_parents' => array('list'),
+ 'require_parents' => ['list'],
'block_level' => true,
'disabled_before' => '',
'disabled_after' => ' ',
- ),
- array(
+ ],
+ [
'tag' => 'list',
'before' => '',
'trim' => 'inside',
- 'require_children' => array('li', 'list'),
+ 'require_children' => ['li', 'list'],
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'list',
- 'parameters' => array(
- 'type' => array('match' => '(none|disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-alpha|upper-alpha|lower-greek|upper-greek|lower-latin|upper-latin|hebrew|armenian|georgian|cjk-ideographic|hiragana|katakana|hiragana-iroha|katakana-iroha)'),
- ),
+ 'parameters' => [
+ 'type' => ['match' => '(none|disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-alpha|upper-alpha|lower-greek|upper-greek|lower-latin|upper-latin|hebrew|armenian|georgian|cjk-ideographic|hiragana|katakana|hiragana-iroha|katakana-iroha)'],
+ ],
'before' => '',
'trim' => 'inside',
- 'require_children' => array('li'),
+ 'require_children' => ['li'],
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'ltr',
'before' => '',
'after' => '',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'me',
'type' => 'unparsed_equals',
'before' => '* $1 ',
@@ -550,57 +548,57 @@ class BBCodeParser
'block_level' => true,
'disabled_before' => '/me ',
'disabled_after' => ' ',
- ),
- array(
+ ],
+ [
'tag' => 'member',
'type' => 'unparsed_equals',
'before' => ' @',
'after' => '',
- ),
+ ],
// Legacy (horrible memories of the 1990s)
- array(
+ [
'tag' => 'move',
'before' => ' ',
'block_level' => true,
- 'disallow_children' => array('move'),
- ),
- array(
+ 'disallow_children' => ['move'],
+ ],
+ [
'tag' => 'nobbc',
'type' => 'unparsed_content',
'content' => '$1',
- ),
- array(
+ ],
+ [
'tag' => 'php',
'type' => 'unparsed_content',
'content' => ' $1',
'validate' => __CLASS__ . '::phpValidate',
'block_level' => false,
'disabled_content' => '$1',
- ),
- array(
+ ],
+ [
'tag' => 'pre',
'before' => ' ',
'after' => ' ',
- ),
- array(
+ ],
+ [
'tag' => 'quote',
'before' => ' {txt_quote}',
'after' => ' ',
'trim' => 'both',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'quote',
- 'parameters' => array(
- 'author' => array('match' => '(.{1,192}?)', 'quoted' => true),
- ),
+ 'parameters' => [
+ 'author' => ['match' => '(.{1,192}?)', 'quoted' => true],
+ ],
'before' => ' {txt_quote_from}: {author}',
'after' => ' ',
'trim' => 'both',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'quote',
'type' => 'parsed_equals',
'before' => ' {txt_quote_from}: $1',
@@ -608,171 +606,171 @@ class BBCodeParser
'trim' => 'both',
'quoted' => 'optional',
// Don't allow everything to be embedded with the author name.
- 'parsed_tags_allowed' => array('url', 'iurl', 'ftp'),
+ 'parsed_tags_allowed' => ['url', 'iurl', 'ftp'],
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'quote',
- 'parameters' => array(
- 'author' => array('match' => '([^<>]{1,192}?)'),
- 'link' => array('match' => '(?:board=\d+;)?((?:topic|threadid)=[\dmsg#\./]{1,40}(?:;start=[\dmsg#\./]{1,40})?|msg=\d+?|action=profile;u=\d+)'),
- 'date' => array('match' => '(\d+)', 'validate' => 'timeformat'),
- ),
+ 'parameters' => [
+ 'author' => ['match' => '([^<>]{1,192}?)'],
+ 'link' => ['match' => '(?:board=\d+;)?((?:topic|threadid)=[\dmsg#\./]{1,40}(?:;start=[\dmsg#\./]{1,40})?|msg=\d+?|action=profile;u=\d+)'],
+ 'date' => ['match' => '(\d+)', 'validate' => 'SMF\\Time::timeformat'],
+ ],
'before' => '{txt_quote_from}: {author} {txt_search_on} {date}',
'after' => ' ',
'trim' => 'both',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'quote',
- 'parameters' => array(
- 'author' => array('match' => '(.{1,192}?)'),
- ),
+ 'parameters' => [
+ 'author' => ['match' => '(.{1,192}?)'],
+ ],
'before' => '{txt_quote_from}: {author}',
'after' => ' ',
'trim' => 'both',
'block_level' => true,
- ),
+ ],
// Legacy (alias of [color=red])
- array(
+ [
'tag' => 'red',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'right',
'before' => '',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'rtl',
'before' => '',
'after' => '',
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 's',
'before' => '',
'after' => '',
- ),
+ ],
// Legacy (never a good idea)
- array(
+ [
'tag' => 'shadow',
'type' => 'unparsed_commas',
'test' => '[#0-9a-zA-Z\-]{3,12},(left|right|top|bottom|[0123]\d{0,2})\]',
'before' => '',
'after' => '',
'validate' => __CLASS__ . '::shadowValidate',
- ),
- array(
+ ],
+ [
'tag' => 'size',
'type' => 'unparsed_equals',
'test' => '([1-9][\d]?p[xt]|small(?:er)?|large[r]?|x[x]?-(?:small|large)|medium|(0\.[1-9]|[1-9](\.[\d][\d]?)?)?em)\]',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'size',
'type' => 'unparsed_equals',
'test' => '[1-7]\]',
'before' => '',
'after' => '',
'validate' => __CLASS__ . '::sizeValidate',
- ),
- array(
+ ],
+ [
'tag' => 'sub',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'sup',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'table',
'before' => '',
'trim' => 'inside',
- 'require_children' => array('tr'),
+ 'require_children' => ['tr'],
'block_level' => true,
- ),
- array(
+ ],
+ [
'tag' => 'td',
'before' => '',
'after' => ' | ',
- 'require_parents' => array('tr'),
+ 'require_parents' => ['tr'],
'trim' => 'outside',
'block_level' => true,
'disabled_before' => '',
'disabled_after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'time',
'type' => 'unparsed_content',
'content' => '$1',
'validate' => __CLASS__ . '::timeValidate',
- ),
- array(
+ ],
+ [
'tag' => 'tr',
'before' => '',
'after' => ' ',
- 'require_parents' => array('table'),
- 'require_children' => array('td'),
+ 'require_parents' => ['table'],
+ 'require_children' => ['td'],
'trim' => 'both',
'block_level' => true,
'disabled_before' => '',
'disabled_after' => '',
- ),
+ ],
// Legacy (the element is dead)
- array(
+ [
'tag' => 'tt',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'u',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'url',
'type' => 'unparsed_content',
'content' => '$1',
'validate' => __CLASS__ . '::urlValidate',
- ),
- array(
+ ],
+ [
'tag' => 'url',
'type' => 'unparsed_equals',
'quoted' => 'optional',
'before' => '',
'after' => '',
'validate' => __CLASS__ . '::urlValidate',
- 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
+ 'disallow_children' => ['email', 'ftp', 'url', 'iurl'],
'disabled_after' => ' ($1)',
- ),
+ ],
// Legacy (alias of [color=white])
- array(
+ [
'tag' => 'white',
'before' => '',
'after' => '',
- ),
- array(
+ ],
+ [
'tag' => 'youtube',
'type' => 'unparsed_content',
'content' => '',
'disabled_content' => 'https://www.youtube.com/watch?v=$1',
'block_level' => true,
- ),
- );
+ ],
+ ];
/**
* @var array
*
* Itemcodes are an alternative syntax for creating lists.
*/
- public static $itemcodes = array(
+ public static $itemcodes = [
'*' => 'disc',
'@' => 'disc',
'+' => 'square',
@@ -781,14 +779,14 @@ class BBCodeParser
'o' => 'circle',
'O' => 'circle',
'0' => 'circle',
- );
+ ];
/**
* @var array
*
* BBCodes whose content should be skipped when autolinking URLs.
*/
- public static $no_autolink_tags = array(
+ public static $no_autolink_tags = [
'url',
'iurl',
'email',
@@ -801,7 +799,7 @@ class BBCodeParser
'code',
'php',
'nobbc',
- );
+ ];
/**
* @var string
@@ -829,10 +827,10 @@ class BBCodeParser
*
* URI schemes that require some sort of special handling.
*/
- public static $schemes = array(
+ public static $schemes = [
// Schemes whose URI definitions require a domain name in the
// authority (or whatever the next part of the URI is).
- 'need_domain' => array(
+ 'need_domain' => [
'aaa', 'aaas', 'acap', 'acct', 'afp', 'cap', 'cid', 'coap',
'coap+tcp', 'coap+ws', 'coaps', 'coaps+tcp', 'coaps+ws', 'crid',
'cvs', 'dict', 'dns', 'feed', 'fish', 'ftp', 'git', 'go', 'gopher',
@@ -844,32 +842,32 @@ class BBCodeParser
'turn', 'turns', 'tv', 'udp', 'vemmi', 'vnc', 'webcal', 'ws', 'wss',
'xmlrpc.beep', 'xmlrpc.beeps', 'xmpp', 'z39.50', 'z39.50r',
'z39.50s',
- ),
+ ],
// Schemes that allow an empty authority ("://" followed by "/")
- 'empty_authority' => array(
+ 'empty_authority' => [
'file', 'ni', 'nih',
- ),
+ ],
// Schemes that do not use an authority but still have a reasonable
// chance of working as clickable links.
- 'no_authority' => array(
+ 'no_authority' => [
'about', 'callto', 'geo', 'gg', 'leaptofrogans', 'magnet', 'mailto',
'maps', 'news', 'ni', 'nih', 'service', 'skype', 'sms', 'tel', 'tv',
- ),
+ ],
// Schemes that should never be autolinked.
- 'forbidden' => array(
+ 'forbidden' => [
'javascript', 'data',
- ),
- );
+ ],
+ ];
/**
* @var array
*
* The 2012 list of top level domains.
*/
- public static $basic_tlds = array(
+ public static $basic_tlds = [
'com', 'net', 'org', 'edu', 'gov', 'mil', 'aero', 'asia', 'biz', 'cat',
'coop', 'info', 'int', 'jobs', 'mobi', 'museum', 'name', 'post', 'pro',
'tel', 'travel', 'xxx', 'ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am',
@@ -893,7 +891,7 @@ class BBCodeParser
'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl', 'tm', 'tn', 'to', 'tr', 'tt',
'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us', 'uy', 'uz', 'va', 'vc', 've',
'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye', 'yt', 'za', 'zm', 'zw',
- );
+ ];
/*********************
* Internal properties
@@ -939,7 +937,7 @@ class BBCodeParser
*
* Replacement values for smileys.
*/
- protected $smiley_preg_replacements = array();
+ protected $smiley_preg_replacements = [];
/**
* @var array
@@ -954,21 +952,21 @@ class BBCodeParser
* you need to add information to this variable in order to distinguish the
* guest version vs. the member version of the output.
*/
- private $cache_key_extras = array();
+ private $cache_key_extras = [];
/**
* @var array
*
* Version of self::$codes used for interal processing.
*/
- private $bbc_codes = array();
+ private $bbc_codes = [];
/**
* @var array
*
* Copies of $this->bbc_codes for different locales.
*/
- private $bbc_lang_locales = array();
+ private $bbc_lang_locales = [];
/**
* @var string
@@ -990,7 +988,7 @@ class BBCodeParser
* BBCode tags that are currently open at any given step of processing
* $this->message.
*/
- private $open_tags = array();
+ private $open_tags = [];
/**
* @var string
@@ -1025,7 +1023,7 @@ class BBCodeParser
*
* Placeholders used to protect certain strings from processing.
*/
- private $placeholders = array();
+ private $placeholders = [];
/**
* @var int
@@ -1047,7 +1045,7 @@ class BBCodeParser
*
* Holds parsed messages.
*/
- private $results = array();
+ private $results = [];
/**
* @var bool
@@ -1077,20 +1075,18 @@ public function __construct()
/**********************
* Set up localization.
**********************/
- if (!empty(Utils::$context['utf8']))
- {
+ if (!empty(Utils::$context['utf8'])) {
$this->utf8 = true;
$this->encoding = 'UTF-8';
- }
- else
- {
+ } else {
$this->encoding = !empty(Config::$modSettings['global_character_set']) ? Config::$modSettings['global_character_set'] : (!empty(Lang::$txt['lang_character_set']) ? Lang::$txt['lang_character_set'] : $this->encoding);
$this->utf8 = $this->encoding === 'UTF-8';
}
- if (!empty(Lang::$txt['lang_locale']))
+ if (!empty(Lang::$txt['lang_locale'])) {
$this->locale = Lang::$txt['lang_locale'];
+ }
$this->time_offset = User::$me->time_offset;
$this->time_format = User::$me->time_format;
@@ -1106,10 +1102,9 @@ public function __construct()
usort(
self::$codes,
- function($a, $b)
- {
+ function ($a, $b) {
return strcmp($a['tag'], $b['tag']);
- }
+ },
);
/********************
@@ -1117,11 +1112,12 @@ function($a, $b)
********************/
$this->autolink_enabled = !empty(Config::$modSettings['autoLinkUrls']);
- if (!$this->utf8)
+ if (!$this->utf8) {
self::$domain_label_chars = '0-9A-Za-z\-';
+ }
// In case a mod wants to control behaviour for a special URI scheme.
- IntegrationHook::call('integrate_autolinker_schemes', array(&self::$schemes));
+ IntegrationHook::call('integrate_autolinker_schemes', [&self::$schemes]);
/*************************
* Set up smileys parsing.
@@ -1132,9 +1128,8 @@ function($a, $b)
// Maybe a mod wants to implement an alternative method for smileys
// (e.g. emojis instead of images)
- if ($this->smiley_set !== 'none')
- {
- IntegrationHook::call('integrate_smileys', array(&$this->smiley_preg_search, &$this->smiley_preg_replacements));
+ if ($this->smiley_set !== 'none') {
+ IntegrationHook::call('integrate_smileys', [&$this->smiley_preg_search, &$this->smiley_preg_replacements]);
}
/************************
@@ -1156,11 +1151,12 @@ function($a, $b)
* @param array $parse_tags If set, only parses these tags rather than all of them.
* @return string The parsed string.
*/
- public function parse(string $message, bool $smileys = true, string $cache_id = '', array $parse_tags = array()): string
+ public function parse(string $message, bool $smileys = true, string $cache_id = '', array $parse_tags = []): string
{
// Don't waste cycles
- if (strval($message) === '')
+ if (strval($message) === '') {
return '';
+ }
// Ensure we start with a clean slate.
$this->resetRuntimeProperties();
@@ -1176,25 +1172,26 @@ public function parse(string $message, bool $smileys = true, string $cache_id =
$this->message = self::sanitizeMSCutPaste($this->message);
// If the load average is too high, don't parse the BBC.
- if ($this->highLoadAverage())
+ if ($this->highLoadAverage()) {
return $this->message;
+ }
- if (!$this->enable_bbc)
- {
- if ($this->smileys === true)
+ if (!$this->enable_bbc) {
+ if ($this->smileys === true) {
$this->message = $this->parseSmileys($this->message);
+ }
return $this->message;
}
// Allow mods access before entering $this->parseMessage.
- IntegrationHook::call('integrate_pre_parsebbc', array(&$this->message, &$this->smileys, &$cache_id, &$this->parse_tags, &$this->cache_key_extras));
+ IntegrationHook::call('integrate_pre_parsebbc', [&$this->message, &$this->smileys, &$cache_id, &$this->parse_tags, &$this->cache_key_extras]);
// If no cache id was given, make a generic one.
$cache_id = strval($cache_id) !== '' ? $cache_id : 'str' . substr(md5($this->message), 0, 7);
// Use a unique identifier key for this combination of string and settings.
- $cache_key = 'parse:' . $cache_id . '-' . md5(json_encode(array(
+ $cache_key = 'parse:' . $cache_id . '-' . md5(json_encode([
$this->message,
// Localization settings.
$this->encoding,
@@ -1218,15 +1215,17 @@ public function parse(string $message, bool $smileys = true, string $cache_id =
$this->smiley_preg_replacements,
// Additional stuff that might affect output.
$this->cache_key_extras,
- )));
+ ]));
// Have we already parsed this string?
- if (isset($this->results[$cache_key]))
+ if (isset($this->results[$cache_key])) {
return $this->results[$cache_key];
+ }
// Or maybe we cached the results recently?
- if (($this->results[$cache_key] = CacheApi::get($cache_key, 240)) != null)
+ if (($this->results[$cache_key] = CacheApi::get($cache_key, 240)) != null) {
return $this->results[$cache_key];
+ }
// Keep track of how long this takes.
$cache_t = microtime(true);
@@ -1235,11 +1234,12 @@ public function parse(string $message, bool $smileys = true, string $cache_id =
$this->parseMessage();
// Allow mods access to what $this->parseMessage created.
- IntegrationHook::call('integrate_post_parsebbc', array(&$this->message, &$this->smileys, &$cache_id, &$this->parse_tags));
+ IntegrationHook::call('integrate_post_parsebbc', [&$this->message, &$this->smileys, &$cache_id, &$this->parse_tags]);
// Cache the output if it took some time...
- if (!empty(CacheApi::$enable) && microtime(true) - $cache_t > pow(50, -CacheApi::$enable))
+ if (!empty(CacheApi::$enable) && microtime(true) - $cache_t > pow(50, -CacheApi::$enable)) {
CacheApi::put($cache_key, $this->message, 240);
+ }
// Remember for later.
$this->results[$cache_key] = $this->message;
@@ -1260,46 +1260,44 @@ public function parse(string $message, bool $smileys = true, string $cache_id =
*/
public function parseSmileys(string $message): string
{
- if ($this->smiley_set == 'none' || trim($message) == '')
+ if ($this->smiley_set == 'none' || trim($message) == '') {
return $message;
+ }
// If smileyPregSearch hasn't been set, do it now.
- if (empty($this->smiley_preg_search))
- {
+ if (empty($this->smiley_preg_search)) {
// Cache for longer when customized smiley codes aren't enabled
$cache_time = !$this->custom_smileys_enabled ? 7200 : 480;
// Load the smileys in reverse order by length so they don't get parsed incorrectly.
- if (($temp = CacheApi::get('parsing_smileys_' . $this->smiley_set, $cache_time)) == null)
- {
- $smileysfrom = array();
- $smileysto = array();
- $smileysdescs = array();
-
- $result = Db::$db->query('', '
- SELECT s.code, f.filename, s.description
+ if (($temp = CacheApi::get('parsing_smileys_' . $this->smiley_set, $cache_time)) == null) {
+ $smileysfrom = [];
+ $smileysto = [];
+ $smileysdescs = [];
+
+ $result = Db::$db->query(
+ '',
+ 'SELECT s.code, f.filename, s.description
FROM {db_prefix}smileys AS s
JOIN {db_prefix}smiley_files AS f ON (s.id_smiley = f.id_smiley)
WHERE f.smiley_set = {string:smiley_set}' . (!$this->custom_smileys_enabled ? '
AND s.code IN ({array_string:default_codes})' : '') . '
ORDER BY LENGTH(s.code) DESC',
- array(
- 'default_codes' => array('>:D', ':D', '::)', '>:(', ':))', ':)', ';)', ';D', ':(', ':o', '8)', ':P', '???', ':-[', ':-X', ':-*', ':\'(', ':-\\', '^-^', 'O0', 'C:-)', 'O:-)'),
+ [
+ 'default_codes' => ['>:D', ':D', '::)', '>:(', ':))', ':)', ';)', ';D', ':(', ':o', '8)', ':P', '???', ':-[', ':-X', ':-*', ':\'(', ':-\\', '^-^', 'O0', 'C:-)', 'O:-)'],
'smiley_set' => $this->smiley_set,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$smileysfrom[] = $row['code'];
$smileysto[] = Utils::htmlspecialchars($row['filename']);
$smileysdescs[] = !empty(Lang::$txt['icon_' . strtolower($row['description'])]) ? Lang::$txt['icon_' . strtolower($row['description'])] : $row['description'];
}
Db::$db->free_result($result);
- CacheApi::put('parsing_smileys_' . $this->smiley_set, array($smileysfrom, $smileysto, $smileysdescs), $cache_time);
- }
- else
- {
+ CacheApi::put('parsing_smileys_' . $this->smiley_set, [$smileysfrom, $smileysto, $smileysdescs], $cache_time);
+ } else {
list($smileysfrom, $smileysto, $smileysdescs) = $temp;
}
@@ -1307,28 +1305,27 @@ public function parseSmileys(string $message): string
$non_breaking_space = $this->utf8 ? '\x{A0}' : '\xA0';
// This smiley regex makes sure it doesn't parse smileys within code tags (so [url=mailto:David@bla.com] doesn't parse the :D smiley)
- $this->smiley_preg_replacements = array();
- $search_parts = array();
+ $this->smiley_preg_replacements = [];
+ $search_parts = [];
$smileys_path = Utils::htmlspecialchars($this->smileys_url . '/' . rawurlencode($this->smiley_set) . '/');
- for ($i = 0, $n = count($smileysfrom); $i < $n; $i++)
- {
+ for ($i = 0, $n = count($smileysfrom); $i < $n; $i++) {
$special_chars = Utils::htmlspecialchars($smileysfrom[$i], ENT_QUOTES);
- $smiley_code = '';
+ $smiley_code = '';
$this->smiley_preg_replacements[$smileysfrom[$i]] = $smiley_code;
$search_parts[] = $smileysfrom[$i];
- if ($smileysfrom[$i] != $special_chars)
- {
+
+ if ($smileysfrom[$i] != $special_chars) {
$this->smiley_preg_replacements[$special_chars] = $smiley_code;
$search_parts[] = $special_chars;
// Some 2.0 hex htmlchars are in there as 3 digits; allow for finding leading 0 or not
$special_chars2 = preg_replace('/(\d{2});/', '$1;', $special_chars);
- if ($special_chars2 != $special_chars)
- {
+
+ if ($special_chars2 != $special_chars) {
$this->smiley_preg_replacements[$special_chars2] = $smiley_code;
$search_parts[] = $special_chars2;
}
@@ -1339,17 +1336,17 @@ public function parseSmileys(string $message): string
}
// If there are no smileys defined, no need to replace anything
- if (empty($this->smiley_preg_replacements))
+ if (empty($this->smiley_preg_replacements)) {
return $message;
+ }
// Replace away!
return preg_replace_callback(
$this->smiley_preg_search,
- function($matches)
- {
+ function ($matches) {
return $this->smiley_preg_replacements[$matches[1]];
},
- $message
+ $message,
);
}
@@ -1364,36 +1361,34 @@ function($matches)
public function unparse(string $string): string
{
// Replace newlines with spaces, as that's how browsers usually interpret them.
- $string = preg_replace("~\s*[\r\n]+\s*~", ' ', $string);
+ $string = preg_replace('~\s*[\r\n]+\s*~', ' ', $string);
// Though some of us love paragraphs, the parser will do better with breaks.
$string = preg_replace('~\s*?
\s*(?!<)~i', ' ', $string);
// Safari/webkit wraps lines in Wysiwyg in 's.
- if (BrowserDetector::isBrowser('webkit'))
- {
- $string = preg_replace(array('~ ]*?))?' . '>~i', ' '), array(' ', ''), $string);
+ if (BrowserDetector::isBrowser('webkit')) {
+ $string = preg_replace(['~ ]*?))?' . '>~i', ' '], [' ', ''], $string);
}
// If there's a trailing break get rid of it - Firefox tends to add one.
$string = preg_replace('~ $~i', '', $string);
// Remove any formatting within code tags.
- if (strpos($string, '[code') !== false)
- {
+ if (strpos($string, '[code') !== false) {
$string = preg_replace('~ ~i', '#smf_br_spec_grudge_cool!#', $string);
$parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
// Only mess with stuff outside [code] tags.
- for ($i = 0, $n = count($parts); $i < $n; $i++)
- {
+ for ($i = 0, $n = count($parts); $i < $n; $i++) {
// Value of 2 means we're inside the tag.
- if ($i % 4 == 2)
+ if ($i % 4 == 2) {
$parts[$i] = strip_tags($parts[$i]);
+ }
}
- $string = strtr(implode('', $parts), array('#smf_br_spec_grudge_cool!#' => ' '));
+ $string = strtr(implode('', $parts), ['#smf_br_spec_grudge_cool!#' => ' ']);
}
// Remove scripts, style and comment blocks.
@@ -1405,28 +1400,24 @@ public function unparse(string $string): string
// Do the smileys ultra first!
preg_match_all('~ ]+alt="([^"]+)"[^>]+class="smiley"[^>]*>(?:\s)?~i', $string, $matches);
- if (!empty($matches[0]))
- {
+ if (!empty($matches[0])) {
// Get all our smiley codes
- $request = Db::$db->query('', '
- SELECT code
+ $request = Db::$db->query(
+ '',
+ 'SELECT code
FROM {db_prefix}smileys
ORDER BY LENGTH(code) DESC',
- array()
+ [],
);
$smiley_codes = Db::$db->fetch_all($request);
Db::$db->free_result($request);
- foreach ($matches[1] as $k => $possible_code)
- {
+ foreach ($matches[1] as $k => $possible_code) {
$possible_code = Utils::htmlspecialcharsDecode($possible_code);
- if (in_array($possible_code, $smiley_codes))
- {
+ if (in_array($possible_code, $smiley_codes)) {
$matches[1][$k] = '-[]-smf_smily_start#|#' . $possible_code . '-[]-smf_smily_end#|#';
- }
- else
- {
+ } else {
$matches[1][$k] = $matches[0][$k];
}
}
@@ -1435,92 +1426,81 @@ public function unparse(string $string): string
$string = str_replace($matches[0], $matches[1], $string);
// Now sort out spaces
- $string = str_replace(array('-[]-smf_smily_end#|#-[]-smf_smily_start#|#', '-[]-smf_smily_end#|#', '-[]-smf_smily_start#|#'), ' ', $string);
+ $string = str_replace(['-[]-smf_smily_end#|#-[]-smf_smily_start#|#', '-[]-smf_smily_end#|#', '-[]-smf_smily_start#|#'], ' ', $string);
}
// Only try to buy more time if the client didn't quit.
- if (connection_aborted() && Utils::$context['server']['is_apache'])
+ if (connection_aborted() && Utils::$context['server']['is_apache']) {
@apache_reset_timeout();
+ }
$parts = preg_split('~(<[A-Za-z]+\s*[^<>]*?style="?[^<>"]+"?[^<>]*?(?:/?)>|[A-Za-z]+>)~', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
$replacement = '';
- $stack = array();
+ $stack = [];
- foreach ($parts as $part)
- {
+ foreach ($parts as $part) {
// Opening tag.
- if (preg_match('~(<([A-Za-z]+)\s*[^<>]*?)style="?([^<>"]+)"?([^<>]*?(/?)>)~', $part, $matches) === 1)
- {
+ if (preg_match('~(<([A-Za-z]+)\s*[^<>]*?)style="?([^<>"]+)"?([^<>]*?(/?)>)~', $part, $matches) === 1) {
// If it's being closed instantly, we can't deal with it...yet.
- if ($matches[5] === '/')
+ if ($matches[5] === '/') {
continue;
+ }
// Get an array of styles that apply to this element. (The strtr is there to combat HTML generated by Word.)
- $styles = explode(';', strtr($matches[3], array('"' => '')));
+ $styles = explode(';', strtr($matches[3], ['"' => '']));
$curElement = $matches[2];
$precedingStyle = $matches[1];
$afterStyle = $matches[4];
$curCloseTags = '';
$extra_attr = '';
- foreach ($styles as $type_value_pair)
- {
+ foreach ($styles as $type_value_pair) {
// Remove spaces and convert uppercase letters.
$clean_type_value_pair = strtolower(strtr(trim($type_value_pair), '=', ':'));
// Something like 'font-weight: bold' is expected here.
- if (strpos($clean_type_value_pair, ':') === false)
+ if (strpos($clean_type_value_pair, ':') === false) {
continue;
+ }
// Capture the elements of a single style item (e.g. 'font-weight' and 'bold').
- list ($style_type, $style_value) = explode(':', $type_value_pair);
+ list($style_type, $style_value) = explode(':', $type_value_pair);
$style_value = trim($style_value);
- switch (trim($style_type))
- {
+ switch (trim($style_type)) {
case 'font-weight':
- if ($style_value === 'bold')
- {
+ if ($style_value === 'bold') {
$curCloseTags .= '[/b]';
$replacement .= '[b]';
}
break;
case 'text-decoration':
- if ($style_value == 'underline')
- {
+ if ($style_value == 'underline') {
$curCloseTags .= '[/u]';
$replacement .= '[u]';
- }
- elseif ($style_value == 'line-through')
- {
+ } elseif ($style_value == 'line-through') {
$curCloseTags .= '[/s]';
$replacement .= '[s]';
}
break;
case 'text-align':
- if ($style_value == 'left')
- {
+ if ($style_value == 'left') {
$curCloseTags .= '[/left]';
$replacement .= '[left]';
- }
- elseif ($style_value == 'center')
- {
+ } elseif ($style_value == 'center') {
$curCloseTags .= '[/center]';
$replacement .= '[center]';
- }
- elseif ($style_value == 'right')
- {
+ } elseif ($style_value == 'right') {
$curCloseTags .= '[/right]';
$replacement .= '[right]';
}
break;
case 'font-style':
- if ($style_value == 'italic')
- {
+ if ($style_value == 'italic') {
$curCloseTags .= '[/i]';
$replacement .= '[i]';
}
@@ -1533,8 +1513,7 @@ public function unparse(string $string): string
case 'font-size':
// Sometimes people put decimals where decimals should not be.
- if (preg_match('~(\d)+\.\d+(p[xt])~i', $style_value, $dec_matches) === 1)
- {
+ if (preg_match('~(\d)+\.\d+(p[xt])~i', $style_value, $dec_matches) === 1) {
$style_value = $dec_matches[1] . $dec_matches[2];
}
@@ -1544,66 +1523,63 @@ public function unparse(string $string): string
case 'font-family':
// Only get the first freaking font if there's a list!
- if (strpos($style_value, ',') !== false)
+ if (strpos($style_value, ',') !== false) {
$style_value = substr($style_value, 0, strpos($style_value, ','));
+ }
$curCloseTags .= '[/font]';
- $replacement .= '[font=' . strtr($style_value, array("'" => '')) . ']';
+ $replacement .= '[font=' . strtr($style_value, ["'" => '']) . ']';
break;
// This is a hack for images with dimensions embedded.
case 'width':
case 'height':
- if (preg_match('~[1-9]\d*~i', $style_value, $dimension) === 1)
+ if (preg_match('~[1-9]\d*~i', $style_value, $dimension) === 1) {
$extra_attr .= ' ' . $style_type . '="' . $dimension[0] . '"';
+ }
break;
case 'list-style-type':
- if (preg_match('~none|disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-alpha|upper-alpha|lower-greek|lower-latin|upper-latin|hebrew|armenian|georgian|cjk-ideographic|hiragana|katakana|hiragana-iroha|katakana-iroha~i', $style_value, $listType) === 1)
+ if (preg_match('~none|disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-alpha|upper-alpha|lower-greek|lower-latin|upper-latin|hebrew|armenian|georgian|cjk-ideographic|hiragana|katakana|hiragana-iroha|katakana-iroha~i', $style_value, $listType) === 1) {
$extra_attr .= ' listtype="' . $listType[0] . '"';
+ }
break;
}
}
// Preserve some tags stripping the styling.
- if (in_array($matches[2], array('a', 'font', 'td')))
- {
+ if (in_array($matches[2], ['a', 'font', 'td'])) {
$replacement .= $precedingStyle . $afterStyle;
$curCloseTags = '' . $matches[2] . '>' . $curCloseTags;
}
// If there's something that still needs closing, push it to the stack.
- if (!empty($curCloseTags))
- {
- array_push($stack, array(
+ if (!empty($curCloseTags)) {
+ array_push(
+ $stack,
+ [
'element' => strtolower($curElement),
- 'closeTags' => $curCloseTags
- )
+ 'closeTags' => $curCloseTags,
+ ],
);
- }
- elseif (!empty($extra_attr))
- {
+ } elseif (!empty($extra_attr)) {
$replacement .= $precedingStyle . $extra_attr . $afterStyle;
}
}
// Closing tag.
- elseif (preg_match('~([A-Za-z]+)>~', $part, $matches) === 1)
- {
+ elseif (preg_match('~([A-Za-z]+)>~', $part, $matches) === 1) {
// Is this the element that we've been waiting for to be closed?
- if (!empty($stack) && strtolower($matches[1]) === $stack[count($stack) - 1]['element'])
- {
+ if (!empty($stack) && strtolower($matches[1]) === $stack[count($stack) - 1]['element']) {
$byebyeTag = array_pop($stack);
$replacement .= $byebyeTag['closeTags'];
}
// Must've been something else.
- else
- {
+ else {
$replacement .= $part;
}
}
// In all other cases, just add the part to the replacement.
- else
- {
+ else {
$replacement .= $part;
}
}
@@ -1612,21 +1588,21 @@ public function unparse(string $string): string
$string = $replacement;
// We are not finished yet, request more time.
- if (connection_aborted() && Utils::$context['server']['is_apache'])
+ if (connection_aborted() && Utils::$context['server']['is_apache']) {
@apache_reset_timeout();
+ }
// Let's pull out any legacy alignments.
- while (preg_match('~<([A-Za-z]+)\s+[^<>]*?(align="*(left|center|right)"*)[^<>]*?(/?)>~i', $string, $matches) === 1)
- {
+ while (preg_match('~<([A-Za-z]+)\s+[^<>]*?(align="*(left|center|right)"*)[^<>]*?(/?)>~i', $string, $matches) === 1) {
// Find the position in the text of this tag over again.
$start_pos = strpos($string, $matches[0]);
- if ($start_pos === false)
+ if ($start_pos === false) {
break;
+ }
// End tag?
- if ($matches[4] != '/' && strpos($string, '' . $matches[1] . '>', $start_pos) !== false)
- {
+ if ($matches[4] != '/' && strpos($string, '' . $matches[1] . '>', $start_pos) !== false) {
$end_pos = strpos($string, '' . $matches[1] . '>', $start_pos);
// Remove the align from that tag so it's never checked again.
@@ -1636,23 +1612,21 @@ public function unparse(string $string): string
// Put the tags back into the body.
$string = substr($string, 0, $start_pos) . $tag . '[' . $matches[3] . ']' . $content . '[/' . $matches[3] . ']' . substr($string, $end_pos);
- }
- else
- {
+ } else {
// Just get rid of this evil tag.
$string = substr($string, 0, $start_pos) . substr($string, $start_pos + strlen($matches[0]));
}
}
// Let's do some special stuff for fonts - cause we all love fonts.
- while (preg_match('~ ]*)>~i', $string, $matches) === 1)
- {
+ while (preg_match('~]*)>~i', $string, $matches) === 1) {
// Find the position of this again.
$start_pos = strpos($string, $matches[0]);
$end_pos = false;
- if ($start_pos === false)
+ if ($start_pos === false) {
break;
+ }
// This must have an end tag - and we must find the right one.
$lower_text = strtolower($string);
@@ -1661,68 +1635,59 @@ public function unparse(string $string): string
$start_pos_test = $start_pos + 4;
$start_font_tag_stack = 0;
- while ($start_pos_test < strlen($string))
- {
+ while ($start_pos_test < strlen($string)) {
// Where is the next starting font?
$next_start_pos = strpos($lower_text, '', $start_pos_test);
// Did we past another starting tag before an end one?
- if ($next_start_pos !== false && $next_start_pos < $next_end_pos)
- {
+ if ($next_start_pos !== false && $next_start_pos < $next_end_pos) {
$start_font_tag_stack++;
$start_pos_test = $next_start_pos + 4;
}
// Otherwise we have an end tag but not the right one?
- elseif ($start_font_tag_stack)
- {
+ elseif ($start_font_tag_stack) {
$start_font_tag_stack--;
$start_pos_test = $next_end_pos + 4;
}
// Otherwise we're there!
- else
- {
+ else {
$end_pos = $next_end_pos;
break;
}
}
- if ($end_pos === false)
+ if ($end_pos === false) {
break;
+ }
// Now work out what the attributes are.
$attribs = self::fetchTagAttributes($matches[1]);
- $tags = array();
- $sizes_equivalence = array(1 => '8pt', '10pt', '12pt', '14pt', '18pt', '24pt', '36pt');
+ $tags = [];
+ $sizes_equivalence = [1 => '8pt', '10pt', '12pt', '14pt', '18pt', '24pt', '36pt'];
- foreach ($attribs as $s => $v)
- {
- if ($s == 'size')
- {
+ foreach ($attribs as $s => $v) {
+ if ($s == 'size') {
// Cast before empty check because casting a string results in a 0 and we don't have zeros in the array! ;)
$v = (int) trim($v);
$v = empty($v) ? 1 : $v;
- $tags[] = array('[size=' . $sizes_equivalence[$v] . ']', '[/size]');
- }
- elseif ($s == 'face')
- {
- $tags[] = array('[font=' . trim(strtolower($v)) . ']', '[/font]');
- }
- elseif ($s == 'color')
- {
- $tags[] = array('[color=' . trim(strtolower($v)) . ']', '[/color]');
+ $tags[] = ['[size=' . $sizes_equivalence[$v] . ']', '[/size]'];
+ } elseif ($s == 'face') {
+ $tags[] = ['[font=' . trim(strtolower($v)) . ']', '[/font]'];
+ } elseif ($s == 'color') {
+ $tags[] = ['[color=' . trim(strtolower($v)) . ']', '[/color]'];
}
}
// As before add in our tags.
$before = $after = '';
- foreach ($tags as $tag)
- {
+ foreach ($tags as $tag) {
$before .= $tag[0];
- if (isset($tag[1]))
+ if (isset($tag[1])) {
$after = $tag[1] . $after;
+ }
}
// Remove the tag so it's never checked again.
@@ -1733,11 +1698,11 @@ public function unparse(string $string): string
}
// Almost there, just a little more time.
- if (connection_aborted() && Utils::$context['server']['is_apache'])
+ if (connection_aborted() && Utils::$context['server']['is_apache']) {
@apache_reset_timeout();
+ }
- if (count($parts = preg_split('~<(/?)(li|ol|ul)([^>]*)>~i', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
- {
+ if (count($parts = preg_split('~<(/?)(li|ol|ul)([^>]*)>~i', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1) {
// A toggle that determines whether we're directly under a or .
$inList = false;
@@ -1745,7 +1710,7 @@ public function unparse(string $string): string
$listDepth = 0;
// Map what we can expect from the HTML to what is supported by SMF.
- $listTypeMapping = array(
+ $listTypeMapping = [
'1' => 'decimal',
'A' => 'upper-alpha',
'a' => 'lower-alpha',
@@ -1754,30 +1719,26 @@ public function unparse(string $string): string
'disc' => 'disc',
'square' => 'square',
'circle' => 'circle',
- );
+ ];
// $i: text, $i + 1: '/', $i + 2: tag, $i + 3: tail.
- for ($i = 0, $numParts = count($parts) - 1; $i < $numParts; $i += 4)
- {
+ for ($i = 0, $numParts = count($parts) - 1; $i < $numParts; $i += 4) {
$tag = strtolower($parts[$i + 2]);
$is_opening_tag = $parts[$i + 1] === '';
- if ($is_opening_tag)
- {
- switch ($tag)
- {
+ if ($is_opening_tag) {
+ switch ($tag) {
case 'ol':
case 'ul':
// We have a problem, we're already in a list.
- if ($inList)
- {
+ if ($inList) {
// Inject a list opener, we'll deal with the ol/ul next loop.
- array_splice($parts, $i, 0, array(
+ array_splice($parts, $i, 0, [
'',
'',
str_repeat("\t", $listDepth) . '[li]',
'',
- ));
+ ]);
$numParts = count($parts) - 1;
// The inlist status changes a bit.
@@ -1785,20 +1746,14 @@ public function unparse(string $string): string
}
// Just starting a new list.
- else
- {
+ else {
$inList = true;
- if ($tag === 'ol')
- {
+ if ($tag === 'ol') {
$listType = 'decimal';
- }
- elseif (preg_match('~type="?(' . implode('|', array_keys($listTypeMapping)) . ')"?~', $parts[$i + 3], $match) === 1)
- {
+ } elseif (preg_match('~type="?(' . implode('|', array_keys($listTypeMapping)) . ')"?~', $parts[$i + 3], $match) === 1) {
$listType = $listTypeMapping[$match[1]];
- }
- else
- {
+ } else {
$listType = null;
}
@@ -1811,8 +1766,7 @@ public function unparse(string $string): string
case 'li':
// This is how it should be: a list item inside the list.
- if ($inList)
- {
+ if ($inList) {
$parts[$i + 2] = str_repeat("\t", $listDepth) . '[li]';
$parts[$i + 3] = '';
@@ -1821,18 +1775,15 @@ public function unparse(string $string): string
}
// The li is no direct child of a list.
- else
- {
+ else {
// We are apparently in a list item.
- if ($listDepth > 0)
- {
+ if ($listDepth > 0) {
$parts[$i + 2] = '[/li]' . "\n" . str_repeat("\t", $listDepth) . '[li]';
$parts[$i + 3] = '';
}
// We're not even near a list.
- else
- {
+ else {
// Quickly create a list with an item.
$listDepth++;
@@ -1845,15 +1796,12 @@ public function unparse(string $string): string
}
// Handle all the closing tags.
- else
- {
- switch ($tag)
- {
+ else {
+ switch ($tag) {
case 'ol':
case 'ul':
// As we expected it, closing the list while we're in it.
- if ($inList)
- {
+ if ($inList) {
$inList = false;
$listDepth--;
@@ -1861,28 +1809,24 @@ public function unparse(string $string): string
$parts[$i + 1] = '';
$parts[$i + 2] = str_repeat("\t", $listDepth) . '[/list]';
$parts[$i + 3] = '';
- }
- else
- {
+ } else {
// We're in a list item.
- if ($listDepth > 0)
- {
+ if ($listDepth > 0) {
// Inject closure for this list item first.
// The content of $parts[$i] is left as is!
- array_splice($parts, $i + 1, 0, array(
+ array_splice($parts, $i + 1, 0, [
'', // $i + 1
'[/li]' . "\n", // $i + 2
'', // $i + 3
'', // $i + 4
- ));
+ ]);
$numParts = count($parts) - 1;
// Now that we've closed the li, we're in list space.
$inList = true;
}
// We're not even in a list, ignore
- else
- {
+ else {
$parts[$i + 1] = '';
$parts[$i + 2] = '';
$parts[$i + 3] = '';
@@ -1891,15 +1835,12 @@ public function unparse(string $string): string
break;
case 'li':
- if ($inList)
- {
+ if ($inList) {
// There's no use for a after or ~i' => function () {
return '[/tr]';
},
- '~<(td|th)\s[^<>]*?colspan="?(\d{1,2})"?.*?' . '>~i' => function($matches)
- {
+ '~<(td|th)\s[^<>]*?colspan="?(\d{1,2})"?.*?' . '>~i' => function ($matches) {
return str_repeat('[td][/td]', $matches[2] - 1) . '[td]';
},
- '~<(td|th)(\s(.)*?)*?' . '>~i' => function()
- {
+ '~<(td|th)(\s(.)*?)*?' . '>~i' => function () {
return '[td]';
},
- '~(td|th)>~i' => function()
- {
+ '~(td|th)>~i' => function () {
return '[/td]';
},
- '~ ]*?)?' . '>~i' => function()
- {
+ '~ ]*?)?' . '>~i' => function () {
return "\n";
},
- '~ ]*>(\n)?~i' => function($matches)
- {
+ '~ ]*>(\n)?~i' => function ($matches) {
return "[hr]\n" . $matches[0];
},
- '~(\n)?\\[hr\\]~i' => function()
- {
+ '~(\n)?\[hr\]~i' => function () {
return "\n[hr]";
},
- '~^\n\\[hr\\]~i' => function()
- {
- return "[hr]";
+ '~^\n\[hr\]~i' => function () {
+ return '[hr]';
},
- '~~i' => function()
- {
- return "<blockquote>";
+ '~~i' => function () {
+ return '<blockquote>';
},
- '~ ~i' => function()
- {
- return "</blockquote>";
+ '~ ~i' => function () {
+ return '</blockquote>';
},
- '~~i' => function()
- {
- return "<ins>";
+ '~~i' => function () {
+ return '<ins>';
},
- '~~i' => function()
- {
- return "</ins>";
+ '~~i' => function () {
+ return '</ins>';
},
- );
+ ];
- foreach ($tags as $tag => $replace)
+ foreach ($tags as $tag => $replace) {
$string = preg_replace_callback($tag, $replace, $string);
+ }
// Please give us just a little more time.
- if (connection_aborted() && Utils::$context['server']['is_apache'])
+ if (connection_aborted() && Utils::$context['server']['is_apache']) {
@apache_reset_timeout();
+ }
// What about URL's - the pain in the ass of the tag world.
- while (preg_match('~]*)>([^<>]*)~i', $string, $matches) === 1)
- {
+ while (preg_match('~]*)>([^<>]*)~i', $string, $matches) === 1) {
// Find the position of the URL.
$start_pos = strpos($string, $matches[0]);
- if ($start_pos === false)
+ if ($start_pos === false) {
break;
+ }
$end_pos = $start_pos + strlen($matches[0]);
@@ -2191,58 +2081,46 @@ public function unparse(string $string): string
$attrs = self::fetchTagAttributes($matches[1]);
- foreach ($attrs as $attrib => $value)
- {
- if ($attrib == 'href')
- {
+ foreach ($attrs as $attrib => $value) {
+ if ($attrib == 'href') {
$href = new Url(trim($value));
$our_url = new Url(Config::$boardurl);
// Are we dealing with an FTP link?
- if (in_array($href->scheme, array('ftp', 'ftps')))
- {
+ if (in_array($href->scheme, ['ftp', 'ftps'])) {
$tag_type = 'ftp';
}
// Or is this a link to an email address?
- elseif ($href->scheme == 'mailto')
- {
+ elseif ($href->scheme == 'mailto') {
$tag_type = 'email';
$href = $href->path;
}
// No http(s), so attempt to fix this potential relative URL.
- elseif (!in_array($href->scheme, array('http', 'https')) && isset($our_url->host))
- {
+ elseif (!in_array($href->scheme, ['http', 'https']) && isset($our_url->host)) {
$base_url = ($our_url->scheme ?? 'http') . '://' . $our_url->host . (empty($our_url->port) ? '' : ':' . $our_url->port);
- if (substr($href, 0, 1) === '/')
- {
+ if (substr($href, 0, 1) === '/') {
$href = $base_url . $href;
- }
- else
- {
+ } else {
$href = $base_url . '/' . trim($our_url->path, '/') . '/' . $href;
}
}
}
// External URL?
- if ($attrib == 'target' && $tag_type == 'url')
- {
- if (trim($value) == '_blank')
+ if ($attrib == 'target' && $tag_type == 'url') {
+ if (trim($value) == '_blank') {
$tag_type == 'iurl';
+ }
}
}
$tag = '';
- if ($href != '')
- {
- if ($matches[2] == $href)
- {
+ if ($href != '') {
+ if ($matches[2] == $href) {
$tag = '[' . $tag_type . ']' . $href . '[/' . $tag_type . ']';
- }
- else
- {
+ } else {
$tag = '[' . $tag_type . '=' . $href . ']' . $matches[2] . '[/' . $tag_type . ']';
}
}
@@ -2279,8 +2157,9 @@ public function unparse(string $string): string
*/
public static function load(bool $init = false): object
{
- if (!isset(self::$parser) || !empty($init))
+ if (!isset(self::$parser) || !empty($init)) {
self::$parser = new self();
+ }
return self::$parser;
}
@@ -2306,25 +2185,28 @@ public static function getSigTags(): array
{
list($sig_limits, $sig_bbc) = explode(':', Config::$modSettings['signature_settings']);
- if (empty($sig_bbc))
- return array();
+ if (empty($sig_bbc)) {
+ return [];
+ }
$disabled_tags = explode(',', $sig_bbc);
// Get all available bbc tags
$temp = self::getCodes();
- $allowed_tags = array();
+ $allowed_tags = [];
- foreach ($temp as $tag)
- {
- if (!in_array($tag['tag'], $disabled_tags))
+ foreach ($temp as $tag) {
+ if (!in_array($tag['tag'], $disabled_tags)) {
$allowed_tags[] = $tag['tag'];
+ }
}
$allowed_tags = array_unique($allowed_tags);
- if (empty($allowed_tags))
+
+ if (empty($allowed_tags)) {
// An empty array means that all bbc tags are allowed. So if all tags are disabled we need to add a dummy tag.
$allowed_tags[] = 'nonexisting';
+ }
return $allowed_tags;
}
@@ -2342,18 +2224,18 @@ public static function getSigTags(): array
public static function highlightPhpCode(string $code): string
{
// Remove special characters.
- $code = Utils::htmlspecialcharsDecode(strtr($code, array(' ' => "\n", ' ' => "\n", "\t" => 'SMF_TAB();', '[' => '[')));
+ $code = Utils::htmlspecialcharsDecode(strtr($code, [' ' => "\n", ' ' => "\n", "\t" => 'SMF_TAB();', '[' => '[']));
$oldlevel = error_reporting(0);
- $buffer = str_replace(array("\n", "\r"), '', @highlight_string($code, true));
+ $buffer = str_replace(["\n", "\r"], '', @highlight_string($code, true));
error_reporting($oldlevel);
// Yes, I know this is kludging it, but this is the best way to preserve tabs from PHP :P.
- $buffer = preg_replace('~SMF_TAB(?:(?:font|span)><(?:font color|span style)="[^"]*?">)?\\(\\);~', '' . "\t" . ' ', $buffer);
+ $buffer = preg_replace('~SMF_TAB(?:(?:font|span)><(?:font color|span style)="[^"]*?">)?\(\);~', '' . "\t" . ' ', $buffer);
- return strtr($buffer, array('\'' => ''', '' => '', ' ' => ''));
+ return strtr($buffer, ['\'' => ''', '' => '', ' ' => '']);
}
/**
@@ -2367,13 +2249,14 @@ public static function highlightPhpCode(string $code): string
*/
public static function sanitizeMSCutPaste(string $string): string
{
- if (empty($string))
+ if (empty($string)) {
return $string;
+ }
self::load();
// UTF-8 occurrences of MS special characters.
- $findchars_utf8 = array(
+ $findchars_utf8 = [
"\xe2\x80\x9a", // single low-9 quotation mark
"\xe2\x80\x9e", // double low-9 quotation mark
"\xe2\x80\xa6", // horizontal ellipsis
@@ -2381,10 +2264,10 @@ public static function sanitizeMSCutPaste(string $string): string
"\xe2\x80\x99", // right single curly quote
"\xe2\x80\x9c", // left double curly quote
"\xe2\x80\x9d", // right double curly quote
- );
+ ];
// windows 1252 / iso equivalents
- $findchars_iso = array(
+ $findchars_iso = [
chr(130),
chr(132),
chr(133),
@@ -2392,10 +2275,10 @@ public static function sanitizeMSCutPaste(string $string): string
chr(146),
chr(147),
chr(148),
- );
+ ];
// safe replacements
- $replacechars = array(
+ $replacechars = [
',', // ‚
',,', // „
'...', // …
@@ -2403,7 +2286,7 @@ public static function sanitizeMSCutPaste(string $string): string
"'", // ’
'"', // “
'"', // ”
- );
+ ];
$string = str_replace(Utils::$context['utf8'] ? $findchars_utf8 : $findchars_iso, $replacechars, $string);
@@ -2422,10 +2305,11 @@ public static function sanitizeMSCutPaste(string $string): string
* @param array $parse_tags If set, only parses these tags rather than all of them.
* @return string|array The parsed message or the list of BBCodes.
*/
- public static function backcompatParseBbc($message, $smileys = true, $cache_id = '', $parse_tags = array()): string|array
+ public static function backcompatParseBbc($message, $smileys = true, $cache_id = '', $parse_tags = []): string|array
{
- if ($message === false)
+ if ($message === false) {
return self::getCodes();
+ }
self::load();
@@ -2480,8 +2364,9 @@ public static function attachValidate(&$tag, &$data, $disabled, $params): void
$return_context = '';
// BBC or the entire attachments feature is disabled
- if (empty(Config::$modSettings['attachmentEnable']) || !empty($disabled['attach']))
+ if (empty(Config::$modSettings['attachmentEnable']) || !empty($disabled['attach'])) {
return;
+ }
// Save the attach ID.
$attach_id = $params['{id}'];
@@ -2489,70 +2374,58 @@ public static function attachValidate(&$tag, &$data, $disabled, $params): void
$current_attachment = Attachment::parseAttachBBC($attach_id);
// parseAttachBBC will return a string (Lang::$txt key) rather than dying with a fatal_error. Up to you to decide what to do.
- if (is_string($current_attachment))
- {
- $data = '' . (!empty(Lang::$txt[$current_attachment]) ? Lang::$txt[$current_attachment] : $current_attachment) . '';
+ if (is_string($current_attachment)) {
+ $data = '' . (!empty(Lang::$txt[$current_attachment]) ? Lang::$txt[$current_attachment] : $current_attachment) . '';
return;
}
// We need a display mode.
- if (empty($params['{display}']))
- {
+ if (empty($params['{display}'])) {
// Images, video, and audio are embedded by default.
- if (!empty($current_attachment['is_image']) || strpos($current_attachment['mime_type'], 'video/') === 0 || strpos($current_attachment['mime_type'], 'audio/') === 0)
- {
+ if (!empty($current_attachment['is_image']) || strpos($current_attachment['mime_type'], 'video/') === 0 || strpos($current_attachment['mime_type'], 'audio/') === 0) {
$params['{display}'] = 'embed';
}
// Anything else shows a link by default.
- else
- {
+ else {
$params['{display}'] = 'link';
}
}
// Embedded file.
- if ($params['{display}'] == 'embed')
- {
+ if ($params['{display}'] == 'embed') {
$alt = ' alt="' . (!empty($params['{alt}']) ? $params['{alt}'] : $current_attachment['name']) . '"';
$title = !empty($data) ? ' title="' . Utils::htmlspecialchars($data) . '"' : '';
// Image.
- if (!empty($current_attachment['is_image']))
- {
+ if (!empty($current_attachment['is_image'])) {
// Just viewing the page shouldn't increase the download count for embedded images.
$current_attachment['href'] .= ';preview';
- if (empty($params['{width}']) && empty($params['{height}']))
- {
+ if (empty($params['{width}']) && empty($params['{height}'])) {
$return_context .= '';
- }
- else
- {
- $width = !empty($params['{width}']) ? ' width="' . $params['{width}'] . '"': '';
+ } else {
+ $width = !empty($params['{width}']) ? ' width="' . $params['{width}'] . '"' : '';
$height = !empty($params['{height}']) ? 'height="' . $params['{height}'] . '"' : '';
$return_context .= '';
}
}
// Video.
- elseif (strpos($current_attachment['mime_type'], 'video/') === 0)
- {
+ elseif (strpos($current_attachment['mime_type'], 'video/') === 0) {
$width = !empty($params['{width}']) ? ' width="' . $params['{width}'] . '"' : '';
$height = !empty($params['{height}']) ? ' height="' . $params['{height}'] . '"' : '';
- $return_context .= '' . (!empty($data) && $data != $current_attachment['name'] ? '' . $data . ' ' : '');
+ $return_context .= '' . (!empty($data) && $data != $current_attachment['name'] ? '' . $data . ' ' : '');
}
// Audio.
- elseif (strpos($current_attachment['mime_type'], 'audio/') === 0)
- {
+ elseif (strpos($current_attachment['mime_type'], 'audio/') === 0) {
$width = 'max-width:100%; width: ' . (!empty($params['{width}']) ? $params['{width}'] : '400') . 'px;';
$height = !empty($params['{height}']) ? 'height: ' . $params['{height}'] . 'px;' : '';
- $return_context .= (!empty($data) && $data != $current_attachment['name'] ? $data . ' ' : '') . '';
+ $return_context .= (!empty($data) && $data != $current_attachment['name'] ? $data . ' ' : '') . '';
}
// Anything else.
- else
- {
+ else {
$width = !empty($params['{width}']) ? ' width="' . $params['{width}'] . '"' : '';
$height = !empty($params['{height}']) ? ' height="' . $params['{height}'] . '"' : '';
@@ -2560,8 +2433,7 @@ public static function attachValidate(&$tag, &$data, $disabled, $params): void
}
}
// No image. Show a link.
- else
- {
+ else {
$return_context .= '' . Utils::htmlspecialchars(!empty($data) ? $data : $current_attachment['name']) . '';
}
@@ -2569,7 +2441,7 @@ public static function attachValidate(&$tag, &$data, $disabled, $params): void
// If you want to work with the attachment data itself, use one of these:
// - integrate_pre_parseAttachBBC
// - integrate_post_parseAttachBBC
- IntegrationHook::call('integrate_attach_bbc_validate', array(&$return_context, $current_attachment, $tag, $data, $disabled, $params));
+ IntegrationHook::call('integrate_attach_bbc_validate', [&$return_context, $current_attachment, $tag, $data, $disabled, $params]);
// Gotta append what we just did.
$data = $return_context;
@@ -2585,22 +2457,20 @@ public static function attachValidate(&$tag, &$data, $disabled, $params): void
*/
public static function codeValidate(&$tag, &$data, $disabled, $params): void
{
- if (!isset($disabled['code']))
- {
+ if (!isset($disabled['code'])) {
$code = is_array($data) ? $data[0] : $data;
$php_parts = preg_split('~(<\?php|\?>)~', $code, -1, PREG_SPLIT_DELIM_CAPTURE);
- for ($php_i = 0, $php_n = count($php_parts); $php_i < $php_n; $php_i++)
- {
+ for ($php_i = 0, $php_n = count($php_parts); $php_i < $php_n; $php_i++) {
// Do PHP code coloring?
- if ($php_parts[$php_i] != '<?php')
+ if ($php_parts[$php_i] != '<?php') {
continue;
+ }
$php_string = '';
- while ($php_i + 1 < count($php_parts) && $php_parts[$php_i] != '?>')
- {
+ while ($php_i + 1 < count($php_parts) && $php_parts[$php_i] != '?>') {
$php_string .= $php_parts[$php_i];
$php_parts[$php_i++] = '';
}
@@ -2613,12 +2483,9 @@ public static function codeValidate(&$tag, &$data, $disabled, $params): void
$code = str_replace("\t", "\t", $code);
- if (is_array($data))
- {
+ if (is_array($data)) {
$data[0] = $code;
- }
- else
- {
+ } else {
$data = $code;
}
}
@@ -2635,7 +2502,7 @@ public static function codeValidate(&$tag, &$data, $disabled, $params): void
*/
public static function emailValidate(&$tag, &$data, $disabled, $params): void
{
- $data = strtr($data, array(' ' => ''));
+ $data = strtr($data, [' ' => '']);
}
/**
@@ -2648,15 +2515,17 @@ public static function emailValidate(&$tag, &$data, $disabled, $params): void
*/
public static function flashValidate(&$tag, &$data, $disabled, $params): void
{
- $data[0] = new Url(strtr(trim($data[0]), array(' ' => '', ' ' => '%20')), true);
+ $data[0] = new Url(strtr(trim($data[0]), [' ' => '', ' ' => '%20']), true);
- if (empty($data[0]->scheme))
+ if (empty($data[0]->scheme)) {
$data[0] = new Url('//' . ltrim($data[0], ':/'));
+ }
$ascii_url = (clone $data[0])->toAscii();
- if ((string) $ascii_url !== (string) $data[0])
+ if ((string) $ascii_url !== (string) $data[0]) {
$tag['content'] = str_replace('href="$1"', 'href="' . $ascii_url . '"', $tag['content']);
+ }
}
/**
@@ -2671,12 +2540,9 @@ public static function floatValidate(&$tag, &$data, $disabled, $params): void
{
$class = 'class="bbc_float float' . (strpos($data, 'left') === 0 ? 'left' : 'right') . '"';
- if (preg_match('~\bmax=(\d+(?:%|px|em|rem|ex|pt|pc|ch|vw|vh|vmin|vmax|cm|mm|in)?)~', $data, $matches))
- {
+ if (preg_match('~\bmax=(\d+(?:%|px|em|rem|ex|pt|pc|ch|vw|vh|vmin|vmax|cm|mm|in)?)~', $data, $matches)) {
$css = ' style="max-width:' . $matches[1] . (is_numeric($matches[1]) ? 'px' : '') . '"';
- }
- else
- {
+ } else {
$css = '';
}
@@ -2693,20 +2559,19 @@ public static function floatValidate(&$tag, &$data, $disabled, $params): void
*/
public static function ftpValidate(&$tag, &$data, $disabled, $params): void
{
- $data = new Url(strtr(trim($data), array(' ' => '', ' ' => '%20')), true);
+ $data = new Url(strtr(trim($data), [' ' => '', ' ' => '%20']), true);
- if (empty($data->scheme))
+ if (empty($data->scheme)) {
$data = new Url('ftp://' . ltrim($data, ':/'));
+ }
- if (isset($tag['content']))
- {
+ if (isset($tag['content'])) {
$ascii_url = (clone $data)->toAscii();
- if ((string) $ascii_url !== (string) $data)
+ if ((string) $ascii_url !== (string) $data) {
$tag['content'] = str_replace('href="$1"', 'href="' . $ascii_url . '"', $tag['content']);
- }
- else
- {
+ }
+ } else {
$data->toAscii();
}
}
@@ -2721,20 +2586,17 @@ public static function ftpValidate(&$tag, &$data, $disabled, $params): void
*/
public static function imgValidate(&$tag, &$data, $disabled, $params): void
{
- $url = new Url(strtr(trim($data), array(' ' => '', ' ' => '%20')), true);
+ $url = new Url(strtr(trim($data), [' ' => '', ' ' => '%20']), true);
$url->toAscii();
- if (!isset($url->scheme))
- {
+ if (!isset($url->scheme)) {
$url = new Url('//' . ltrim($url, ':/'));
- }
- else
- {
+ } else {
$url = $url->proxied();
}
- $alt = !empty($params['{alt}']) ? ' alt="' . $params['{alt}']. '"' : ' alt=""';
- $title = !empty($params['{title}']) ? ' title="' . $params['{title}']. '"' : '';
+ $alt = !empty($params['{alt}']) ? ' alt="' . $params['{alt}'] . '"' : ' alt=""';
+ $title = !empty($params['{title}']) ? ' title="' . $params['{title}'] . '"' : '';
$data = isset($disabled[$tag['tag']]) ? $url : '';
}
@@ -2749,31 +2611,28 @@ public static function imgValidate(&$tag, &$data, $disabled, $params): void
*/
public static function urlValidate(&$tag, &$data, $disabled, $params): void
{
- if ($tag['type'] === 'unparsed_content')
- {
- $data = new Url(strtr(trim($data), array(' ' => '', ' ' => '%20')), true);
+ if ($tag['type'] === 'unparsed_content') {
+ $data = new Url(strtr(trim($data), [' ' => '', ' ' => '%20']), true);
- if (empty($data->scheme))
+ if (empty($data->scheme)) {
$data = new Url('//' . ltrim($data, ':/'));
+ }
$ascii_url = (clone $data)->toAscii();
- if ((string) $ascii_url !== (string) $data)
+ if ((string) $ascii_url !== (string) $data) {
$tag['content'] = str_replace('href="$1"', 'href="' . $ascii_url . '"', $tag['content']);
- }
- else
- {
- if (substr($data, 0, 1) == '#')
- {
- $data = '#post_' . substr($data, 1);
}
- else
- {
- $data = new Url(strtr(trim($data), array(' ' => '', ' ' => '%20')), true);
+ } else {
+ if (substr($data, 0, 1) == '#') {
+ $data = '#post_' . substr($data, 1);
+ } else {
+ $data = new Url(strtr(trim($data), [' ' => '', ' ' => '%20']), true);
$data->toAscii();
- if (empty($data->scheme))
+ if (empty($data->scheme)) {
$data = '//' . ltrim($data, ':/');
+ }
}
}
}
@@ -2788,15 +2647,13 @@ public static function urlValidate(&$tag, &$data, $disabled, $params): void
*/
public static function phpValidate(&$tag, &$data, $disabled, $params): void
{
- if (!isset($disabled['php']))
- {
+ if (!isset($disabled['php'])) {
$add_begin = substr(trim($data), 0, 5) != '<?';
$data = self::highlightPhpCode($add_begin ? '<?php ' . $data . '?>' : $data);
- if ($add_begin)
- {
- $data = preg_replace(array('~^(.+?)<\?.{0,40}?php(?: |\s)~', '~\?>((?:(font|span)>)*)$~'), '$1', $data, 2);
+ if ($add_begin) {
+ $data = preg_replace(['~^(.+?)<\?.{0,40}?php(?: |\s)~', '~\?>((?:(font|span)>)*)$~'], '$1', $data, 2);
}
}
}
@@ -2811,24 +2668,15 @@ public static function phpValidate(&$tag, &$data, $disabled, $params): void
*/
public static function shadowValidate(&$tag, &$data, $disabled, $params): void
{
- if ($data[1] == 'top' || (is_numeric($data[1]) && $data[1] < 50))
- {
+ if ($data[1] == 'top' || (is_numeric($data[1]) && $data[1] < 50)) {
$data[1] = '0 -2px 1px';
- }
- elseif ($data[1] == 'right' || (is_numeric($data[1]) && $data[1] < 100))
- {
+ } elseif ($data[1] == 'right' || (is_numeric($data[1]) && $data[1] < 100)) {
$data[1] = '2px 0 1px';
- }
- elseif ($data[1] == 'bottom' || (is_numeric($data[1]) && $data[1] < 190))
- {
+ } elseif ($data[1] == 'bottom' || (is_numeric($data[1]) && $data[1] < 190)) {
$data[1] = '0 2px 1px';
- }
- elseif ($data[1] == 'left' || (is_numeric($data[1]) && $data[1] < 280))
- {
+ } elseif ($data[1] == 'left' || (is_numeric($data[1]) && $data[1] < 280)) {
$data[1] = '-2px 0 1px';
- }
- else
- {
+ } else {
$data[1] = '1px 1px 1px';
}
}
@@ -2843,7 +2691,7 @@ public static function shadowValidate(&$tag, &$data, $disabled, $params): void
*/
public static function sizeValidate(&$tag, &$data, $disabled, $params): void
{
- $sizes = array(1 => 0.7, 2 => 1.0, 3 => 1.35, 4 => 1.45, 5 => 2.0, 6 => 2.65, 7 => 3.95);
+ $sizes = [1 => 0.7, 2 => 1.0, 3 => 1.35, 4 => 1.45, 5 => 2.0, 6 => 2.65, 7 => 3.95];
$data = $sizes[$data] . 'em';
}
@@ -2857,8 +2705,9 @@ public static function sizeValidate(&$tag, &$data, $disabled, $params): void
*/
public static function timeValidate(&$tag, &$data, $disabled, $params): void
{
- if (is_numeric($data))
+ if (is_numeric($data)) {
$data = Time::create('@' . $data)->format();
+ }
$tag['content'] = '$1';
}
@@ -2872,26 +2721,25 @@ public static function timeValidate(&$tag, &$data, $disabled, $params): void
*/
protected function parseMessage(): void
{
- $this->open_tags = array();
- $this->message = strtr($this->message, array("\n" => ' '));
+ $this->open_tags = [];
+ $this->message = strtr($this->message, ["\n" => ' ']);
$this->setAllTagsRegex();
- while ($this->pos !== false)
- {
+ while ($this->pos !== false) {
$this->last_pos = isset($this->last_pos) ? max($this->pos, $this->last_pos) : $this->pos;
preg_match('~\[/?(?=' . $this->alltags_regex . ')~i', $this->message, $matches, PREG_OFFSET_CAPTURE, $this->pos + 1);
- $this->pos = isset($matches[0][1]) ? $matches[0][1] : false;
+ $this->pos = $matches[0][1] ?? false;
// Failsafe.
- if ($this->pos === false || $this->last_pos > $this->pos)
+ if ($this->pos === false || $this->last_pos > $this->pos) {
$this->pos = strlen($this->message) + 1;
+ }
// Can't have a one letter smiley, URL, or email! (Sorry.)
- if ($this->last_pos < $this->pos - 1)
- {
+ if ($this->last_pos < $this->pos - 1) {
// Make sure the $this->last_pos is not negative.
$this->last_pos = max($this->last_pos, 0);
@@ -2905,11 +2753,10 @@ protected function parseMessage(): void
// Restore any placeholders
$data = strtr($data, $this->placeholders);
- $data = strtr($data, array("\t" => ' '));
+ $data = strtr($data, ["\t" => ' ']);
// If it wasn't changed, no copying or other boring stuff has to happen!
- if ($data != substr($this->message, $this->last_pos, $this->pos - $this->last_pos))
- {
+ if ($data != substr($this->message, $this->last_pos, $this->pos - $this->last_pos)) {
$this->message = substr($this->message, 0, $this->last_pos) . $data . substr($this->message, $this->pos);
// Since we changed it, look again in case we added or removed a tag. But we don't want to skip any.
@@ -2920,36 +2767,35 @@ protected function parseMessage(): void
}
// Are we there yet? Are we there yet?
- if ($this->pos >= strlen($this->message) - 1)
+ if ($this->pos >= strlen($this->message) - 1) {
break;
+ }
$tag_character = strtolower($this->message[$this->pos + 1]);
- if ($tag_character == '/' && !empty($this->open_tags))
- {
+ if ($tag_character == '/' && !empty($this->open_tags)) {
$this->closeTags();
+
continue;
}
// No tags for this character, so just keep going (fastest possible course.)
- if (!isset($this->bbc_codes[$tag_character]))
+ if (!isset($this->bbc_codes[$tag_character])) {
continue;
+ }
$this->inside = empty($this->open_tags) ? null : $this->open_tags[count($this->open_tags) - 1];
// What tag do we have?
list($tag, $params) = $this->detectTag($tag_character);
- if ($tag === null)
- {
+ if ($tag === null) {
// Item codes are complicated buggers... they are implicit [li]s and can make [list]s!
- if (isset(self::$itemcodes[$this->message[$this->pos + 1]], $this->message[$this->pos + 2]) && $this->message[$this->pos + 2] == ']' && !isset($this->disabled['list']) && !isset($this->disabled['li']))
- {
+ if (isset(self::$itemcodes[$this->message[$this->pos + 1]], $this->message[$this->pos + 2]) && $this->message[$this->pos + 2] == ']' && !isset($this->disabled['list']) && !isset($this->disabled['li'])) {
$this->parseItemCode();
}
// Implicitly close lists and tables if something other than what's required is in them. This is needed for itemcode.
- elseif ($this->inside !== null && !empty($this->inside['require_children']))
- {
+ elseif ($this->inside !== null && !empty($this->inside['require_children'])) {
array_pop($this->open_tags);
$this->message = substr($this->message, 0, $this->pos) . "\n" . $this->inside['after'] . "\n" . substr($this->message, $this->pos);
@@ -2960,18 +2806,17 @@ protected function parseMessage(): void
}
// Propagate the list to the child (so wrapping the disallowed tag won't work either.)
- if (isset($this->inside['disallow_children']))
- {
+ if (isset($this->inside['disallow_children'])) {
$tag['disallow_children'] = isset($tag['disallow_children']) ? array_unique(array_merge($tag['disallow_children'], $this->inside['disallow_children'])) : $this->inside['disallow_children'];
}
// Is this tag disabled?
- if (isset($this->disabled[$tag['tag']]))
+ if (isset($this->disabled[$tag['tag']])) {
$tag = $this->useDisabledTag($tag);
+ }
// The only special case is 'html', which doesn't need to close things.
- if (!empty($tag['block_level']) && $tag['tag'] != 'html' && empty($this->inside['block_level']))
- {
+ if (!empty($tag['block_level']) && $tag['tag'] != 'html' && empty($this->inside['block_level'])) {
$this->closeInlineTags();
}
@@ -2982,30 +2827,31 @@ protected function parseMessage(): void
}
// Close any remaining tags.
- while ($tag = array_pop($this->open_tags))
+ while ($tag = array_pop($this->open_tags)) {
$this->message .= "\n" . $tag['after'] . "\n";
+ }
// Parse the smileys within the parts where it can be done safely.
- if ($this->smileys === true)
- {
+ if ($this->smileys === true) {
$message_parts = explode("\n", $this->message);
- for ($i = 0, $n = count($message_parts); $i < $n; $i += 2)
+ for ($i = 0, $n = count($message_parts); $i < $n; $i += 2) {
$message_parts[$i] = $this->parseSmileys($message_parts[$i]);
+ }
$this->message = implode('', $message_parts);
}
// No smileys, just get rid of the markers.
- else
- {
- $this->message = strtr($this->message, array("\n" => ''));
+ else {
+ $this->message = strtr($this->message, ["\n" => '']);
}
- if ($this->message !== '' && $this->message[0] === ' ')
+ if ($this->message !== '' && $this->message[0] === ' ') {
$this->message = ' ' . substr($this->message, 1);
+ }
// Cleanup whitespace.
- $this->message = strtr($this->message, array(' ' => ' ', "\r" => '', "\n" => ' ', ' ' => ' ', '
' => "\n"));
+ $this->message = strtr($this->message, [' ' => ' ', "\r" => '', "\n" => ' ', ' ' => ' ', '
' => "\n"]);
}
/**
@@ -3016,78 +2862,70 @@ protected function parseMessage(): void
*/
protected function autoLink(string $data): string
{
- if (empty($this->autolink_enabled))
+ if (empty($this->autolink_enabled)) {
return $data;
+ }
// Are we inside tags that should be auto linked?
$no_autolink_area = false;
- if (!empty($this->open_tags))
- {
- foreach ($this->open_tags as $open_tag)
- {
- if (in_array($open_tag['tag'], self::$no_autolink_tags))
+ if (!empty($this->open_tags)) {
+ foreach ($this->open_tags as $open_tag) {
+ if (in_array($open_tag['tag'], self::$no_autolink_tags)) {
$no_autolink_area = true;
+ }
}
}
- if (!$no_autolink_area)
- {
+ if (!$no_autolink_area) {
// An right after a URL can break the autolinker
- if (strpos($data, ' ') !== false)
- {
+ if (strpos($data, ' ') !== false) {
$this->placeholders[html_entity_decode(' ', 0, $this->encoding)] = ' ';
- $data = strtr($data, array(' ' => html_entity_decode(' ', 0, $this->encoding)));
+ $data = strtr($data, [' ' => html_entity_decode(' ', 0, $this->encoding)]);
}
// Parse any URLs
- if (!isset($this->disabled['url']) && strpos($data, '[url') === false)
- {
+ if (!isset($this->disabled['url']) && strpos($data, '[url') === false) {
$this->setUrlRegex();
$tmp_data = preg_replace_callback(
'~' . $this->url_regex . '~i' . ($this->utf8 ? 'u' : ''),
- function($matches)
- {
+ function ($matches) {
$url = array_shift($matches);
// If this isn't a clean URL, bail out
- if ($url !== (string) Url::create($url)->sanitize())
+ if ($url !== (string) Url::create($url)->sanitize()) {
return $url;
+ }
// Ensure the host name is in its canonical form.
$url = new Url($url, true);
- if (!isset($url->scheme))
+ if (!isset($url->scheme)) {
$url->scheme = '';
+ }
- if ($url->scheme == 'mailto')
- {
- if (isset($this->disabled['email']))
+ if ($url->scheme == 'mailto') {
+ if (isset($this->disabled['email'])) {
return $url;
+ }
// Is this version of PHP capable of validating this email address?
$can_validate = defined('FILTER_FLAG_EMAIL_UNICODE') || strlen($url->path) == strspn(strtolower($url->path), 'abcdefghijklmnopqrstuvwxyz0123456789!#$%&\'*+-/=?^_`{|}~.@');
$flags = defined('FILTER_FLAG_EMAIL_UNICODE') ? FILTER_FLAG_EMAIL_UNICODE : null;
- if (!$can_validate || filter_var($url->path, FILTER_VALIDATE_EMAIL, $flags) !== false)
- {
+ if (!$can_validate || filter_var($url->path, FILTER_VALIDATE_EMAIL, $flags) !== false) {
return '[email=' . $url->path . ']' . $url . '[/email]';
}
- else
- {
- return $url;
- }
+
+ return $url;
}
// Are we linking a schemeless URL or naked domain name (e.g. "example.com")?
- if (empty($url->scheme))
- {
+ if (empty($url->scheme)) {
$full_url = new Url('//' . ltrim($url, ':/'));
- }
- else
- {
+ } else {
$full_url = clone $url;
}
@@ -3098,33 +2936,34 @@ function($matches)
!in_array($url->scheme, self::$schemes['no_authority'])
&& !$full_url->isValid()
)
- )
- {
+ ) {
return $url;
}
- return '[url="' . str_replace(array('[', ']'), array('[', ']'), $full_url->toAscii()) . '"]' . $url . '[/url]';
+ return '[url="' . str_replace(['[', ']'], ['[', ']'], $full_url->toAscii()) . '"]' . $url . '[/url]';
},
- $data
+ $data,
);
- if (!is_null($tmp_data))
+ if (!is_null($tmp_data)) {
$data = $tmp_data;
+ }
}
// Next, emails... Must be careful not to step on enablePostHTML logic above...
- if (!isset($this->disabled['email']) && strpos($data, '@') !== false && strpos($data, '[email') === false && stripos($data, 'mailto:') === false)
- {
+ if (!isset($this->disabled['email']) && strpos($data, '@') !== false && strpos($data, '[email') === false && stripos($data, 'mailto:') === false) {
$this->setEmailRegex();
$tmp_data = preg_replace('~' . $this->email_regex . '~i' . ($this->utf8 ? 'u' : ''), '[email]$0[/email]', $data);
- if (!is_null($tmp_data))
+ if (!is_null($tmp_data)) {
$data = $tmp_data;
+ }
}
- if (isset($_REQUEST['preview']))
- file_put_contents('/tmp/derp.txt', "data = " . $data . "\n", FILE_APPEND);
+ if (isset($_REQUEST['preview'])) {
+ file_put_contents('/tmp/derp.txt', 'data = ' . $data . "\n", FILE_APPEND);
+ }
}
return $data;
@@ -3145,44 +2984,44 @@ protected function highLoadAverage(): bool
*/
protected function setDisabled(): void
{
- $this->disabled = array();
+ $this->disabled = [];
- if (!empty(Config::$modSettings['disabledBBC']))
- {
+ if (!empty(Config::$modSettings['disabledBBC'])) {
$temp = explode(',', strtolower(Config::$modSettings['disabledBBC']));
- foreach ($temp as $tag)
+ foreach ($temp as $tag) {
$this->disabled[trim($tag)] = true;
+ }
- if (in_array('color', $this->disabled))
- {
+ if (in_array('color', $this->disabled)) {
$this->disabled = array_merge(
$this->disabled,
- array(
+ [
'black' => true,
'white' => true,
'red' => true,
'green' => true,
'blue' => true,
- )
+ ],
);
}
}
- if (!empty($this->parse_tags))
- {
- if (!in_array('email', $this->parse_tags))
+ if (!empty($this->parse_tags)) {
+ if (!in_array('email', $this->parse_tags)) {
$this->disabled['email'] = true;
+ }
- if (!in_array('url', $this->parse_tags))
+ if (!in_array('url', $this->parse_tags)) {
$this->disabled['url'] = true;
+ }
- if (!in_array('iurl', $this->parse_tags))
+ if (!in_array('iurl', $this->parse_tags)) {
$this->disabled['iurl'] = true;
+ }
}
- if ($this->for_print)
- {
+ if ($this->for_print) {
// [glow], [shadow], and [move] can't really be printed.
$this->disabled['glow'] = true;
$this->disabled['shadow'] = true;
@@ -3208,14 +3047,13 @@ protected function setDisabled(): void
$this->disabled['flash'] = true;
// @todo Change maybe?
- if (!isset($_GET['images']))
- {
+ if (!isset($_GET['images'])) {
$this->disabled['img'] = true;
$this->disabled['attach'] = true;
}
// Maybe some custom BBC need to be disabled for printing.
- IntegrationHook::call('integrate_bbc_print', array(&$this->disabled));
+ IntegrationHook::call('integrate_bbc_print', [&$this->disabled]);
}
}
@@ -3227,63 +3065,61 @@ protected function setBbcCodes(): void
// If we already have a version of the BBCodes for the current language, use that.
$locale_key = $this->locale . '|' . implode(',', $this->disabled);
- if (!empty($this->bbc_lang_locales[$locale_key]))
+ if (!empty($this->bbc_lang_locales[$locale_key])) {
$this->bbc_codes = $this->bbc_lang_locales[$locale_key];
+ }
// If we are not doing every tag then we don't cache this run.
- if (!empty($this->parse_tags))
- $this->bbc_codes = array();
+ if (!empty($this->parse_tags)) {
+ $this->bbc_codes = [];
+ }
// Avoid unnecessary repetition.
- if (!empty($this->bbc_codes))
+ if (!empty($this->bbc_codes)) {
return;
+ }
// Add itemcodes to the array.
- if (!isset($this->disabled['li']) && !isset($this->disabled['list']))
- {
- foreach (self::$itemcodes as $c => $dummy)
- $this->bbc_codes[$c] = array();
+ if (!isset($this->disabled['li']) && !isset($this->disabled['list'])) {
+ foreach (self::$itemcodes as $c => $dummy) {
+ $this->bbc_codes[$c] = [];
+ }
}
$codes = self::$codes;
// Shhhh!
- if (!isset($this->disabled['color']))
- {
- $codes[] = array(
+ if (!isset($this->disabled['color'])) {
+ $codes[] = [
'tag' => 'chrissy',
'before' => '',
'after' => ' :-*',
- );
- $codes[] = array(
+ ];
+ $codes[] = [
'tag' => 'kissy',
'before' => '',
'after' => ' :-*',
- );
+ ];
}
- $codes[] = array(
+ $codes[] = [
'tag' => 'cowsay',
- 'parameters' => array(
- 'e' => array('optional' => true, 'quoted' => true, 'match' => '(.*?)', 'default' => 'oo', 'validate' => function ($eyes)
- {
- return Utils::entitySubstr($eyes . 'oo', 0, 2);
- },
- ),
- 't' => array('optional' => true, 'quoted' => true, 'match' => '(.*?)', 'default' => ' ', 'validate' => function ($tongue)
- {
- return Utils::entitySubstr($tongue . ' ', 0, 2);
- },
- ),
- ),
+ 'parameters' => [
+ 'e' => ['optional' => true, 'quoted' => true, 'match' => '(.*?)', 'default' => 'oo', 'validate' => function ($eyes) {
+ return Utils::entitySubstr($eyes . 'oo', 0, 2);
+ },
+ ],
+ 't' => ['optional' => true, 'quoted' => true, 'match' => '(.*?)', 'default' => ' ', 'validate' => function ($tongue) {
+ return Utils::entitySubstr($tongue . ' ', 0, 2);
+ },
+ ],
+ ],
'before' => '',
'after' => ' ',
'block_level' => true,
- 'validate' => function(&$tag, &$data, $disabled, $params)
- {
+ 'validate' => function (&$tag, &$data, $disabled, $params) {
static $moo = true;
- if ($moo)
- {
+ if ($moo) {
Theme::addInlineJavaScript("\n\t" . base64_decode(
'aWYoZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoImJvdmluZV9vcmFjbGU
iKT09PW51bGwpe2xldCBzdHlsZU5vZGU9ZG9jdW1lbnQuY3JlYXRlRWx
@@ -3303,27 +3139,29 @@ protected function setBbcCodes(): void
BIFwnXCcgXCdcJyBcJ1wnIFwnXCcgXCdcJyBcJ1wnIFwnXCcgfHwgXCd
cJyBcJ1wnIFwnXCcgXCdcJyB8fFwnO30nO2RvY3VtZW50LmdldEVsZW1
lbnRzQnlUYWdOYW1lKCJoZWFkIilbMF0uYXBwZW5kQ2hpbGQoc3R5bGV
- Ob2RlKTt9'
+ Ob2RlKTt9',
), true);
$moo = false;
}
- }
- );
+ },
+ ];
- foreach ($codes as $code)
- {
+ foreach ($codes as $code) {
// Make it easier to process parameters later
- if (!empty($code['parameters']))
+ if (!empty($code['parameters'])) {
ksort($code['parameters'], SORT_STRING);
+ }
// If we are not doing every tag only do ones we are interested in.
- if (empty($this->parse_tags) || in_array($code['tag'], $this->parse_tags))
+ if (empty($this->parse_tags) || in_array($code['tag'], $this->parse_tags)) {
$this->bbc_codes[substr($code['tag'], 0, 1)][] = $code;
+ }
}
- if (empty($this->parse_tags))
+ if (empty($this->parse_tags)) {
$this->bbc_lang_locales[$locale_key] = $this->bbc_codes;
+ }
}
/**
@@ -3332,13 +3170,14 @@ protected function setBbcCodes(): void
protected function setUrlRegex(): void
{
// Don't repeat this unnecessarily.
- if (!empty($this->url_regex))
+ if (!empty($this->url_regex)) {
return;
+ }
$this->setTldRegex();
// PCRE subroutines for efficiency.
- $pcre_subroutines = array(
+ $pcre_subroutines = [
'tlds' => $this->tld_regex,
'pct' => '%[0-9A-Fa-f]{2}',
'space_lookahead' => '(?=$|\s| )',
@@ -3346,16 +3185,16 @@ protected function setUrlRegex(): void
'domain_label_char' => '[' . self::$domain_label_chars . ']',
'not_domain_label_char' => '[^' . self::$domain_label_chars . ']',
'domain' => '(?:(?P>domain_label_char)+\.)+(?P>tlds)(?!\.(?P>domain_label_char))',
- 'no_domain' => '(?:(?P>domain_label_char)|[._\~!$&\'()*+,;=:@]|(?P>pct))+',
+ 'no_domain' => '(?:(?P>domain_label_char)|[._\\~!$&\'()*+,;=:@]|(?P>pct))+',
'scheme_need_domain' => Utils::buildRegex(self::$schemes['need_domain'], '~'),
'scheme_empty_authority' => Utils::buildRegex(self::$schemes['empty_authority'], '~'),
'scheme_no_authority' => Utils::buildRegex(self::$schemes['no_authority'], '~'),
'scheme_any' => '[A-Za-z][0-9A-Za-z+\-.]*',
- 'user_info' => '(?:(?P>domain_label_char)|[._\~!$&\'()*+,;=:]|(?P>pct))+',
+ 'user_info' => '(?:(?P>domain_label_char)|[._\\~!$&\'()*+,;=:]|(?P>pct))+',
'dec_octet' => '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)',
'h16' => '[0-9A-Fa-f]{1,4}',
'ipv4' => '(?:\b(?:(?P>dec_octet)\.){3}(?P>dec_octet)\b)',
- 'ipv6' => '\[(?:' . implode('|', array(
+ 'ipv6' => '\[(?:' . implode('|', [
'(?:(?P>h16):){7}(?P>h16)',
'(?:(?P>h16):){1,7}:',
'(?:(?P>h16):){1,6}(?::(?P>h16))',
@@ -3368,22 +3207,22 @@ protected function setUrlRegex(): void
'fe80:(?::(?P>h16)){0,4}%[0-9A-Za-z]+',
'::(ffff(:0{1,4})?:)?(?P>ipv4)',
'(?:(?P>h16):){1,4}:(?P>ipv4)',
- )) . ')\]',
- 'host' => '(?:' . implode('|', array(
+ ]) . ')\]',
+ 'host' => '(?:' . implode('|', [
'localhost',
'(?P>domain)',
'(?P>ipv4)',
'(?P>ipv6)',
- )) . ')',
+ ]) . ')',
'authority' => '(?:(?P>user_info)@)?(?P>host)(?::\d+)?',
- );
+ ];
// Brackets and quotation marks are problematic at the end of an IRI.
// E.g.: `http://foo.com/baz(qux)` vs. `(http://foo.com/baz_qux)`
// In the first case, the user probably intended the `)` as part of the
// IRI, but not in the second case. To account for this, we test for
// balanced pairs within the IRI.
- $balanced_pairs = array(
+ $balanced_pairs = [
// Brackets and parentheses
'(' => ')', // '(' => ')',
'[' => ']', // '[' => ']',
@@ -3402,38 +3241,35 @@ protected function setUrlRegex(): void
'‚' => '’', // '‚' => '’',
'‛' => '’', // '‛' => '’',
'‹' => '›', // '‹' => '›',
- );
+ ];
- foreach ($balanced_pairs as $pair_opener => $pair_closer)
+ foreach ($balanced_pairs as $pair_opener => $pair_closer) {
$balanced_pairs[htmlspecialchars($pair_opener)] = htmlspecialchars($pair_closer);
+ }
$bracket_quote_chars = '';
- $bracket_quote_entities = array();
- foreach ($balanced_pairs as $pair_opener => $pair_closer)
- {
- if ($pair_opener == $pair_closer)
+ $bracket_quote_entities = [];
+
+ foreach ($balanced_pairs as $pair_opener => $pair_closer) {
+ if ($pair_opener == $pair_closer) {
$pair_closer = '';
+ }
- foreach (array($pair_opener, $pair_closer) as $bracket_quote)
- {
- if (strpos($bracket_quote, '&') === false)
- {
+ foreach ([$pair_opener, $pair_closer] as $bracket_quote) {
+ if (strpos($bracket_quote, '&') === false) {
$bracket_quote_chars .= $bracket_quote;
- }
- else
- {
+ } else {
$bracket_quote_entities[] = substr($bracket_quote, 1);
}
}
}
- $bracket_quote_chars = str_replace(array('[', ']'), array('\[', '\]'), $bracket_quote_chars);
+ $bracket_quote_chars = str_replace(['[', ']'], ['\[', '\]'], $bracket_quote_chars);
$pcre_subroutines['bracket_quote'] = '[' . $bracket_quote_chars . ']|&' . Utils::buildRegex($bracket_quote_entities, '~');
- $pcre_subroutines['allowed_entities'] = '&(?!' . Utils::buildRegex(array_merge($bracket_quote_entities, array('lt;', 'gt;')), '~') . ')';
+ $pcre_subroutines['allowed_entities'] = '&(?!' . Utils::buildRegex(array_merge($bracket_quote_entities, ['lt;', 'gt;']), '~') . ')';
$pcre_subroutines['excluded_lookahead'] = '(?![' . self::$excluded_trailing_chars . ']*(?P>space_lookahead))';
- foreach (array('path', 'query', 'fragment') as $part)
- {
+ foreach (['path', 'query', 'fragment'] as $part) {
switch ($part) {
case 'path':
$part_disallowed_chars = '\s<>' . $bracket_quote_chars . self::$excluded_trailing_chars . '/#&';
@@ -3452,10 +3288,9 @@ protected function setUrlRegex(): void
}
$pcre_subroutines[$part . '_allowed'] = '[^' . $part_disallowed_chars . ']|(?P>allowed_entities)|[' . $part_excluded_trailing_chars . '](?P>excluded_lookahead)';
- $balanced_construct_regex = array();
+ $balanced_construct_regex = [];
- foreach ($balanced_pairs as $pair_opener => $pair_closer)
- {
+ foreach ($balanced_pairs as $pair_opener => $pair_closer) {
$balanced_construct_regex[] = preg_quote($pair_opener) . '(?P>' . $part . '_recursive)*+' . preg_quote($pair_closer);
}
@@ -3639,8 +3474,9 @@ protected function setUrlRegex(): void
// Finally, define the PCRE subroutines in the regex.
$this->url_regex .= '(?(DEFINE)';
- foreach ($pcre_subroutines as $name => $subroutine)
+ foreach ($pcre_subroutines as $name => $subroutine) {
$this->url_regex .= '(?<' . $name . '>' . $subroutine . ')';
+ }
$this->url_regex .= ')';
}
@@ -3650,8 +3486,9 @@ protected function setUrlRegex(): void
*/
protected function setEmailRegex(): void
{
- if (!empty($this->email_regex))
+ if (!empty($this->email_regex)) {
return;
+ }
$this->setTldRegex();
@@ -3673,12 +3510,12 @@ protected function setEmailRegex(): void
*/
protected function setAllTagsRegex(): void
{
- $alltags = array();
+ $alltags = [];
- foreach ($this->bbc_codes as $section)
- {
- foreach ($section as $code)
+ foreach ($this->bbc_codes as $section) {
+ foreach ($section as $code) {
$alltags[] = $code['tag'];
+ }
}
$this->alltags_regex = '(?' . '>\b' . Utils::buildRegex(array_unique($alltags)) . '\b|' . Utils::buildRegex(array_keys(self::$itemcodes)) . ')';
@@ -3689,8 +3526,7 @@ protected function setAllTagsRegex(): void
*/
protected function setTldRegex(): void
{
- if (!isset($this->tld_regex))
- {
+ if (!isset($this->tld_regex)) {
Url::setTldRegex();
$this->tld_regex = Config::$modSettings['tld_regex'];
}
@@ -3706,32 +3542,27 @@ protected function insertTxt(string $string): string
{
return preg_replace_callback(
'/{(.*?)}/',
- function ($matches)
- {
- if ($matches[0] === '{scripturl}')
- {
+ function ($matches) {
+ if ($matches[0] === '{scripturl}') {
return Config::$scripturl;
}
- elseif ($matches[0] === '{hosturl}')
- {
- if (!isset($this->hosturl))
- {
+
+ if ($matches[0] === '{hosturl}') {
+ if (!isset($this->hosturl)) {
$our_url = new Url(Config::$scripturl);
$this->hosturl = $our_url->scheme . '://' . $our_url->host;
}
return $this->hosturl;
}
- elseif (strpos($matches[1], 'txt_') === 0 && isset(Lang::$txt[substr($matches[1], 4)]))
- {
+
+ if (strpos($matches[1], 'txt_') === 0 && isset(Lang::$txt[substr($matches[1], 4)])) {
return Lang::$txt[substr($matches[1], 4)];
}
- else
- {
- return $matches[0];
- }
+
+ return $matches[0];
},
- $string
+ $string,
);
}
@@ -3743,40 +3574,39 @@ function ($matches)
*/
protected function fixHtml(string $data): string
{
- if (empty($this->enable_post_html) || strpos($data, '<') === false)
+ if (empty($this->enable_post_html) || strpos($data, '<') === false) {
return $data;
+ }
- $data = preg_replace('~<a\s+href=((?:")?)((?:https?://|ftps?://|mailto:|tel:)\S+?)\\1>(.*?)</a>~i', '[url="$2"]$3[/url]', $data);
+ $data = preg_replace('~<a\s+href=((?:")?)((?:https?://|ftps?://|mailto:|tel:)\S+?)\1>(.*?)</a>~i', '[url="$2"]$3[/url]', $data);
// should be empty.
- $empty_tags = array('br', 'hr');
+ $empty_tags = ['br', 'hr'];
- foreach ($empty_tags as $tag)
- {
- $data = str_replace(array('<' . $tag . '>', '<' . $tag . '/>', '<' . $tag . ' />'), '<' . $tag . '>', $data);
+ foreach ($empty_tags as $tag) {
+ $data = str_replace(['<' . $tag . '>', '<' . $tag . '/>', '<' . $tag . ' />'], '<' . $tag . '>', $data);
}
// b, u, i, s, pre... basic tags.
- $closable_tags = array('b', 'u', 'i', 's', 'em', 'ins', 'del', 'pre', 'blockquote', 'strong');
+ $closable_tags = ['b', 'u', 'i', 's', 'em', 'ins', 'del', 'pre', 'blockquote', 'strong'];
- foreach ($closable_tags as $tag)
- {
+ foreach ($closable_tags as $tag) {
$diff = substr_count($data, '<' . $tag . '>') - substr_count($data, '</' . $tag . '>');
- $data = strtr($data, array('<' . $tag . '>' => '<' . $tag . '>', '</' . $tag . '>' => '' . $tag . '>'));
+ $data = strtr($data, ['<' . $tag . '>' => '<' . $tag . '>', '</' . $tag . '>' => '' . $tag . '>']);
- if ($diff > 0)
+ if ($diff > 0) {
$data = substr($data, 0, -1) . str_repeat('' . $tag . '>', $diff) . substr($data, -1);
+ }
}
// Do - with security... action= -> action-.
- preg_match_all('~<img\s+src=((?:")?)((?:https?://|ftps?://)\S+?)\\1(?:\s+alt=(".*?"|\S*?))?(?:\s?/)?>~i', $data, $matches, PREG_PATTERN_ORDER);
+ preg_match_all('~<img\s+src=((?:")?)((?:https?://|ftps?://)\S+?)\1(?:\s+alt=(".*?"|\S*?))?(?:\s?/)?>~i', $data, $matches, PREG_PATTERN_ORDER);
- if (!empty($matches[0]))
- {
- $replaces = array();
- foreach ($matches[2] as $match => $imgtag)
- {
+ if (!empty($matches[0])) {
+ $replaces = [];
+
+ foreach ($matches[2] as $match => $imgtag) {
$alt = empty($matches[3][$match]) ? '' : ' alt=' . preg_replace('~^"|"$~', '', $matches[3][$match]);
// Remove action= from the URL - no funny business, now.
@@ -3803,49 +3633,45 @@ protected function closeTags(): void
{
$pos2 = strpos($this->message, ']', $this->pos + 1);
- if ($pos2 == $this->pos + 2)
+ if ($pos2 == $this->pos + 2) {
return;
+ }
$look_for = strtolower(substr($this->message, $this->pos + 2, $pos2 - $this->pos - 2));
// A closing tag that doesn't match any open tags? Skip it.
- if (!in_array($look_for, array_map(function($tag) { return $tag['tag']; }, $this->open_tags)))
+ if (!in_array($look_for, array_map(function ($tag) { return $tag['tag']; }, $this->open_tags))) {
return;
+ }
- $to_close = array();
+ $to_close = [];
$block_level = null;
- do
- {
+ do {
$tag = array_pop($this->open_tags);
- if (!$tag)
+ if (!$tag) {
break;
+ }
- if (!empty($tag['block_level']))
- {
+ if (!empty($tag['block_level'])) {
// Only find out if we need to.
- if ($block_level === false)
- {
+ if ($block_level === false) {
array_push($this->open_tags, $tag);
break;
}
// The idea is, if we are LOOKING for a block level tag, we can close them on the way.
- if (strlen($look_for) > 0 && isset($this->bbc_codes[$look_for[0]]))
- {
- foreach ($this->bbc_codes[$look_for[0]] as $temp)
- {
- if ($temp['tag'] == $look_for)
- {
+ if (strlen($look_for) > 0 && isset($this->bbc_codes[$look_for[0]])) {
+ foreach ($this->bbc_codes[$look_for[0]] as $temp) {
+ if ($temp['tag'] == $look_for) {
$block_level = !empty($temp['block_level']);
break;
}
}
}
- if ($block_level !== true)
- {
+ if ($block_level !== true) {
$block_level = false;
array_push($this->open_tags, $tag);
break;
@@ -3853,23 +3679,19 @@ protected function closeTags(): void
}
$to_close[] = $tag;
- }
- while ($tag['tag'] != $look_for);
+ } while ($tag['tag'] != $look_for);
// Did we just eat through everything and not find it?
- if ((empty($this->open_tags) && (empty($tag) || $tag['tag'] != $look_for)))
- {
+ if ((empty($this->open_tags) && (empty($tag) || $tag['tag'] != $look_for))) {
$this->open_tags = $to_close;
+
return;
}
- elseif (!empty($to_close) && $tag['tag'] != $look_for)
- {
- if ($block_level === null && isset($look_for[0], $this->bbc_codes[$look_for[0]]))
- {
- foreach ($this->bbc_codes[$look_for[0]] as $temp)
- {
- if ($temp['tag'] == $look_for)
- {
+
+ if (!empty($to_close) && $tag['tag'] != $look_for) {
+ if ($block_level === null && isset($look_for[0], $this->bbc_codes[$look_for[0]])) {
+ foreach ($this->bbc_codes[$look_for[0]] as $temp) {
+ if ($temp['tag'] == $look_for) {
$block_level = !empty($temp['block_level']);
break;
}
@@ -3877,17 +3699,16 @@ protected function closeTags(): void
}
// We're not looking for a block level tag (or maybe even a tag that exists...)
- if (!$block_level)
- {
- foreach ($to_close as $tag)
+ if (!$block_level) {
+ foreach ($to_close as $tag) {
array_push($this->open_tags, $tag);
+ }
return;
}
}
- foreach ($to_close as $tag)
- {
+ foreach ($to_close as $tag) {
$this->message = substr($this->message, 0, $this->pos) . "\n" . $tag['after'] . "\n" . substr($this->message, $pos2 + 1);
$this->pos += strlen($tag['after']) + 2;
$pos2 = $this->pos - 1;
@@ -3895,24 +3716,22 @@ protected function closeTags(): void
// See the comment at the end of the big loop - just eating whitespace ;).
$whitespace_regex = '';
- if (!empty($tag['block_level']))
+ if (!empty($tag['block_level'])) {
$whitespace_regex .= '( |\s)*( )?';
+ }
// Trim one line of whitespace after unnested tags, but all of it after nested ones
- if (!empty($tag['trim']) && $tag['trim'] != 'inside')
- {
+ if (!empty($tag['trim']) && $tag['trim'] != 'inside') {
$whitespace_regex .= empty($tag['require_parents']) ? '( |\s)*' : '( | |\s)*';
}
- if (!empty($whitespace_regex) && preg_match('~' . $whitespace_regex . '~', substr($this->message, $this->pos), $matches) != 0)
- {
+ if (!empty($whitespace_regex) && preg_match('~' . $whitespace_regex . '~', substr($this->message, $this->pos), $matches) != 0) {
$this->message = substr($this->message, 0, $this->pos) . substr($this->message, $this->pos + strlen($matches[0]));
}
}
- if (!empty($to_close))
- {
- $to_close = array();
+ if (!empty($to_close)) {
+ $to_close = [];
$this->pos--;
}
}
@@ -3926,121 +3745,108 @@ protected function closeTags(): void
protected function detectTag(string $tag_character): array
{
$tag = null;
- $params = array();
+ $params = [];
- foreach ($this->bbc_codes[$tag_character] as $possible)
- {
+ foreach ($this->bbc_codes[$tag_character] as $possible) {
$pt_strlen = strlen($possible['tag']);
// Not a match?
- if (strtolower(substr($this->message, $this->pos + 1, $pt_strlen)) != $possible['tag'])
+ if (strtolower(substr($this->message, $this->pos + 1, $pt_strlen)) != $possible['tag']) {
continue;
+ }
- $next_c = isset($this->message[$this->pos + 1 + $pt_strlen]) ? $this->message[$this->pos + 1 + $pt_strlen] : '';
+ $next_c = $this->message[$this->pos + 1 + $pt_strlen] ?? '';
// A tag is the last char maybe
- if ($next_c == '')
+ if ($next_c == '') {
break;
+ }
// A test validation?
- if (isset($possible['test']) && preg_match('~^' . $possible['test'] . '~', substr($this->message, $this->pos + 1 + $pt_strlen + 1)) === 0)
- {
+ if (isset($possible['test']) && preg_match('~^' . $possible['test'] . '~', substr($this->message, $this->pos + 1 + $pt_strlen + 1)) === 0) {
continue;
}
+
// Do we want parameters?
- elseif (!empty($possible['parameters']))
- {
+ if (!empty($possible['parameters'])) {
// Are all the parameters optional?
$param_required = false;
- foreach ($possible['parameters'] as $param)
- {
- if (empty($param['optional']))
- {
+ foreach ($possible['parameters'] as $param) {
+ if (empty($param['optional'])) {
$param_required = true;
break;
}
}
- if ($param_required && $next_c != ' ')
+ if ($param_required && $next_c != ' ') {
continue;
+ }
}
// No parameters, so does the next character match what we expect?
- elseif (isset($possible['type']))
- {
+ elseif (isset($possible['type'])) {
// Do we need an equal sign?
- if (in_array($possible['type'], array('unparsed_equals', 'unparsed_commas', 'unparsed_commas_content', 'unparsed_equals_content', 'parsed_equals')) && $next_c != '=')
- {
+ if (in_array($possible['type'], ['unparsed_equals', 'unparsed_commas', 'unparsed_commas_content', 'unparsed_equals_content', 'parsed_equals']) && $next_c != '=') {
continue;
}
// Maybe we just want a /...
- if ($possible['type'] == 'closed' && $next_c != ']' && substr($this->message, $this->pos + 1 + $pt_strlen, 2) != '/]' && substr($this->message, $this->pos + 1 + $pt_strlen, 3) != ' /]')
- {
+ if ($possible['type'] == 'closed' && $next_c != ']' && substr($this->message, $this->pos + 1 + $pt_strlen, 2) != '/]' && substr($this->message, $this->pos + 1 + $pt_strlen, 3) != ' /]') {
continue;
}
// An immediate ]?
- if ($possible['type'] == 'unparsed_content' && $next_c != ']')
- {
+ if ($possible['type'] == 'unparsed_content' && $next_c != ']') {
continue;
}
}
// No type means 'parsed_content', which demands an immediate ] without parameters!
- elseif ($next_c != ']')
- {
+ elseif ($next_c != ']') {
continue;
}
// Check allowed tree?
- if (isset($possible['require_parents']) && ($this->inside === null || !in_array($this->inside['tag'], $possible['require_parents'])))
- {
+ if (isset($possible['require_parents']) && ($this->inside === null || !in_array($this->inside['tag'], $possible['require_parents']))) {
continue;
}
- if (isset($this->inside['require_children']) && !in_array($possible['tag'], $this->inside['require_children']))
- {
+ if (isset($this->inside['require_children']) && !in_array($possible['tag'], $this->inside['require_children'])) {
continue;
}
// If this is in the list of disallowed child tags, don't parse it.
- if (isset($this->inside['disallow_children']) && in_array($possible['tag'], $this->inside['disallow_children']))
- {
+ if (isset($this->inside['disallow_children']) && in_array($possible['tag'], $this->inside['disallow_children'])) {
continue;
}
$this->pos1 = $this->pos + 1 + $pt_strlen + 1;
// Quotes can have alternate styling, we do this php-side due to all the permutations of quotes.
- if ($possible['tag'] == 'quote')
- {
+ if ($possible['tag'] == 'quote') {
// Start with standard
$quote_alt = false;
- foreach ($this->open_tags as $open_quote)
- {
+ foreach ($this->open_tags as $open_quote) {
// Every parent quote this quote has flips the styling
- if ($open_quote['tag'] == 'quote')
+ if ($open_quote['tag'] == 'quote') {
$quote_alt = !$quote_alt;
+ }
}
// Add a class to the quote to style alternating blockquotes
- $possible['before'] = strtr($possible['before'], array('' => ''));
+ $possible['before'] = strtr($possible['before'], ['' => '']);
}
// This is long, but it makes things much easier and cleaner.
- if (!empty($possible['parameters']))
- {
+ if (!empty($possible['parameters'])) {
// Build a regular expression for each parameter for the current tag.
$regex_key = json_encode($possible['parameters']);
- if (!isset($params_regexes[$regex_key]))
- {
+ if (!isset($params_regexes[$regex_key])) {
$params_regexes[$regex_key] = '';
- foreach ($possible['parameters'] as $p => $info)
- {
- $params_regexes[$regex_key] .= '(\s+' . $p . '=' . (empty($info['quoted']) ? '' : '"') . (isset($info['match']) ? $info['match'] : '(.+?)') . (empty($info['quoted']) ? '' : '"') . '\s*)' . (empty($info['optional']) ? '' : '?');
+ foreach ($possible['parameters'] as $p => $info) {
+ $params_regexes[$regex_key] .= '(\s+' . $p . '=' . (empty($info['quoted']) ? '' : '"') . ($info['match'] ?? '(.+?)') . (empty($info['quoted']) ? '' : '"') . '\s*)' . (empty($info['optional']) ? '' : '?');
}
}
@@ -4052,8 +3858,8 @@ protected function detectTag(string $tag_character): array
// Progressively append more blobs until we find our parameters or run out of blobs
$blob_counter = 1;
- while ($blob_counter <= count($blobs))
- {
+
+ while ($blob_counter <= count($blobs)) {
$given_param_string = implode(']', array_slice($blobs, 0, $blob_counter++));
$given_params = preg_split('~\s(?=(' . $splitters . '))~i', $given_param_string);
@@ -4061,57 +3867,46 @@ protected function detectTag(string $tag_character): array
$match = preg_match('~^' . $params_regexes[$regex_key] . '$~i', implode(' ', $given_params), $matches) !== 0;
- if ($match)
+ if ($match) {
break;
+ }
}
// Didn't match our parameter list, try the next possible.
- if (!$match)
+ if (!$match) {
continue;
+ }
- $params = array();
- for ($i = 1, $n = count($matches); $i < $n; $i += 2)
- {
+ $params = [];
+
+ for ($i = 1, $n = count($matches); $i < $n; $i += 2) {
$key = strtok(ltrim($matches[$i]), '=');
- if ($key === false)
+ if ($key === false) {
continue;
-
- if (isset($possible['parameters'][$key]['value']))
- {
- $params['{' . $key . '}'] = strtr($possible['parameters'][$key]['value'], array('$1' => $matches[$i + 1]));
}
- elseif (isset($possible['parameters'][$key]['validate']))
- {
+
+ if (isset($possible['parameters'][$key]['value'])) {
+ $params['{' . $key . '}'] = strtr($possible['parameters'][$key]['value'], ['$1' => $matches[$i + 1]]);
+ } elseif (isset($possible['parameters'][$key]['validate'])) {
$params['{' . $key . '}'] = $possible['parameters'][$key]['validate']($matches[$i + 1]);
- }
- else
- {
+ } else {
$params['{' . $key . '}'] = $matches[$i + 1];
}
// Just to make sure: replace any $ or { so they can't interpolate wrongly.
- $params['{' . $key . '}'] = strtr($params['{' . $key . '}'], array('$' => '$', '{' => '{'));
+ $params['{' . $key . '}'] = strtr($params['{' . $key . '}'], ['$' => '$', '{' => '{']);
}
- foreach ($possible['parameters'] as $p => $info)
- {
- if (!isset($params['{' . $p . '}']))
- {
- if (!isset($info['default']))
- {
+ foreach ($possible['parameters'] as $p => $info) {
+ if (!isset($params['{' . $p . '}'])) {
+ if (!isset($info['default'])) {
$params['{' . $p . '}'] = '';
- }
- elseif (isset($possible['parameters'][$p]['value']))
- {
- $params['{' . $p . '}'] = strtr($possible['parameters'][$p]['value'], array('$1' => $info['default']));
- }
- elseif (isset($possible['parameters'][$p]['validate']))
- {
+ } elseif (isset($possible['parameters'][$p]['value'])) {
+ $params['{' . $p . '}'] = strtr($possible['parameters'][$p]['value'], ['$1' => $info['default']]);
+ } elseif (isset($possible['parameters'][$p]['validate'])) {
$params['{' . $p . '}'] = $possible['parameters'][$p]['validate']($info['default']);
- }
- else
- {
+ } else {
$params['{' . $p . '}'] = $info['default'];
}
}
@@ -4120,27 +3915,27 @@ protected function detectTag(string $tag_character): array
$tag = $possible;
// Put the parameters into the string.
- if (isset($tag['before']))
+ if (isset($tag['before'])) {
$tag['before'] = strtr($tag['before'], $params);
+ }
- if (isset($tag['after']))
+ if (isset($tag['after'])) {
$tag['after'] = strtr($tag['after'], $params);
+ }
- if (isset($tag['content']))
+ if (isset($tag['content'])) {
$tag['content'] = strtr($tag['content'], $params);
+ }
$this->pos1 += strlen($given_param_string);
- }
- else
- {
+ } else {
$tag = $possible;
- $params = array();
+ $params = [];
}
-
break;
}
- return array($tag, $params);
+ return [$tag, $params];
}
/**
@@ -4149,43 +3944,40 @@ protected function detectTag(string $tag_character): array
*/
protected function parseItemCode(): void
{
- if ($this->message[$this->pos + 1] == '0' && !in_array($this->message[$this->pos - 1], array(';', ' ', "\t", "\n", '>')))
+ if ($this->message[$this->pos + 1] == '0' && !in_array($this->message[$this->pos - 1], [';', ' ', "\t", "\n", '>'])) {
return;
+ }
$type = self::$itemcodes[$this->message[$this->pos + 1]];
// First let's set up the tree: it needs to be in a list, or after an li.
- if ($this->inside === null || ($this->inside['tag'] != 'list' && $this->inside['tag'] != 'li'))
- {
- $this->open_tags[] = array(
+ if ($this->inside === null || ($this->inside['tag'] != 'list' && $this->inside['tag'] != 'li')) {
+ $this->open_tags[] = [
'tag' => 'list',
'after' => '',
'block_level' => true,
- 'require_children' => array('li'),
- 'disallow_children' => isset($this->inside['disallow_children']) ? $this->inside['disallow_children'] : null,
- );
+ 'require_children' => ['li'],
+ 'disallow_children' => $this->inside['disallow_children'] ?? null,
+ ];
$html = '';
}
// We're in a list item already: another itemcode? Close it first.
- elseif ($this->inside['tag'] == 'li')
- {
+ elseif ($this->inside['tag'] == 'li') {
array_pop($this->open_tags);
$html = '';
- }
- else
- {
+ } else {
$html = '';
}
// Now we open a new tag.
- $this->open_tags[] = array(
+ $this->open_tags[] = [
'tag' => 'li',
'after' => '',
'trim' => 'outside',
'block_level' => true,
- 'disallow_children' => isset($this->inside['disallow_children']) ? $this->inside['disallow_children'] : null,
- );
+ 'disallow_children' => $this->inside['disallow_children'] ?? null,
+ ];
// First, open the tag...
$html .= '- ';
@@ -4198,8 +3990,7 @@ protected function parseItemCode(): void
$pos2 = strpos($this->message, '
', $this->pos);
$pos3 = strpos($this->message, '[/', $this->pos);
- if ($pos2 !== false && ($pos2 <= $pos3 || $pos3 === false))
- {
+ if ($pos2 !== false && ($pos2 <= $pos3 || $pos3 === false)) {
preg_match('~^( | |\s|\[)+~', substr($this->message, $pos2 + 4), $matches);
$this->message = substr($this->message, 0, $pos2) . (!empty($matches[0]) && substr($matches[0], -1) == '[' ? '[/li]' : '[/li][/list]') . substr($this->message, $pos2);
@@ -4207,8 +3998,7 @@ protected function parseItemCode(): void
$this->open_tags[count($this->open_tags) - 2]['after'] = ' ';
}
// Tell the [list] that it needs to close specially.
- else
- {
+ else {
// Move the li over, because we're not sure what we'll hit.
$this->open_tags[count($this->open_tags) - 1]['after'] = '';
$this->open_tags[count($this->open_tags) - 2]['after'] = '';
@@ -4223,19 +4013,14 @@ protected function parseItemCode(): void
*/
protected function useDisabledTag(array $tag): array
{
- if (!isset($tag['disabled_before']) && !isset($tag['disabled_after']) && !isset($tag['disabled_content']))
- {
+ if (!isset($tag['disabled_before']) && !isset($tag['disabled_after']) && !isset($tag['disabled_content'])) {
$tag['before'] = !empty($tag['block_level']) ? '' : '';
$tag['after'] = !empty($tag['block_level']) ? ' ' : '';
$tag['content'] = isset($tag['type']) && $tag['type'] == 'closed' ? '' : (!empty($tag['block_level']) ? '$1 ' : '$1');
- }
- elseif (isset($tag['disabled_before']) || isset($tag['disabled_after']))
- {
- $tag['before'] = isset($tag['disabled_before']) ? $tag['disabled_before'] : (!empty($tag['block_level']) ? '' : '');
- $tag['after'] = isset($tag['disabled_after']) ? $tag['disabled_after'] : (!empty($tag['block_level']) ? ' ' : '');
- }
- else
- {
+ } elseif (isset($tag['disabled_before']) || isset($tag['disabled_after'])) {
+ $tag['before'] = $tag['disabled_before'] ?? (!empty($tag['block_level']) ? '' : '');
+ $tag['after'] = $tag['disabled_after'] ?? (!empty($tag['block_level']) ? ' ' : '');
+ } else {
$tag['content'] = $tag['disabled_content'];
}
@@ -4250,12 +4035,12 @@ protected function closeInlineTags(): void
{
$n = count($this->open_tags) - 1;
- while (empty($this->open_tags[$n]['block_level']) && $n >= 0)
+ while (empty($this->open_tags[$n]['block_level']) && $n >= 0) {
$n--;
+ }
// Close all the non block level tags so this tag isn't surrounded by them.
- for ($i = count($this->open_tags) - 1; $i > $n; $i--)
- {
+ for ($i = count($this->open_tags) - 1; $i > $n; $i--) {
$this->message = substr($this->message, 0, $this->pos) . "\n" . $this->open_tags[$i]['after'] . "\n" . substr($this->message, $this->pos);
$ot_strlen = strlen($this->open_tags[$i]['after']);
@@ -4265,16 +4050,15 @@ protected function closeInlineTags(): void
// Trim or eat trailing stuff...
$whitespace_regex = '';
- if (!empty($tag['block_level']))
+ if (!empty($tag['block_level'])) {
$whitespace_regex .= '( |\s)*( )?';
+ }
- if (!empty($tag['trim']) && $tag['trim'] != 'inside')
- {
+ if (!empty($tag['trim']) && $tag['trim'] != 'inside') {
$whitespace_regex .= empty($tag['require_parents']) ? '( |\s)*' : '( | |\s)*';
}
- if (!empty($whitespace_regex) && preg_match('~' . $whitespace_regex . '~', substr($this->message, $this->pos), $matches) != 0)
- {
+ if (!empty($whitespace_regex) && preg_match('~' . $whitespace_regex . '~', substr($this->message, $this->pos), $matches) != 0) {
$this->message = substr($this->message, 0, $this->pos) . substr($this->message, $this->pos + strlen($matches[0]));
}
@@ -4292,54 +4076,58 @@ protected function closeInlineTags(): void
protected function transformToHtml(array $tag, array $params): void
{
// Insert Lang::$txt strings into the HTML output.
- foreach (array('content', 'before', 'after') as $key)
- {
- if (isset($tag[$key]))
+ foreach (['content', 'before', 'after'] as $key) {
+ if (isset($tag[$key])) {
$tag[$key] = $this->insertTxt($tag[$key]);
+ }
- if (isset($tag['disabled_' . $key]))
+ if (isset($tag['disabled_' . $key])) {
$tag['disabled_' . $key] = $this->insertTxt($tag['disabled_' . $key]);
+ }
}
// We use this a lot.
$tag_strlen = strlen($tag['tag']);
// Set the validation method to something we can call.
- if (isset($tag['validate']) && is_string($tag['validate']))
+ if (isset($tag['validate']) && is_string($tag['validate'])) {
$tag['validate'] = Utils::getCallable($tag['validate']);
+ }
// No type means 'parsed_content'.
- if (!isset($tag['type']))
- {
+ if (!isset($tag['type'])) {
$this->open_tags[] = $tag;
// There's no data to change, but maybe do something based on params?
$data = null;
- if (isset($tag['validate']))
- call_user_func_array($tag['validate'], array(&$tag, &$data, $this->disabled, $params));
+ if (isset($tag['validate'])) {
+ call_user_func_array($tag['validate'], [&$tag, &$data, $this->disabled, $params]);
+ }
$this->message = substr($this->message, 0, $this->pos) . "\n" . $tag['before'] . "\n" . substr($this->message, $this->pos1);
$this->pos += strlen($tag['before']) - 1 + 2;
}
// Don't parse the content, just skip it.
- elseif ($tag['type'] == 'unparsed_content')
- {
+ elseif ($tag['type'] == 'unparsed_content') {
$pos2 = stripos($this->message, '[/' . substr($this->message, $this->pos + 1, $tag_strlen) . ']', $this->pos1);
- if ($pos2 === false)
+ if ($pos2 === false) {
return;
+ }
$data = substr($this->message, $this->pos1, $pos2 - $this->pos1);
- if (!empty($tag['block_level']) && substr($data, 0, 4) == ' ')
+ if (!empty($tag['block_level']) && substr($data, 0, 4) == ' ') {
$data = substr($data, 4);
+ }
- if (isset($tag['validate']))
- call_user_func_array($tag['validate'], array(&$tag, &$data, $this->disabled, $params));
+ if (isset($tag['validate'])) {
+ call_user_func_array($tag['validate'], [&$tag, &$data, $this->disabled, $params]);
+ }
- $html = strtr($tag['content'], array('$1' => $data));
+ $html = strtr($tag['content'], ['$1' => $data]);
$this->message = substr($this->message, 0, $this->pos) . "\n" . $html . "\n" . substr($this->message, $pos2 + 3 + $tag_strlen);
@@ -4347,179 +4135,185 @@ protected function transformToHtml(array $tag, array $params): void
$this->last_pos = $this->pos + 1;
}
// Don't parse the content, just skip it.
- elseif ($tag['type'] == 'unparsed_equals_content')
- {
+ elseif ($tag['type'] == 'unparsed_equals_content') {
// The value may be quoted for some tags - check.
- if (isset($tag['quoted']))
- {
+ if (isset($tag['quoted'])) {
$quoted = substr($this->message, $this->pos1, 6) == '"';
- if ($tag['quoted'] != 'optional' && !$quoted)
+ if ($tag['quoted'] != 'optional' && !$quoted) {
return;
+ }
- if ($quoted)
+ if ($quoted) {
$this->pos1 += 6;
- }
- else
- {
+ }
+ } else {
$quoted = false;
}
$pos2 = strpos($this->message, $quoted == false ? ']' : '"]', $this->pos1);
- if ($pos2 === false)
+ if ($pos2 === false) {
return;
+ }
$pos3 = stripos($this->message, '[/' . substr($this->message, $this->pos + 1, $tag_strlen) . ']', $pos2);
- if ($pos3 === false)
+ if ($pos3 === false) {
return;
+ }
- $data = array(
+ $data = [
substr($this->message, $pos2 + ($quoted == false ? 1 : 7), $pos3 - ($pos2 + ($quoted == false ? 1 : 7))),
- substr($this->message, $this->pos1, $pos2 - $this->pos1)
- );
+ substr($this->message, $this->pos1, $pos2 - $this->pos1),
+ ];
- if (!empty($tag['block_level']) && substr($data[0], 0, 4) == ' ')
+ if (!empty($tag['block_level']) && substr($data[0], 0, 4) == ' ') {
$data[0] = substr($data[0], 4);
+ }
// Validation for my parking, please!
- if (isset($tag['validate']))
- call_user_func_array($tag['validate'], array(&$tag, &$data, $this->disabled, $params));
+ if (isset($tag['validate'])) {
+ call_user_func_array($tag['validate'], [&$tag, &$data, $this->disabled, $params]);
+ }
- $html = strtr($tag['content'], array('$1' => $data[0], '$2' => $data[1]));
+ $html = strtr($tag['content'], ['$1' => $data[0], '$2' => $data[1]]);
$this->message = substr($this->message, 0, $this->pos) . "\n" . $html . "\n" . substr($this->message, $pos3 + 3 + $tag_strlen);
$this->pos += strlen($html) - 1 + 2;
}
// A closed tag, with no content or value.
- elseif ($tag['type'] == 'closed')
- {
+ elseif ($tag['type'] == 'closed') {
$pos2 = strpos($this->message, ']', $this->pos);
// Maybe a custom BBC wants to do something special?
$data = null;
- if (isset($tag['validate']))
- call_user_func_array($tag['validate'], array(&$tag, &$data, $this->disabled, $params));
+ if (isset($tag['validate'])) {
+ call_user_func_array($tag['validate'], [&$tag, &$data, $this->disabled, $params]);
+ }
$this->message = substr($this->message, 0, $this->pos) . "\n" . $tag['content'] . "\n" . substr($this->message, $pos2 + 1);
$this->pos += strlen($tag['content']) - 1 + 2;
}
// This one is sorta ugly... :/. Unfortunately, it's needed for flash.
- elseif ($tag['type'] == 'unparsed_commas_content')
- {
+ elseif ($tag['type'] == 'unparsed_commas_content') {
$pos2 = strpos($this->message, ']', $this->pos1);
- if ($pos2 === false)
+ if ($pos2 === false) {
return;
+ }
$pos3 = stripos($this->message, '[/' . substr($this->message, $this->pos + 1, $tag_strlen) . ']', $pos2);
- if ($pos3 === false)
+ if ($pos3 === false) {
return;
+ }
// We want $1 to be the content, and the rest to be csv.
$data = explode(',', ',' . substr($this->message, $this->pos1, $pos2 - $this->pos1));
$data[0] = substr($this->message, $pos2 + 1, $pos3 - $pos2 - 1);
- if (isset($tag['validate']))
- call_user_func_array($tag['validate'], array(&$tag, &$data, $this->disabled, $params));
+ if (isset($tag['validate'])) {
+ call_user_func_array($tag['validate'], [&$tag, &$data, $this->disabled, $params]);
+ }
$html = $tag['content'];
- foreach ($data as $k => $d)
- $html = strtr($html, array('$' . ($k + 1) => trim($d)));
+ foreach ($data as $k => $d) {
+ $html = strtr($html, ['$' . ($k + 1) => trim($d)]);
+ }
$this->message = substr($this->message, 0, $this->pos) . "\n" . $html . "\n" . substr($this->message, $pos3 + 3 + $tag_strlen);
$this->pos += strlen($html) - 1 + 2;
}
// This has parsed content, and a csv value which is unparsed.
- elseif ($tag['type'] == 'unparsed_commas')
- {
+ elseif ($tag['type'] == 'unparsed_commas') {
$pos2 = strpos($this->message, ']', $this->pos1);
- if ($pos2 === false)
+ if ($pos2 === false) {
return;
+ }
$data = explode(',', substr($this->message, $this->pos1, $pos2 - $this->pos1));
- if (isset($tag['validate']))
- call_user_func_array($tag['validate'], array(&$tag, &$data, $this->disabled, $params));
+ if (isset($tag['validate'])) {
+ call_user_func_array($tag['validate'], [&$tag, &$data, $this->disabled, $params]);
+ }
// Fix after, for disabled code mainly.
- foreach ($data as $k => $d)
- $tag['after'] = strtr($tag['after'], array('$' . ($k + 1) => trim($d)));
+ foreach ($data as $k => $d) {
+ $tag['after'] = strtr($tag['after'], ['$' . ($k + 1) => trim($d)]);
+ }
$this->open_tags[] = $tag;
// Replace them out, $1, $2, $3, $4, etc.
$html = $tag['before'];
- foreach ($data as $k => $d)
- $html = strtr($html, array('$' . ($k + 1) => trim($d)));
+ foreach ($data as $k => $d) {
+ $html = strtr($html, ['$' . ($k + 1) => trim($d)]);
+ }
$this->message = substr($this->message, 0, $this->pos) . "\n" . $html . "\n" . substr($this->message, $pos2 + 1);
$this->pos += strlen($html) - 1 + 2;
}
// A tag set to a value, parsed or not.
- elseif ($tag['type'] == 'unparsed_equals' || $tag['type'] == 'parsed_equals')
- {
+ elseif ($tag['type'] == 'unparsed_equals' || $tag['type'] == 'parsed_equals') {
// The value may be quoted for some tags - check.
- if (isset($tag['quoted']))
- {
+ if (isset($tag['quoted'])) {
$quoted = substr($this->message, $this->pos1, 6) == '"';
- if ($tag['quoted'] != 'optional' && !$quoted)
+ if ($tag['quoted'] != 'optional' && !$quoted) {
return;
+ }
- if ($quoted)
+ if ($quoted) {
$this->pos1 += 6;
- }
- else
- {
+ }
+ } else {
$quoted = false;
}
- if ($quoted)
- {
+ if ($quoted) {
$end_of_value = strpos($this->message, '"]', $this->pos1);
$nested_tag = strpos($this->message, '="', $this->pos1);
// Check so this is not just an quoted url ending with a =
- if ($nested_tag && substr($this->message, $nested_tag, 8) == '="]')
+ if ($nested_tag && substr($this->message, $nested_tag, 8) == '="]') {
$nested_tag = false;
+ }
- if ($nested_tag && $nested_tag < $end_of_value)
- {
+ if ($nested_tag && $nested_tag < $end_of_value) {
// Nested tag with quoted value detected, use next end tag
$nested_tag_pos = strpos($this->message, $quoted == false ? ']' : '"]', $this->pos1) + 6;
}
}
- $pos2 = strpos($this->message, $quoted == false ? ']' : '"]', isset($nested_tag_pos) ? $nested_tag_pos : $this->pos1);
+ $pos2 = strpos($this->message, $quoted == false ? ']' : '"]', $nested_tag_pos ?? $this->pos1);
- if ($pos2 === false)
+ if ($pos2 === false) {
return;
+ }
$data = substr($this->message, $this->pos1, $pos2 - $this->pos1);
// Validation for my parking, please!
- if (isset($tag['validate']))
- call_user_func_array($tag['validate'], array(&$tag, &$data, $this->disabled, $params));
+ if (isset($tag['validate'])) {
+ call_user_func_array($tag['validate'], [&$tag, &$data, $this->disabled, $params]);
+ }
// For parsed content, we must recurse to avoid security problems.
- if ($tag['type'] != 'unparsed_equals')
- {
+ if ($tag['type'] != 'unparsed_equals') {
$smileys = $this->smileys;
$parse_tags = $this->parse_tags;
$this->smileys = empty($tag['parsed_tags_allowed']);
- $this->parse_tags = !empty($tag['parsed_tags_allowed']) ? $tag['parsed_tags_allowed'] : array();
+ $this->parse_tags = !empty($tag['parsed_tags_allowed']) ? $tag['parsed_tags_allowed'] : [];
$data = $this->parse($data);
@@ -4527,11 +4321,11 @@ protected function transformToHtml(array $tag, array $params): void
$this->parse_tags = $parse_tags;
}
- $tag['after'] = strtr($tag['after'], array('$1' => $data));
+ $tag['after'] = strtr($tag['after'], ['$1' => $data]);
$this->open_tags[] = $tag;
- $html = strtr($tag['before'], array('$1' => $data));
+ $html = strtr($tag['before'], ['$1' => $data]);
$this->message = substr($this->message, 0, $this->pos) . "\n" . $html . "\n" . substr($this->message, $pos2 + ($quoted == false ? 1 : 7));
@@ -4539,14 +4333,12 @@ protected function transformToHtml(array $tag, array $params): void
}
// If this is block level, eat any breaks after it.
- if (!empty($tag['block_level']) && substr($this->message, $this->pos + 1, 4) == ' ')
- {
+ if (!empty($tag['block_level']) && substr($this->message, $this->pos + 1, 4) == ' ') {
$this->message = substr($this->message, 0, $this->pos + 1) . substr($this->message, $this->pos + 5);
}
// Are we trimming outside this tag?
- if (!empty($tag['trim']) && $tag['trim'] != 'outside' && preg_match('~( | |\s)*~', substr($this->message, $this->pos + 1), $matches) != 0)
- {
+ if (!empty($tag['trim']) && $tag['trim'] != 'outside' && preg_match('~( | |\s)*~', substr($this->message, $this->pos + 1), $matches) != 0) {
$this->message = substr($this->message, 0, $this->pos + 1) . substr($this->message, $this->pos + 1 + strlen($matches[0]));
}
}
@@ -4561,68 +4353,52 @@ protected function transformToHtml(array $tag, array $params): void
*/
protected function fetchTagAttributes($string)
{
- $attribs = array();
+ $attribs = [];
$key = $value = '';
$tag_state = 0; // 0 = key, 1 = attribute with no string, 2 = attribute with string
- for ($i = 0; $i < strlen($string); $i++)
- {
+ for ($i = 0; $i < strlen($string); $i++) {
// We're either moving from the key to the attribute or we're in a string and this is fine.
- if ($string[$i] == '=')
- {
- if ($tag_state == 0)
- {
+ if ($string[$i] == '=') {
+ if ($tag_state == 0) {
$tag_state = 1;
- }
- elseif ($tag_state == 2)
- {
+ } elseif ($tag_state == 2) {
$value .= '=';
}
}
// A space is either moving from an attribute back to a potential key or in a string is fine.
- elseif ($string[$i] == ' ')
- {
- if ($tag_state == 2)
- {
+ elseif ($string[$i] == ' ') {
+ if ($tag_state == 2) {
$value .= ' ';
- }
- elseif ($tag_state == 1)
- {
+ } elseif ($tag_state == 1) {
$attribs[$key] = $value;
$key = $value = '';
$tag_state = 0;
}
}
// A quote?
- elseif ($string[$i] == '"')
- {
+ elseif ($string[$i] == '"') {
// Must be either going into or out of a string.
- if ($tag_state == 1)
- {
+ if ($tag_state == 1) {
$tag_state = 2;
- }
- else
- {
+ } else {
$tag_state = 1;
}
}
// Otherwise it's fine.
- else
- {
- if ($tag_state == 0)
- {
+ else {
+ if ($tag_state == 0) {
$key .= $string[$i];
- }
- else
- {
+ } else {
$value .= $string[$i];
}
}
}
// Anything left?
- if ($key != '' && $value != '')
+ if ($key != '' && $value != '') {
$attribs[$key] = $value;
+ }
return $attribs;
}
@@ -4639,62 +4415,58 @@ protected function fetchTagAttributes($string)
protected function legalise($string)
{
// Don't care about the texts that are too short.
- if (strlen($string) < 3)
+ if (strlen($string) < 3) {
return $string;
+ }
// A list of tags that's disabled by the admin.
- $disabled = empty(Config::$modSettings['disabledBBC']) ? array() : array_flip(explode(',', strtolower(Config::$modSettings['disabledBBC'])));
+ $disabled = empty(Config::$modSettings['disabledBBC']) ? [] : array_flip(explode(',', strtolower(Config::$modSettings['disabledBBC'])));
// Get a list of all the tags that are not disabled.
$all_tags = self::getCodes();
- $valid_tags = array();
- $self_closing_tags = array();
+ $valid_tags = [];
+ $self_closing_tags = [];
- foreach ($all_tags as $tag)
- {
- if (!isset($disabled[$tag['tag']]))
+ foreach ($all_tags as $tag) {
+ if (!isset($disabled[$tag['tag']])) {
$valid_tags[$tag['tag']] = !empty($tag['block_level']);
+ }
- if (isset($tag['type']) && $tag['type'] == 'closed')
+ if (isset($tag['type']) && $tag['type'] == 'closed') {
$self_closing_tags[] = $tag['tag'];
+ }
}
// Right - we're going to start by going through the whole lot to make sure we don't have align stuff crossed as this happens load and is stupid!
- $align_tags = array('left', 'center', 'right', 'pre');
+ $align_tags = ['left', 'center', 'right', 'pre'];
// Remove those align tags that are not valid.
$align_tags = array_intersect($align_tags, array_keys($valid_tags));
// These keep track of where we are!
- if (!empty($align_tags) && count($matches = preg_split('~(\\[/?(?:' . implode('|', $align_tags) . ')\\])~', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
- {
+ if (!empty($align_tags) && count($matches = preg_split('~(\[/?(?:' . implode('|', $align_tags) . ')\])~', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1) {
// The first one is never a tag.
$is_tag = false;
// By default we're not inside a tag too.
$inside_tag = null;
- foreach ($matches as $i => $match)
- {
+ foreach ($matches as $i => $match) {
// We're only interested in tags, not text.
- if ($is_tag)
- {
+ if ($is_tag) {
$is_closing_tag = substr($match, 1, 1) === '/';
$tag_name = substr($match, $is_closing_tag ? 2 : 1, -1);
// We're closing the exact same tag that we opened.
- if ($is_closing_tag && $inside_tag === $tag_name)
- {
+ if ($is_closing_tag && $inside_tag === $tag_name) {
$inside_tag = null;
}
// We're opening a tag and we're not yet inside one either
- elseif (!$is_closing_tag && $inside_tag === null)
- {
+ elseif (!$is_closing_tag && $inside_tag === null) {
$inside_tag = $tag_name;
}
// In all other cases, this tag must be invalid
- else
- {
+ else {
unset($matches[$i]);
}
}
@@ -4704,55 +4476,54 @@ protected function legalise($string)
}
// We're still inside a tag and had no chance for closure?
- if ($inside_tag !== null)
+ if ($inside_tag !== null) {
$matches[] = '[/' . $inside_tag . ']';
+ }
// And a complete text string again.
$string = implode('', $matches);
}
// Quickly remove any tags which are back to back.
- $back_to_back_pattern = '~\\[(' . implode('|', array_diff(array_keys($valid_tags), array('td', 'anchor'))) . ')[^<>\\[\\]]*\\]\s*\\[/\\1\\]~';
+ $back_to_back_pattern = '~\[(' . implode('|', array_diff(array_keys($valid_tags), ['td', 'anchor'])) . ')[^<>\[\]]*\]\s*\[/\1\]~';
$lastlen = 0;
- while (strlen($string) !== $lastlen)
+ while (strlen($string) !== $lastlen) {
$lastlen = strlen($string = preg_replace($back_to_back_pattern, '', $string));
+ }
// Need to sort the tags by name length.
uksort(
$valid_tags,
- function($a, $b)
- {
+ function ($a, $b) {
return strlen($a) < strlen($b) ? 1 : -1;
- }
+ },
);
// These inline tags can compete with each other regarding style.
- $competing_tags = array(
+ $competing_tags = [
'color',
'size',
- );
+ ];
// These keep track of where we are!
- if (count($parts = preg_split(sprintf('~(\\[)(/?)(%1$s)((?:[\\s=][^\\]\\[]*)?\\])~', implode('|', array_keys($valid_tags))), $string, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
- {
+ if (count($parts = preg_split(sprintf('~(\[)(/?)(%1$s)((?:[\s=][^\]\[]*)?\])~', implode('|', array_keys($valid_tags))), $string, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1) {
// Start outside [nobbc] or [code] blocks.
$in_code = false;
$in_nobbc = false;
// A buffer containing all opened inline elements.
- $inline_elements = array();
+ $inline_elements = [];
// A buffer containing all opened block elements.
- $block_elements = array();
+ $block_elements = [];
// A buffer containing the opened inline elements that might compete.
- $competing_elements = array();
+ $competing_elements = [];
// $i: text, $i + 1: '[', $i + 2: '/', $i + 3: tag, $i + 4: tag tail.
- for ($i = 0, $n = count($parts) - 1; $i < $n; $i += 5)
- {
+ for ($i = 0, $n = count($parts) - 1; $i < $n; $i += 5) {
$tag = $parts[$i + 3];
$is_opening_tag = $parts[$i + 2] === '';
$is_closing_tag = $parts[$i + 2] === '/';
@@ -4760,30 +4531,25 @@ function($a, $b)
$is_competing_tag = in_array($tag, $competing_tags);
// Check if this might be one of those cleaned out tags.
- if ($tag === '')
- {
+ if ($tag === '') {
continue;
}
+
// Special case: inside [code] blocks any code is left untouched.
- elseif ($tag === 'code')
- {
+ if ($tag === 'code') {
// We're inside a code block and closing it.
- if ($in_code && $is_closing_tag)
- {
+ if ($in_code && $is_closing_tag) {
$in_code = false;
// Reopen tags that were closed before the code block.
- if (!empty($inline_elements))
- {
+ if (!empty($inline_elements)) {
$parts[$i + 4] .= '[' . implode('][', array_keys($inline_elements)) . ']';
}
}
// We're outside a coding and nobbc block and opening it.
- elseif (!$in_code && !$in_nobbc && $is_opening_tag)
- {
+ elseif (!$in_code && !$in_nobbc && $is_opening_tag) {
// If there are still inline elements left open, close them now.
- if (!empty($inline_elements))
- {
+ if (!empty($inline_elements)) {
$parts[$i] .= '[/' . implode('][/', array_reverse($inline_elements)) . ']';
}
@@ -4793,26 +4559,22 @@ function($a, $b)
// Nothing further to do.
continue;
}
+
// Special case: inside [nobbc] blocks any BBC is left untouched.
- elseif ($tag === 'nobbc')
- {
+ if ($tag === 'nobbc') {
// We're inside a nobbc block and closing it.
- if ($in_nobbc && $is_closing_tag)
- {
+ if ($in_nobbc && $is_closing_tag) {
$in_nobbc = false;
// Some inline elements might've been closed that need reopening.
- if (!empty($inline_elements))
- {
+ if (!empty($inline_elements)) {
$parts[$i + 4] .= '[' . implode('][', array_keys($inline_elements)) . ']';
}
}
// We're outside a nobbc and coding block and opening it.
- elseif (!$in_nobbc && !$in_code && $is_opening_tag)
- {
+ elseif (!$in_nobbc && !$in_code && $is_opening_tag) {
// Can't have inline elements still opened.
- if (!empty($inline_elements))
- {
+ if (!empty($inline_elements)) {
$parts[$i] .= '[/' . implode('][/', array_reverse($inline_elements)) . ']';
}
@@ -4821,24 +4583,21 @@ function($a, $b)
continue;
}
+
// So, we're inside one of the special blocks: ignore any tag.
- elseif ($in_code || $in_nobbc)
- {
+ if ($in_code || $in_nobbc) {
continue;
}
// We're dealing with an opening tag.
- if ($is_opening_tag)
- {
+ if ($is_opening_tag) {
// Everything inside the square brackets of the opening tag.
$element_content = $parts[$i + 3] . substr($parts[$i + 4], 0, -1);
// A block level opening tag.
- if ($is_block_level_tag)
- {
+ if ($is_block_level_tag) {
// Are there inline elements still open?
- if (!empty($inline_elements))
- {
+ if (!empty($inline_elements)) {
// Close all the inline tags, a block tag is coming...
$parts[$i] .= '[/' . implode('][/', array_reverse($inline_elements)) . ']';
@@ -4849,37 +4608,29 @@ function($a, $b)
$block_elements[] = $tag;
}
// Inline opening tag.
- elseif (!in_array($tag, $self_closing_tags))
- {
+ elseif (!in_array($tag, $self_closing_tags)) {
// Can't have two opening elements with the same contents!
- if (isset($inline_elements[$element_content]))
- {
+ if (isset($inline_elements[$element_content])) {
// Get rid of this tag.
$parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
// Now try to find the corresponding closing tag.
$cur_level = 1;
- for ($j = $i + 5, $m = count($parts) - 1; $j < $m; $j += 5)
- {
+ for ($j = $i + 5, $m = count($parts) - 1; $j < $m; $j += 5) {
// Find the tags with the same tagname
- if ($parts[$j + 3] === $tag)
- {
+ if ($parts[$j + 3] === $tag) {
// If it's an opening tag, increase the level.
- if ($parts[$j + 2] === '')
- {
+ if ($parts[$j + 2] === '') {
$cur_level++;
}
// A closing tag, decrease the level.
- else
- {
+ else {
$cur_level--;
// Gotcha! Clean out this closing tag gone rogue.
- if ($cur_level === 0)
- {
+ if ($cur_level === 0) {
$parts[$j + 1] = $parts[$j + 2] = $parts[$j + 3] = $parts[$j + 4] = '';
-
break;
}
}
@@ -4887,17 +4638,17 @@ function($a, $b)
}
}
// Otherwise, add this one to the list.
- else
- {
- if ($is_competing_tag)
- {
- if (!isset($competing_elements[$tag]))
- $competing_elements[$tag] = array();
+ else {
+ if ($is_competing_tag) {
+ if (!isset($competing_elements[$tag])) {
+ $competing_elements[$tag] = [];
+ }
$competing_elements[$tag][] = $parts[$i + 4];
- if (count($competing_elements[$tag]) > 1)
+ if (count($competing_elements[$tag]) > 1) {
$parts[$i] .= '[/' . $tag . ']';
+ }
}
$inline_elements[$element_content] = $tag;
@@ -4905,49 +4656,43 @@ function($a, $b)
}
}
// Closing tag.
- else
- {
+ else {
// Closing the block tag.
- if ($is_block_level_tag)
- {
+ if ($is_block_level_tag) {
// Close the elements that should've been closed by closing this tag.
- if (!empty($block_elements))
- {
- $add_closing_tags = array();
+ if (!empty($block_elements)) {
+ $add_closing_tags = [];
- while ($element = array_pop($block_elements))
- {
- if ($element === $tag)
+ while ($element = array_pop($block_elements)) {
+ if ($element === $tag) {
break;
+ }
// Still a block tag was open not equal to this tag.
$add_closing_tags[] = $element['type'];
}
- if (!empty($add_closing_tags))
- {
+ if (!empty($add_closing_tags)) {
$parts[$i + 1] = '[/' . implode('][/', array_reverse($add_closing_tags)) . ']' . $parts[$i + 1];
}
// Apparently the closing tag was not found on the stack.
- if (!is_string($element) || $element !== $tag)
- {
+ if (!is_string($element) || $element !== $tag) {
// Get rid of this particular closing tag, it was never opened.
$parts[$i + 1] = substr($parts[$i + 1], 0, -1);
$parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
+
continue;
}
- }
- else
- {
+ } else {
// Get rid of this closing tag!
$parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
+
continue;
}
// Inline elements are still left opened?
- if (!empty($inline_elements))
- {
+ if (!empty($inline_elements)) {
// Close them first..
$parts[$i] .= '[/' . implode('][/', array_reverse($inline_elements)) . ']';
@@ -4956,37 +4701,32 @@ function($a, $b)
}
}
// Inline tag.
- else
- {
+ else {
// Are we expecting this tag to end?
- if (in_array($tag, $inline_elements))
- {
- foreach (array_reverse($inline_elements, true) as $tag_content_to_be_closed => $tag_to_be_closed)
- {
+ if (in_array($tag, $inline_elements)) {
+ foreach (array_reverse($inline_elements, true) as $tag_content_to_be_closed => $tag_to_be_closed) {
// Closing it one way or the other.
unset($inline_elements[$tag_content_to_be_closed]);
// Was this the tag we were looking for?
- if ($tag_to_be_closed === $tag)
+ if ($tag_to_be_closed === $tag) {
break;
+ }
// Nope, close it and look further!
$parts[$i] .= '[/' . $tag_to_be_closed . ']';
}
- if ($is_competing_tag && !empty($competing_elements[$tag]))
- {
+ if ($is_competing_tag && !empty($competing_elements[$tag])) {
array_pop($competing_elements[$tag]);
- if (count($competing_elements[$tag]) > 0)
- {
+ if (count($competing_elements[$tag]) > 0) {
$parts[$i + 5] = '[' . $tag . $competing_elements[$tag][count($competing_elements[$tag]) - 1] . $parts[$i + 5];
}
}
}
// Unexpected closing tag, ex-ter-mi-nate.
- else
- {
+ else {
$parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
}
}
@@ -4994,24 +4734,22 @@ function($a, $b)
}
// Close the code tags.
- if ($in_code)
- {
+ if ($in_code) {
$parts[$i] .= '[/code]';
}
// The same for nobbc tags.
- elseif ($in_nobbc)
- {
+ elseif ($in_nobbc) {
$parts[$i] .= '[/nobbc]';
}
// Still inline tags left unclosed? Close them now, better late than never.
- elseif (!empty($inline_elements))
- {
+ elseif (!empty($inline_elements)) {
$parts[$i] .= '[/' . implode('][/', array_reverse($inline_elements)) . ']';
}
// Now close the block elements.
- if (!empty($block_elements))
+ if (!empty($block_elements)) {
$parts[$i] .= '[/' . implode('][/', array_reverse($block_elements)) . ']';
+ }
$string = implode('', $parts);
}
@@ -5019,8 +4757,9 @@ function($a, $b)
// Final clean up of back-to-back tags.
$lastlen = 0;
- while (strlen($string) !== $lastlen)
+ while (strlen($string) !== $lastlen) {
$lastlen = strlen($string = preg_replace($back_to_back_pattern, '', $string));
+ }
return $string;
}
@@ -5031,7 +4770,7 @@ function($a, $b)
protected function resetRuntimeProperties(): void
{
// Reset these properties.
- $to_reset = array(
+ $to_reset = [
'message',
'smileys',
'parse_tags',
@@ -5042,12 +4781,13 @@ protected function resetRuntimeProperties(): void
'placeholders',
'placeholders_counter',
'cache_key_extras',
- );
+ ];
$class_vars = get_class_vars(__CLASS__);
- foreach ($to_reset as $var)
+ foreach ($to_reset as $var) {
$this->{$var} = $class_vars[$var];
+ }
}
/*************************
@@ -5061,16 +4801,14 @@ protected function resetRuntimeProperties(): void
protected static function integrateBBC(): void
{
// Only do this once.
- if (self::$integrate_bbc_codes_done !== true)
- {
- IntegrationHook::call('integrate_bbc_codes', array(&self::$codes, &self::$no_autolink_tags));
+ if (self::$integrate_bbc_codes_done !== true) {
+ IntegrationHook::call('integrate_bbc_codes', [&self::$codes, &self::$no_autolink_tags]);
// Prevent duplicates.
- $temp = array();
+ $temp = [];
// Reverse order because mods typically append to the array.
- for ($i = count(self::$codes) - 1; $i >= 0; $i--)
- {
+ for ($i = count(self::$codes) - 1; $i >= 0; $i--) {
$value = self::$codes[$i];
// Since validation functions may be closures, and
@@ -5079,12 +4817,9 @@ protected static function integrateBBC(): void
$serialized = serialize($value);
- if (!in_array($serialized, $temp))
- {
+ if (!in_array($serialized, $temp)) {
$temp[] = $serialized;
- }
- else
- {
+ } else {
unset(self::$codes[$i]);
}
}
@@ -5095,7 +4830,8 @@ protected static function integrateBBC(): void
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\BBCodeParser::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\BBCodeParser::exportStatic')) {
BBCodeParser::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/BackwardCompatibility.php b/Sources/BackwardCompatibility.php
index 09382f9b2a..c7a117a4a3 100644
--- a/Sources/BackwardCompatibility.php
+++ b/Sources/BackwardCompatibility.php
@@ -36,10 +36,9 @@ trait BackwardCompatibility
* Regarding the $backcompat items:
*
* A class's static properties are not exported to global variables unless
- * explicitly included in $backcompat['prop_names']. In contrast, a class's
- * static methods are automatically exported as global functions unless
- * explicitly excluded by setting their entry in $backcompat['func_names']
- * to false.
+ * explicitly included in $backcompat['prop_names']. Likewise, a class's
+ * static methods are not exported as global functions unless explicitly
+ * included in $backcompat['func_names'].
*
* $backcompat['prop_names'] is a simple array where the keys are the names
* of one or more of a class's static properties, and the values are the
@@ -47,184 +46,51 @@ trait BackwardCompatibility
* to a reference to the static property. Static properties that are not
* named in this array will not be exported.
*
- * $backcompat['func_names'] allows you to manually specify the global
- * function names that any given methods should be mapped to. These
- * manually specified function names will ignore and override the effects
- * of $backcompat['func_underscores'] and $backcompat['func_prefix'].
- * If you want to prevent a static method from being exported to global
- * namespace at all, set its $backcompat['func_names'] entry to false.
+ * $backcompat['func_names'] is a simple array where the keys are the names
+ * of one or more of a class's static methods, and the values are the names
+ * that should be used for global functions that will encapsulate those
+ * methods. Methods that are not named in this array will not be exported.
*
- * For convenience, two additional $backcompat options are available:
- * $backcompat['func_underscores'] and $backcompat['func_prefix'].
- *
- * If $backcompat['func_underscores'] is true, method names in camelCase will
- * have underscores inserted into them (e.g.: 'parseIri' --> 'parse_iri').
- * This should usually only be set to true if the majority of the methods in
- * a class were converted from functions that used underscores in their
- * names. If you need to map method names to function names in a mixture of
- * both styles, choose one style for the default and then deal with the
- * exceptions manually via $backcompat['func_names'].
- *
- * If $backcompat['func_prefix'] is set to a string, that string will be
- * prepended to the function name. If $backcompat['func_underscores'] is
- * true, the prefix will be joined to the rest of the function name by an
- * underscore, but the prefix itself will always be used as-is.
- *
- * If instead $backcompat['func_prefix'] is set to true, a prefix derived
- * from the fully qualified class name will be prepended to the func name.
- * This prefix will respect the value of $backcompat['func_underscores'].
- * In most cases, at least for SMF's code, $backcompat['func_underscores']
- * should be true when $backcompat['func_prefix'] is true.
- *
- * $backcompat['func_underscores'] and $backcompat['func_prefix'] don't apply
- * to functions that are manually named in $backcompat['func_names'].
+ * Adding non-static properties or methods to the $backcompat arrays will
+ * produce runtime errors. It is the responsibility of the developer to make
+ * sure not to do this.
*/
public static function exportStatic(): void
{
// Do nothing if backward compatibility has been turned off.
- if (empty(\SMF\Config::$backward_compatibility))
+ if (empty(\SMF\Config::$backward_compatibility)) {
return;
+ }
- $reflector = new \ReflectionClass(__CLASS__);
+ if (!isset(self::$backcompat)) {
+ return;
+ }
// Get any backward compatibility settings.
- $backcompat = $reflector->getStaticPropertyValue('backcompat', array());
-
- $backcompat['func_underscores'] = !empty($backcompat['func_underscores']);
- $backcompat['func_prefix'] = $backcompat['func_prefix'] ?? '';
- $backcompat['func_names'] = $backcompat['func_names'] ?? array();
- $backcompat['prop_names'] = $backcompat['prop_names'] ?? array();
+ self::$backcompat['func_names'] = self::$backcompat['func_names'] ?? [];
+ self::$backcompat['prop_names'] = self::$backcompat['prop_names'] ?? [];
// The property names are simple enough to deal with...
- foreach ($backcompat['prop_names'] as $static => $global)
+ foreach (self::$backcompat['prop_names'] as $static => $global) {
$GLOBALS[$global] = &self::${$static};
-
- // Get the public static functions.
- $static_methods = array_intersect($reflector->getMethods(\ReflectionMethod::IS_STATIC), $reflector->getMethods(\ReflectionMethod::IS_PUBLIC));
-
- // Filter out the parent class's public static functions.
- if (is_object($parent_reflector = $reflector->getParentClass()))
- {
- $static_methods = array_map('json_decode', array_diff(array_map(__CLASS__ . '::methodAsJson', $static_methods), array_map(__CLASS__ . '::methodAsJson', array_intersect($parent_reflector->getMethods(\ReflectionMethod::IS_STATIC), $parent_reflector->getMethods(\ReflectionMethod::IS_PUBLIC)))));
}
- foreach ($static_methods as $method)
- {
- $method = (array) $method;
-
- // Skip the static methods supplied by this trait.
- if (method_exists(__TRAIT__, $method['name']))
- continue;
-
+ // The method names are slightly more complicated...
+ foreach (self::$backcompat['func_names'] as $method => $func) {
// If the name is manually set to false (or anything invalid), skip this method.
- if (isset($backcompat['func_names'][$method['name']]) && !is_string($backcompat['func_names'][$method['name']]))
- {
+ if (!is_string($func)) {
continue;
}
- // What global function name shall we use for this method?
- $func = $backcompat['func_underscores'] ? self::toUnderscores($method['name']) : $method['name'];
-
- // Allow overriding the function name.
- if (isset($backcompat['func_names'][$method['name']]))
- {
- $func = $backcompat['func_names'][$method['name']];
- }
- // Allow manually specified prefixes.
- elseif ($backcompat['func_prefix'] !== true)
- {
- if ($backcompat['func_underscores'] && substr($backcompat['func_prefix'], -1) !== '_')
- {
- $backcompat['func_prefix'] .= '_';
- }
-
- $func = strtolower($backcompat['func_prefix'] . $func);
- }
- // Avoid name conflicts with existing functions.
- else
- {
- if ($backcompat['func_underscores'])
- {
- $full_prefix = strtolower(strtr($method['class'], '\\', '_')) . '_';
- }
- else
- {
- $full_prefix = str_replace(' ', '', ucwords(strtr($method['class'], '\\', ' ')));
- }
-
- $i = 0;
- $prefix = '';
- $class_parts = explode('\\', $method['class']);
- while ($backcompat['func_prefix'] === true || function_exists($prefix . $func))
- {
- $prefix = array_slice($class_parts, $i--);
-
- if ($backcompat['func_underscores'])
- {
- $prefix = strtolower(implode('_', $prefix)) . '_';
- }
- else
- {
- $prefix = str_replace(' ', '', ucwords(implode(' ', $prefix)));
- }
-
- if ($prefix === $full_prefix || $i < -count($class_parts))
- break;
- }
-
- $func = strtolower($prefix . $func);
- }
-
// If function already exists, die violently.
- if (function_exists($func))
- throw new \Exception("Function $func already exists", 1);
+ if (function_exists($func)) {
+ throw new \Exception("Function {$func} already exists", 1);
+ }
// Here's where the magic happens.
- eval('function ' . $func . '(...$args) { return ' . $method['class'] . '::' . $method['name'] . '(...$args); }');
+ eval('function ' . $func . '(...$args) { return ' . __CLASS__ . '::' . $method . '(...$args); }');
}
}
-
- /**
- * Converts a camelCase string to an underscore separated string.
- * For example, this converts "fooBarBaz" to "foo_bar_baz".
- *
- * @param string $string A (possibly) camelCase string.
- * @return string An underscore separated string.
- */
- public static function toUnderscores(string $string): string
- {
- return strtolower(preg_replace('/(?<=\P{Lu})\p{Lu}/', '_$0', $string));
- }
-
- /**
- * Converts an underscore separated string to a camelCase string.
- * For example, this converts "foo_bar_baz" to "fooBarBaz".
- *
- * @param string $string A (possibly) underscore separated string.
- * @return string A camelCase string.
- */
- public static function toCamelCase(string $string): string
- {
- return preg_replace_callback(
- '/_(\p{L})/',
- function ($matches)
- {
- return strtoupper($matches[1]);
- },
- strtolower($string)
- );
- }
-
- /**
- * Small callback function used by exportStatic(). Pay this no mind.
- *
- * @param object $method A \ReflectorMethod object.
- * @return string A JSON string.
- */
- private static function methodAsJson(object $method): string
- {
- return json_encode((array) $method);
- }
}
?>
\ No newline at end of file
diff --git a/Sources/Board.php b/Sources/Board.php
index 41c23f02ad..de88872c60 100644
--- a/Sources/Board.php
+++ b/Sources/Board.php
@@ -29,34 +29,37 @@
*/
class Board implements \ArrayAccess
{
- use BackwardCompatibility, ArrayAccessHelper;
+ use BackwardCompatibility;
+ use ArrayAccessHelper;
/**
* @var array
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
+ private static $backcompat = [
+ 'func_names' => [
'load' => 'loadBoard',
- 'init' => false,
- 'sort' => 'sortBoards',
+ 'markRead' => 'MarkRead',
+ 'markBoardsRead' => 'markBoardsRead',
+ 'getMsgMemberID' => 'getMsgMemberID',
'modify' => 'modifyBoard',
'create' => 'createBoard',
'delete' => 'deleteBoards',
'reorder' => 'reorderBoards',
- 'getParents' => 'getBoardParents',
+ 'fixChildren' => 'fixChildren',
+ 'sort' => 'sortBoards',
'getModerators' => 'getBoardModerators',
'getModeratorGroups' => 'getBoardModeratorGroups',
- 'setParsedDescriptions' => 'setBoardParsedDescription',
- 'getParsedDescriptions' => 'getBoardsParsedDescription',
- ),
- 'prop_names' => array(
+ 'isChildOf' => 'isChildOf',
+ 'getParents' => 'getBoardParents',
+ ],
+ 'prop_names' => [
'board_id' => 'board',
'info' => 'board_info',
'loaded' => 'boards',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -96,28 +99,28 @@ class Board implements \ArrayAccess
*
* Info about individual members allowed to moderate this board.
*/
- public array $moderators = array();
+ public array $moderators = [];
/**
* @var array
*
* Info about member groups allowed to moderate this board.
*/
- public array $moderator_groups = array();
+ public array $moderator_groups = [];
/**
* @var array
*
* Info about member groups allowed to access this board.
*/
- public array $member_groups = array();
+ public array $member_groups = [];
/**
* @var array
*
* Info about member groups forbidden from accessing this board.
*/
- public array $deny_groups = array();
+ public array $deny_groups = [];
/**
* @var int
@@ -160,7 +163,7 @@ class Board implements \ArrayAccess
*
* All of this board's ancestor boards.
*/
- public array $parent_boards = array();
+ public array $parent_boards = [];
/**
* @var int
@@ -195,7 +198,7 @@ class Board implements \ArrayAccess
*
* Boards that are children of this board.
*/
- public array $children = array();
+ public array $children = [];
/**
* @var int
@@ -272,21 +275,21 @@ class Board implements \ArrayAccess
*
* HTML anchor links for this board's children.
*/
- public array $link_children = array();
+ public array $link_children = [];
/**
* @var array
*
* HTML anchor links for this board's moderators.
*/
- public array $link_moderators = array();
+ public array $link_moderators = [];
/**
* @var array
*
* HTML anchor links for this board's moderator groups.
*/
- public array $link_moderator_groups = array();
+ public array $link_moderator_groups = [];
/**
* @var int
@@ -308,7 +311,7 @@ class Board implements \ArrayAccess
*
* Info about the latest post in this board.
*/
- public array $last_post = array();
+ public array $last_post = [];
/**
* @var bool
@@ -351,7 +354,7 @@ class Board implements \ArrayAccess
*
* All loaded instances of this class.
*/
- public static array $loaded = array();
+ public static array $loaded = [];
/*********************
* Internal properties
@@ -365,7 +368,7 @@ class Board implements \ArrayAccess
* means any groups that have the manage_boards permission that aren't
* in the board's list of allowed groups.
*/
- protected array $overridden_access_groups = array();
+ protected array $overridden_access_groups = [];
/**
* @var array
@@ -375,14 +378,14 @@ class Board implements \ArrayAccess
* groups that have the manage_boards permission that are in the board's
* list of denied groups.
*/
- protected array $overridden_deny_groups = array();
+ protected array $overridden_deny_groups = [];
/**
* @var array
*
* Alternate names for some object properties.
*/
- protected array $prop_aliases = array(
+ protected array $prop_aliases = [
'id_board' => 'id',
'board_name' => 'name',
'board_description' => 'description',
@@ -408,7 +411,7 @@ class Board implements \ArrayAccess
// Initial exclamation mark means inverse of the property.
'is_read' => '!new',
- );
+ ];
/****************************
* Internal static properties
@@ -419,9 +422,9 @@ class Board implements \ArrayAccess
*
* Properties that should be cached in different situations.
*/
- protected static array $cache_props = array(
+ protected static array $cache_props = [
// When caching Board::$info
- 'info' => array(
+ 'info' => [
'id',
'cat',
'name',
@@ -447,15 +450,15 @@ class Board implements \ArrayAccess
'count_posts',
'cur_topic_approved',
'cur_topic_starter',
- ),
- );
+ ],
+ ];
/**
* @var array
*
* Holds parsed versions of board descriptions.
*/
- protected static array $parsed_descriptions = array();
+ protected static array $parsed_descriptions = [];
/****************
* Public methods
@@ -469,39 +472,35 @@ class Board implements \ArrayAccess
*/
public function __set(string $prop, $value): void
{
- if (in_array($this->prop_aliases[$prop] ?? $prop, array('member_groups', 'deny_groups')))
- {
- if (!is_array($value))
+ if (in_array($this->prop_aliases[$prop] ?? $prop, ['member_groups', 'deny_groups'])) {
+ if (!is_array($value)) {
$value = explode(',', $value);
+ }
$value = array_map('intval', array_filter($value, 'strlen'));
// Special handling for access for board manager groups.
- if (!empty(Config::$modSettings['board_manager_groups']) && in_array($this->prop_aliases[$prop] ?? $prop, array('member_groups', 'deny_groups')) && is_array($value))
- {
+ if (!empty(Config::$modSettings['board_manager_groups']) && in_array($this->prop_aliases[$prop] ?? $prop, ['member_groups', 'deny_groups']) && is_array($value)) {
$board_manager_groups = array_map('intval', array_filter(explode(',', Config::$modSettings['board_manager_groups']), 'strlen'));
- if (($this->prop_aliases[$prop] ?? $prop) === 'deny_groups')
- {
+ if (($this->prop_aliases[$prop] ?? $prop) === 'deny_groups') {
$this->overridden_deny_groups = array_intersect($board_manager_groups, $value);
$value = array_diff($value, $board_manager_groups);
- }
- else
- {
+ } else {
$this->overridden_access_groups = array_diff($board_manager_groups, $value);
$value = array_merge($board_manager_groups, $value);
}
}
- $value = array_unique(array_diff($value, array(1)));
+ $value = array_unique(array_diff($value, [1]));
sort($value);
}
// Special handling for the category.
- if (($this->prop_aliases[$prop] ?? null) === 'cat[id]')
- {
+ if (($this->prop_aliases[$prop] ?? null) === 'cat[id]') {
$this->cat = Category::init($value);
+
return;
}
@@ -513,21 +512,20 @@ public function __set(string $prop, $value): void
*
* @param array $boardOptions An array of options related to the board.
*/
- public function save(array $boardOptions = array()): void
+ public function save(array $boardOptions = []): void
{
User::$me->isAllowedTo('manage_boards');
// Undo any overrides of the group access values.
- $access_groups = array_unique(array_diff($this->member_groups, $this->overridden_access_groups, array(1)));
- $deny_groups = array_unique(array_diff(array_merge($this->deny_groups, $this->overridden_deny_groups), array(1)));
+ $access_groups = array_unique(array_diff($this->member_groups, $this->overridden_access_groups, [1]));
+ $deny_groups = array_unique(array_diff(array_merge($this->deny_groups, $this->overridden_deny_groups), [1]));
sort($access_groups);
sort($deny_groups);
// Saving a new board.
- if (empty($this->id))
- {
- $columns = array(
+ if (empty($this->id)) {
+ $columns = [
'id_cat' => 'int',
'child_level' => 'int',
'id_parent' => 'int',
@@ -547,9 +545,9 @@ public function save(array $boardOptions = array()): void
'unapproved_topics' => 'int',
'redirect' => 'string-255',
'deny_member_groups' => 'string-255',
- );
+ ];
- $params = array(
+ $params = [
$this->cat['id'],
$this->child_level,
$this->parent,
@@ -569,22 +567,22 @@ public function save(array $boardOptions = array()): void
$this->unapproved_topics,
$this->redirect,
implode(',', $deny_groups),
- );
+ ];
- $this->id = Db::$db->insert('',
+ $this->id = Db::$db->insert(
+ '',
'{db_prefix}boards',
$columns,
$params,
- array('id_board'),
- 1
+ ['id_board'],
+ 1,
);
self::$loaded[$this->id] = $this;
}
// Updating an existing board.
- else
- {
- $set = array(
+ else {
+ $set = [
'id_cat = {int:id_cat}',
'child_level = {int:child_level}',
'id_parent = {int:id_parent}',
@@ -604,9 +602,9 @@ public function save(array $boardOptions = array()): void
'unapproved_topics = {int:unapproved_topics}',
'redirect = {string:redirect}',
'deny_member_groups = {string:deny_groups}',
- );
+ ];
- $params = array(
+ $params = [
'id' => $this->id,
'id_cat' => $this->cat['id'],
'child_level' => $this->child_level,
@@ -627,90 +625,97 @@ public function save(array $boardOptions = array()): void
'unapproved_topics' => $this->unapproved_topics,
'redirect' => $this->redirect,
'deny_groups' => implode(',', $deny_groups),
- );
+ ];
// Do any hooks want to add or adjust anything?
- IntegrationHook::call('integrate_modify_board', array($this->id, $boardOptions, &$set, &$params));
+ IntegrationHook::call('integrate_modify_board', [$this->id, $boardOptions, &$set, &$params]);
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET ' . (implode(', ', $set)) . '
WHERE id_board = {int:id}',
- $params
+ $params,
);
}
// Before we add new access_groups or deny_groups, remove all of the old entries.
- Db::$db->query('', '
- DELETE FROM {db_prefix}board_permissions_view
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}board_permissions_view
WHERE id_board = {int:this_board}',
- array(
+ [
'this_board' => $this->id,
- )
+ ],
);
- $inserts = array();
+ $inserts = [];
- foreach ($access_groups as $id_group)
- $inserts[] = array($id_group, $this->id, 0);
+ foreach ($access_groups as $id_group) {
+ $inserts[] = [$id_group, $this->id, 0];
+ }
- foreach ($deny_groups as $id_group)
- $inserts[] = array($id_group, $this->id, 1);
+ foreach ($deny_groups as $id_group) {
+ $inserts[] = [$id_group, $this->id, 1];
+ }
- if ($inserts != array())
- {
- Db::$db->insert('insert',
+ if ($inserts != []) {
+ Db::$db->insert(
+ 'insert',
'{db_prefix}board_permissions_view',
- array('id_group' => 'int', 'id_board' => 'int', 'deny' => 'int'),
+ ['id_group' => 'int', 'id_board' => 'int', 'deny' => 'int'],
$inserts,
- array('id_group', 'id_board', 'deny')
+ ['id_group', 'id_board', 'deny'],
);
}
// Reset current moderators for this board - if there are any!
- Db::$db->query('', '
- DELETE FROM {db_prefix}moderators
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}moderators
WHERE id_board = {int:this_board}',
- array(
+ [
'this_board' => $this->id,
- )
+ ],
);
- if (!empty($this->moderators))
- {
- Db::$db->insert('insert',
+ if (!empty($this->moderators)) {
+ Db::$db->insert(
+ 'insert',
'{db_prefix}moderators',
- array('id_board' => 'int', 'id_member' => 'int'),
- array_map(fn($mod) => array($this->id, $mod['id']), $this->moderators),
- array('id_board', 'id_member')
+ ['id_board' => 'int', 'id_member' => 'int'],
+ array_map(fn ($mod) => [$this->id, $mod['id']], $this->moderators),
+ ['id_board', 'id_member'],
);
}
// Reset current moderator groups for this board - if there are any!
- Db::$db->query('', '
- DELETE FROM {db_prefix}moderator_groups
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}moderator_groups
WHERE id_board = {int:this_board}',
- array(
+ [
'this_board' => $this->id,
- )
+ ],
);
- if (!empty($this->moderator_groups))
- {
- Db::$db->insert('insert',
+ if (!empty($this->moderator_groups)) {
+ Db::$db->insert(
+ 'insert',
'{db_prefix}moderator_groups',
- array('id_board' => 'int', 'id_group' => 'int'),
- array_map(fn($mod) => array($this->id, $mod['id']), $this->moderator_groups),
- array('id_board', 'id_group')
+ ['id_board' => 'int', 'id_group' => 'int'],
+ array_map(fn ($mod) => [$this->id, $mod['id']], $this->moderator_groups),
+ ['id_board', 'id_group'],
);
}
// If we were moving boards, ensure that the order is correct.
- if (isset($boardOptions['move_to']))
+ if (isset($boardOptions['move_to'])) {
self::reorder();
+ }
// The caches might now be wrong.
- Config::updateModSettings(array('settings_updated' => time()));
+ Config::updateModSettings(['settings_updated' => time()]);
CacheApi::clean('data');
}
@@ -736,24 +741,20 @@ public function move(
?int $target_category = null,
?int $target_board = null,
bool $first_child = false,
- bool $save = true
- ): array
- {
+ bool $save = true,
+ ): array {
// Do we have what we need?
- switch ($move_to)
- {
+ switch ($move_to) {
case 'top':
case 'bottom':
- if (!isset($target_category))
- {
+ if (!isset($target_category)) {
Lang::load('Errors');
trigger_error(sprintf(Lang::$txt['modify_board_incorrect_move_to'], $move_to), E_USER_ERROR);
}
break;
default:
- if (!isset($target_board))
- {
+ if (!isset($target_board)) {
Lang::load('Errors');
trigger_error(sprintf(Lang::$txt['modify_board_incorrect_move_to'], $move_to), E_USER_ERROR);
}
@@ -761,17 +762,15 @@ public function move(
}
// IDs of all boards that were affected by this move.
- $affected_boards = array($this->id);
+ $affected_boards = [$this->id];
// Ensure everything is loaded.
- if ((isset($target_category) && !isset(Category::$loaded[$target_category])) || (isset($target_board) && !isset(self::$loaded[$target_board])))
- {
+ if ((isset($target_category) && !isset(Category::$loaded[$target_category])) || (isset($target_board) && !isset(self::$loaded[$target_board]))) {
Category::getTree();
}
// Where are we moving this board to?
- switch ($move_to)
- {
+ switch ($move_to) {
case 'top':
$id_cat = $target_category;
$child_level = 0;
@@ -785,8 +784,9 @@ public function move(
$id_parent = 0;
$after = 0;
- foreach (Category::$loaded[$id_cat]->children as $id_board => $dummy)
+ foreach (Category::$loaded[$id_cat]->children as $id_board => $dummy) {
$after = max($after, self::$loaded[$id_board]->order);
+ }
break;
@@ -796,22 +796,19 @@ public function move(
$id_parent = $target_board;
// People can be creative, in many ways...
- if (self::isChildOf($id_parent, $this->id))
- {
+ if (self::isChildOf($id_parent, $this->id)) {
ErrorHandler::fatalLang('mboards_parent_own_child_error', false);
- }
- elseif ($id_parent == $this->id)
- {
+ } elseif ($id_parent == $this->id) {
ErrorHandler::fatalLang('mboards_board_own_child_error', false);
}
$after = self::$loaded[$target_board]->order;
// Check if there are already children and (if so) get the max board order.
- if (!empty(self::$loaded[$id_parent]->children) && empty($first_child))
- {
- foreach (self::$loaded[$id_parent]->children as $childBoard_id => $dummy)
+ if (!empty(self::$loaded[$id_parent]->children) && empty($first_child)) {
+ foreach (self::$loaded[$id_parent]->children as $childBoard_id => $dummy) {
$after = max($after, self::$loaded[$childBoard_id]->order);
+ }
}
break;
@@ -831,32 +828,30 @@ public function move(
}
// Get a list of children of this board.
- $child_list = array();
+ $child_list = [];
Category::recursiveBoards($child_list, $this);
// See if there are changes that affect children.
- foreach ($child_list as $child_id)
- {
- if ($child_level != $this->child_level)
- {
+ foreach ($child_list as $child_id) {
+ if ($child_level != $this->child_level) {
self::$loaded[$child_id]->child_level += ($child_level - $this->child_level);
$affected_boards[] = $child_id;
}
- if ($id_cat != self::$loaded[$child_id]->category)
- {
+ if ($id_cat != self::$loaded[$child_id]->category) {
self::$loaded[$child_id]->category = $id_cat;
$affected_boards[] = $child_id;
}
}
- foreach (self::$loaded as $board)
- {
- if ($board->order <= $after)
+ foreach (self::$loaded as $board) {
+ if ($board->order <= $after) {
continue;
+ }
- if ($board->id === $this->id)
+ if ($board->id === $this->id) {
continue;
+ }
$board->order += (1 + count($child_list));
$affected_boards[] = $board->id;
@@ -869,10 +864,10 @@ public function move(
$this->order = $after + 1;
// Are we saving the changes?
- if ($save)
- {
- foreach ($affected_boards as $board_id)
+ if ($save) {
+ foreach ($affected_boards as $board_id) {
self::$loaded[$board_id]->save();
+ }
}
return $affected_boards;
@@ -883,29 +878,28 @@ public function move(
*/
public function parseDescription(): void
{
- if (empty($this->description))
+ if (empty($this->description)) {
return;
+ }
// Save the unparsed description in case we need it later.
- if (!isset($this->custom['unparsed_description']))
+ if (!isset($this->custom['unparsed_description'])) {
$this->custom['unparsed_description'] = $this->description;
+ }
- if (!empty(CacheApi::$enable))
- {
- if (empty(self::$parsed_descriptions))
- self::$parsed_descriptions = CacheApi::get('parsed_boards_descriptions', 864000) ?? array();
+ if (!empty(CacheApi::$enable)) {
+ if (empty(self::$parsed_descriptions)) {
+ self::$parsed_descriptions = CacheApi::get('parsed_boards_descriptions', 864000) ?? [];
+ }
- if (!isset(self::$parsed_descriptions[$this->id]))
- {
+ if (!isset(self::$parsed_descriptions[$this->id])) {
self::$parsed_descriptions[$this->id] = BBCodeParser::load()->parse($this->description, false, '', Utils::$context['description_allowed_tags']);
CacheApi::put('parsed_boards_descriptions', self::$parsed_descriptions, 864000);
}
$this->description = self::$parsed_descriptions[$this->id];
- }
- else
- {
+ } else {
$this->description = BBCodeParser::load()->parse($this->description, false, '', Utils::$context['description_allowed_tags']);
}
}
@@ -915,8 +909,9 @@ public function parseDescription(): void
*/
public function unparseDescription(): void
{
- if (isset($this->custom['unparsed_description']))
+ if (isset($this->custom['unparsed_description'])) {
$this->description = $this->custom['unparsed_description'];
+ }
}
/***********************
@@ -932,52 +927,44 @@ public function unparseDescription(): void
* @param array $query_customizations Customizations to the SQL query.
* @return array Instances of this class for the loaded boards.
*/
- public static function load(array|int $ids = array(), array $query_customizations = array()): array
+ public static function load(array|int $ids = [], array $query_customizations = []): array
{
- $loaded = array();
+ $loaded = [];
$ids = array_unique(array_map('intval', (array) $ids));
- if (empty($query_customizations))
- {
- if (empty($ids))
- {
+ if (empty($query_customizations)) {
+ if (empty($ids)) {
$loaded[] = self::init();
- }
- else
- {
- foreach ($ids as $id)
+ } else {
+ foreach ($ids as $id) {
$loaded[] = self::init($id);
+ }
}
return $loaded;
}
- $selects = $query_customizations['selects'] ?? array('b.*');
- $joins = $query_customizations['joins'] ?? array();
- $where = $query_customizations['where'] ?? array();
- $order = $query_customizations['order'] ?? array();
- $group = $query_customizations['group'] ?? array();
+ $selects = $query_customizations['selects'] ?? ['b.*'];
+ $joins = $query_customizations['joins'] ?? [];
+ $where = $query_customizations['where'] ?? [];
+ $order = $query_customizations['order'] ?? [];
+ $group = $query_customizations['group'] ?? [];
$limit = $query_customizations['limit'] ?? 0;
- $params = $query_customizations['params'] ?? array();
+ $params = $query_customizations['params'] ?? [];
- if ($ids !== array())
- {
+ if ($ids !== []) {
$where[] = 'b.id_board IN ({array_int:ids})';
$params['ids'] = $ids;
}
- foreach (self::queryData($selects, $params, $joins, $where, $order, $group, $limit) as $row)
- {
+ foreach (self::queryData($selects, $params, $joins, $where, $order, $group, $limit) as $row) {
$row['id_board'] = (int) $row['id_board'];
- if (isset(self::$loaded[$row['id_board']]))
- {
+ if (isset(self::$loaded[$row['id_board']])) {
self::$loaded[$row['id_board']]->set($row);
$loaded[] = self::$loaded[$row['id_board']];
- }
- else
- {
+ } else {
$loaded[] = self::init($row['id_board'], $row);
}
}
@@ -1008,18 +995,16 @@ public static function load(array|int $ids = array(), array $query_customization
* is not null.
* @return object|null An instance of this class, or null on error.
*/
- public static function init(?int $id = null, array $props = array()): object|null
+ public static function init(?int $id = null, array $props = []): ?object
{
// This should already have been set, but just in case...
- if (!isset(self::$board_id))
+ if (!isset(self::$board_id)) {
self::$board_id = (int) ($_REQUEST['board'] ?? 0);
+ }
- if (!isset(self::$loaded[$id]))
- {
+ if (!isset(self::$loaded[$id])) {
new self($id, $props);
- }
- else
- {
+ } else {
self::$loaded[$id]->set($props);
}
@@ -1036,146 +1021,142 @@ public static function markRead(): void
User::$me->checkSession('get');
- if (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'all')
- {
+ if (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'all') {
// Find all the boards this user can see.
- $boards = array();
+ $boards = [];
- $result = Db::$db->query('', '
- SELECT b.id_board
+ $result = Db::$db->query(
+ '',
+ 'SELECT b.id_board
FROM {db_prefix}boards AS b
WHERE {query_see_board}',
- array(
- )
+ [
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$boards[] = $row['id_board'];
}
Db::$db->free_result($result);
- if (!empty($boards))
+ if (!empty($boards)) {
self::markBoardsRead($boards, isset($_REQUEST['unread']));
+ }
$_SESSION['id_msg_last_visit'] = Config::$modSettings['maxMsgID'];
- if (!empty($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'action=unread') !== false)
- {
+ if (!empty($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'action=unread') !== false) {
Utils::redirectexit('action=unread');
}
- if (isset($_SESSION['topicseen_cache']))
- $_SESSION['topicseen_cache'] = array();
+ if (isset($_SESSION['topicseen_cache'])) {
+ $_SESSION['topicseen_cache'] = [];
+ }
Utils::redirectexit();
- }
- elseif (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'unreadreplies')
- {
+ } elseif (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'unreadreplies') {
// Make sure all the topics are integers!
$topics = array_map('intval', explode('-', $_REQUEST['topics']));
- $logged_topics = array();
+ $logged_topics = [];
- $request = Db::$db->query('', '
- SELECT id_topic, unwatched
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic, unwatched
FROM {db_prefix}log_topics
WHERE id_topic IN ({array_int:selected_topics})
AND id_member = {int:current_user}',
- array(
+ [
'selected_topics' => $topics,
'current_user' => User::$me->id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$logged_topics[$row['id_topic']] = $row['unwatched'];
}
Db::$db->free_result($request);
- $markRead = array();
+ $markRead = [];
- foreach ($topics as $id_topic)
- {
- $markRead[] = array(Config::$modSettings['maxMsgID'], User::$me->id, $id_topic, (isset($logged_topics[Topic::$topic_id]) ? $logged_topics[Topic::$topic_id] : 0));
+ foreach ($topics as $id_topic) {
+ $markRead[] = [Config::$modSettings['maxMsgID'], User::$me->id, $id_topic, ($logged_topics[Topic::$topic_id] ?? 0)];
}
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_topics',
- array('id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int', 'unwatched' => 'int'),
+ ['id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int', 'unwatched' => 'int'],
$markRead,
- array('id_member', 'id_topic')
+ ['id_member', 'id_topic'],
);
- if (isset($_SESSION['topicseen_cache']))
- $_SESSION['topicseen_cache'] = array();
+ if (isset($_SESSION['topicseen_cache'])) {
+ $_SESSION['topicseen_cache'] = [];
+ }
Utils::redirectexit('action=unreadreplies');
}
// Special case: mark a topic unread!
- elseif (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'topic')
- {
+ elseif (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'topic') {
// First, let's figure out what the latest message is.
- $result = Db::$db->query('', '
- SELECT t.id_first_msg, t.id_last_msg, COALESCE(lt.unwatched, 0) as unwatched
+ $result = Db::$db->query(
+ '',
+ 'SELECT t.id_first_msg, t.id_last_msg, COALESCE(lt.unwatched, 0) as unwatched
FROM {db_prefix}topics as t
LEFT JOIN {db_prefix}log_topics as lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
WHERE t.id_topic = {int:current_topic}',
- array(
+ [
'current_topic' => Topic::$topic_id,
'current_member' => User::$me->id,
- )
+ ],
);
$topicinfo = Db::$db->fetch_assoc($result);
Db::$db->free_result($result);
- if (!empty($_GET['t']))
- {
+ if (!empty($_GET['t'])) {
// If they read the whole topic, go back to the beginning.
- if ($_GET['t'] >= $topicinfo['id_last_msg'])
- {
+ if ($_GET['t'] >= $topicinfo['id_last_msg']) {
$earlyMsg = 0;
}
// If they want to mark the whole thing read, same.
- elseif ($_GET['t'] <= $topicinfo['id_first_msg'])
- {
+ elseif ($_GET['t'] <= $topicinfo['id_first_msg']) {
$earlyMsg = 0;
}
// Otherwise, get the latest message before the named one.
- else
- {
- $result = Db::$db->query('', '
- SELECT MAX(id_msg)
+ else {
+ $result = Db::$db->query(
+ '',
+ 'SELECT MAX(id_msg)
FROM {db_prefix}messages
WHERE id_topic = {int:current_topic}
AND id_msg >= {int:id_first_msg}
AND id_msg < {int:topic_msg_id}',
- array(
+ [
'current_topic' => Topic::$topic_id,
'topic_msg_id' => (int) $_GET['t'],
'id_first_msg' => $topicinfo['id_first_msg'],
- )
+ ],
);
list($earlyMsg) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
}
}
// Marking read from first page? That's the whole topic.
- elseif ($_REQUEST['start'] == 0)
- {
+ elseif ($_REQUEST['start'] == 0) {
$earlyMsg = 0;
- }
- else
- {
- $result = Db::$db->query('', '
- SELECT id_msg
+ } else {
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_msg
FROM {db_prefix}messages
WHERE id_topic = {int:current_topic}
ORDER BY id_msg
LIMIT {int:start}, 1',
- array(
+ [
'current_topic' => Topic::$topic_id,
'start' => (int) $_REQUEST['start'],
- )
+ ],
);
list($earlyMsg) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
@@ -1184,155 +1165,149 @@ public static function markRead(): void
}
// Blam, unread!
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_topics',
- array('id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int', 'unwatched' => 'int'),
- array($earlyMsg, User::$me->id, Topic::$topic_id, $topicinfo['unwatched']),
- array('id_member', 'id_topic')
+ ['id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int', 'unwatched' => 'int'],
+ [$earlyMsg, User::$me->id, Topic::$topic_id, $topicinfo['unwatched']],
+ ['id_member', 'id_topic'],
);
Utils::redirectexit('board=' . self::$info->id . '.0');
- }
- else
- {
- $categories = array();
- $boards = array();
+ } else {
+ $categories = [];
+ $boards = [];
- if (isset($_REQUEST['c']))
- {
+ if (isset($_REQUEST['c'])) {
$_REQUEST['c'] = explode(',', $_REQUEST['c']);
- foreach ($_REQUEST['c'] as $c)
+ foreach ($_REQUEST['c'] as $c) {
$categories[] = (int) $c;
+ }
}
- if (isset($_REQUEST['boards']))
- {
+ if (isset($_REQUEST['boards'])) {
$_REQUEST['boards'] = explode(',', $_REQUEST['boards']);
- foreach ($_REQUEST['boards'] as $b)
+ foreach ($_REQUEST['boards'] as $b) {
$boards[] = (int) $b;
+ }
}
- if (!empty(self::$info->id))
+ if (!empty(self::$info->id)) {
$boards[] = (int) self::$info->id;
+ }
- if (isset($_REQUEST['children']) && !empty($boards))
- {
+ if (isset($_REQUEST['children']) && !empty($boards)) {
// They want to mark the entire tree starting with the boards specified
// The easiest thing is to just get all the boards they can see, but since we've specified the top of tree we ignore some of them
- $request = Db::$db->query('', '
- SELECT b.id_board, b.id_parent
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board, b.id_parent
FROM {db_prefix}boards AS b
WHERE {query_see_board}
AND b.child_level > {int:no_parents}
AND b.id_board NOT IN ({array_int:board_list})
ORDER BY child_level ASC',
- array(
+ [
'no_parents' => 0,
'board_list' => $boards,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (in_array($row['id_parent'], $boards))
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (in_array($row['id_parent'], $boards)) {
$boards[] = $row['id_board'];
+ }
}
Db::$db->free_result($request);
}
- $clauses = array();
- $clauseParameters = array();
+ $clauses = [];
+ $clauseParameters = [];
- if (!empty($categories))
- {
+ if (!empty($categories)) {
$clauses[] = 'id_cat IN ({array_int:category_list})';
$clauseParameters['category_list'] = $categories;
}
- if (!empty($boards))
- {
+ if (!empty($boards)) {
$clauses[] = 'id_board IN ({array_int:board_list})';
$clauseParameters['board_list'] = $boards;
}
- if (empty($clauses))
+ if (empty($clauses)) {
Utils::redirectexit();
+ }
- $boards = array();
+ $boards = [];
- $request = Db::$db->query('', '
- SELECT b.id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board
FROM {db_prefix}boards AS b
WHERE {query_see_board}
AND b.' . implode(' OR b.', $clauses),
- array_merge($clauseParameters, array(
- ))
+ array_merge($clauseParameters, [
+ ]),
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$boards[] = $row['id_board'];
}
Db::$db->free_result($request);
- if (empty($boards))
+ if (empty($boards)) {
Utils::redirectexit();
+ }
self::markBoardsRead($boards, isset($_REQUEST['unread']));
- foreach ($boards as $b)
- {
- if (isset($_SESSION['topicseen_cache'][$b]))
- $_SESSION['topicseen_cache'][$b] = array();
+ foreach ($boards as $b) {
+ if (isset($_SESSION['topicseen_cache'][$b])) {
+ $_SESSION['topicseen_cache'][$b] = [];
+ }
}
- if (!isset($_REQUEST['unread']))
- {
+ if (!isset($_REQUEST['unread'])) {
// Find all the boards this user can see.
- $result = Db::$db->query('', '
- SELECT b.id_board
+ $result = Db::$db->query(
+ '',
+ 'SELECT b.id_board
FROM {db_prefix}boards AS b
WHERE b.id_parent IN ({array_int:parent_list})
AND {query_see_board}',
- array(
+ [
'parent_list' => $boards,
- )
+ ],
);
- if (Db::$db->num_rows($result) > 0)
- {
- $logBoardInserts = array();
- while ($row = Db::$db->fetch_assoc($result))
- {
- $logBoardInserts[] = array(Config::$modSettings['maxMsgID'], User::$me->id, $row['id_board']);
+ if (Db::$db->num_rows($result) > 0) {
+ $logBoardInserts = [];
+
+ while ($row = Db::$db->fetch_assoc($result)) {
+ $logBoardInserts[] = [Config::$modSettings['maxMsgID'], User::$me->id, $row['id_board']];
}
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_boards',
- array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
+ ['id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'],
$logBoardInserts,
- array('id_member', 'id_board')
+ ['id_member', 'id_board'],
);
}
Db::$db->free_result($result);
- if (empty(self::$info->id))
- {
+ if (empty(self::$info->id)) {
Utils::redirectexit();
- }
- else
- {
+ } else {
Utils::redirectexit('board=' . self::$info->id . '.0');
}
- }
- else
- {
- if (empty(self::$info->parent))
- {
+ } else {
+ if (empty(self::$info->parent)) {
Utils::redirectexit();
- }
- else
- {
+ } else {
Utils::redirectexit('board=' . self::$info->parent . '.0');
}
}
@@ -1348,67 +1323,66 @@ public static function markRead(): void
public static function markBoardsRead(int|array $boards, bool $unread = false): void
{
// Force $boards to be an array.
- if (!is_array($boards))
- {
- $boards = array($boards);
- }
- else
- {
+ if (!is_array($boards)) {
+ $boards = [$boards];
+ } else {
$boards = array_unique($boards);
}
// No boards, nothing to mark as read.
- if (empty($boards))
+ if (empty($boards)) {
return;
+ }
// Allow the user to mark a board as unread.
- if ($unread)
- {
+ if ($unread) {
// Clear out all the places where this lovely info is stored.
// @todo Maybe not log_mark_read?
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_mark_read
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_mark_read
WHERE id_board IN ({array_int:board_list})
AND id_member = {int:current_member}',
- array(
+ [
'current_member' => User::$me->id,
'board_list' => $boards,
- )
+ ],
);
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_boards
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_boards
WHERE id_board IN ({array_int:board_list})
AND id_member = {int:current_member}',
- array(
+ [
'current_member' => User::$me->id,
'board_list' => $boards,
- )
+ ],
);
}
// Otherwise mark the board as read.
- else
- {
- $markRead = array();
+ else {
+ $markRead = [];
- foreach ($boards as $board)
- {
- $markRead[] = array(Config::$modSettings['maxMsgID'], User::$me->id, $board);
+ foreach ($boards as $board) {
+ $markRead[] = [Config::$modSettings['maxMsgID'], User::$me->id, $board];
}
// Update log_mark_read and log_boards.
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_mark_read',
- array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
+ ['id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'],
$markRead,
- array('id_board', 'id_member')
+ ['id_board', 'id_member'],
);
- Db::$db->insert('replace',
+ Db::$db->insert(
+ 'replace',
'{db_prefix}log_boards',
- array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
+ ['id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'],
$markRead,
- array('id_board', 'id_member')
+ ['id_board', 'id_member'],
);
}
@@ -1416,52 +1390,55 @@ public static function markBoardsRead(int|array $boards, bool $unread = false):
// @todo look at this...
// The call to markBoardsRead() in Display() used to be simply
// marking log_boards (the previous query only)
- $result = Db::$db->query('', '
- SELECT MIN(id_topic)
+ $result = Db::$db->query(
+ '',
+ 'SELECT MIN(id_topic)
FROM {db_prefix}log_topics
WHERE id_member = {int:current_member}',
- array(
+ [
'current_member' => User::$me->id,
- )
+ ],
);
list($lowest_topic) = Db::$db->fetch_row($result);
Db::$db->free_result($result);
- if (empty($lowest_topic))
+ if (empty($lowest_topic)) {
return;
+ }
// @todo SLOW This query seems to eat it sometimes.
- $topics = array();
- $result = Db::$db->query('', '
- SELECT lt.id_topic
+ $topics = [];
+ $result = Db::$db->query(
+ '',
+ 'SELECT lt.id_topic
FROM {db_prefix}log_topics AS lt
INNER JOIN {db_prefix}topics AS t /*!40000 USE INDEX (PRIMARY) */ ON (t.id_topic = lt.id_topic
AND t.id_board IN ({array_int:board_list}))
WHERE lt.id_member = {int:current_member}
AND lt.id_topic >= {int:lowest_topic}
AND lt.unwatched != 1',
- array(
+ [
'current_member' => User::$me->id,
'board_list' => $boards,
'lowest_topic' => $lowest_topic,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$topics[] = $row['id_topic'];
}
Db::$db->free_result($result);
- if (!empty($topics))
- {
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_topics
+ if (!empty($topics)) {
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_topics
WHERE id_member = {int:current_member}
AND id_topic IN ({array_int:topic_list})',
- array(
+ [
'current_member' => User::$me->id,
'topic_list' => $topics,
- )
+ ],
);
}
}
@@ -1477,23 +1454,23 @@ public static function markBoardsRead(int|array $boards, bool $unread = false):
public static function getMsgMemberID(int $messageID): int
{
// Find the topic and make sure the member still exists.
- $result = Db::$db->query('', '
- SELECT COALESCE(mem.id_member, 0)
+ $result = Db::$db->query(
+ '',
+ 'SELECT COALESCE(mem.id_member, 0)
FROM {db_prefix}messages AS m
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
WHERE m.id_msg = {int:selected_message}
LIMIT 1',
- array(
+ [
'selected_message' => (int) $messageID,
- )
+ ],
);
- if (Db::$db->num_rows($result) > 0)
- {
+
+ if (Db::$db->num_rows($result) > 0) {
list($memberID) = Db::$db->fetch_row($result);
}
// The message doesn't even exist.
- else
- {
+ else {
$memberID = 0;
}
Db::$db->free_result($result);
@@ -1522,98 +1499,96 @@ public static function modify(int $board_id, array &$boardOptions): void
)
|| (
isset($boardOptions['target_category'])
- && !isset(Category::$loaded[$boardOptions['target_category']]))
- )
- {
+ && !isset(Category::$loaded[$boardOptions['target_category']])
+ )
+ ) {
ErrorHandler::fatalLang('no_board');
}
- IntegrationHook::call('integrate_pre_modify_board', array($board_id, &$boardOptions));
+ IntegrationHook::call('integrate_pre_modify_board', [$board_id, &$boardOptions]);
$board = self::$loaded[$board_id];
// In case the board has to be moved.
- if (isset($boardOptions['move_to']))
- {
+ if (isset($boardOptions['move_to'])) {
$moved_boards = $board->move($boardOptions['move_to'], $boardOptions['target_category'] ?? null, $boardOptions['target_board'] ?? null, !empty($boardOptions['move_first_child']), false);
}
// Set moderators of this board.
- if (isset($boardOptions['moderators']) || isset($boardOptions['moderator_string']) || isset($boardOptions['moderator_groups']) || isset($boardOptions['moderator_group_string']))
- {
+ if (isset($boardOptions['moderators']) || isset($boardOptions['moderator_string']) || isset($boardOptions['moderator_groups']) || isset($boardOptions['moderator_group_string'])) {
// Validate and get the IDs of the new moderators.
// $boardOptions['moderator_string'] is only set if the admin has JavaScript disabled.
- if (isset($boardOptions['moderator_string']) && trim($boardOptions['moderator_string']) != '')
- {
- if (empty($boardOptions['moderators']))
- $boardOptions['moderators'] = array();
+ if (isset($boardOptions['moderator_string']) && trim($boardOptions['moderator_string']) != '') {
+ if (empty($boardOptions['moderators'])) {
+ $boardOptions['moderators'] = [];
+ }
// Divvy out the usernames, remove extra space.
- $moderator_string = strtr(Utils::htmlspecialchars($boardOptions['moderator_string'], ENT_QUOTES), array('"' => '"'));
+ $moderator_string = strtr(Utils::htmlspecialchars($boardOptions['moderator_string'], ENT_QUOTES), ['"' => '"']);
preg_match_all('~"([^"]+)"~', $moderator_string, $matches);
$moderators = array_filter(array_map('trim', array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_string)))), 'strlen');
// Find all the id_member's for the member_name's in the list.
- if (!empty($moderators))
- {
- foreach (User::load($moderators, User::LOAD_BY_NAME, 'minimal') as $moderator)
+ if (!empty($moderators)) {
+ foreach (User::load($moderators, User::LOAD_BY_NAME, 'minimal') as $moderator) {
$boardOptions['moderators'][] = $moderator->id;
+ }
}
}
// Validate and get the IDs of the new moderator groups.
// $boardOptions['moderator_group_string'] is only set if the admin has JavaScript disabled.
- if (isset($boardOptions['moderator_group_string']) && trim($boardOptions['moderator_group_string']) != '')
- {
- if (empty($boardOptions['moderator_groups']))
- $boardOptions['moderator_groups'] = array();
+ if (isset($boardOptions['moderator_group_string']) && trim($boardOptions['moderator_group_string']) != '') {
+ if (empty($boardOptions['moderator_groups'])) {
+ $boardOptions['moderator_groups'] = [];
+ }
// Divvy out the group names, remove extra space.
- $moderator_group_string = strtr(Utils::htmlspecialchars($boardOptions['moderator_group_string'], ENT_QUOTES), array('"' => '"'));
+ $moderator_group_string = strtr(Utils::htmlspecialchars($boardOptions['moderator_group_string'], ENT_QUOTES), ['"' => '"']);
preg_match_all('~"([^"]+)"~', $moderator_group_string, $matches);
$moderator_groups = array_filter(array_map('trim', array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_group_string)))), 'strlen');
- // Find all the id_group's for all the group names in the list
+ // Find all the id_group's for all the group names in the list
// But skip any invalid ones (invisible/post groups/Administrator/Moderator)
- if (!empty($moderator_groups))
- {
- $query_customizations = array(
- 'where' => array(
+ if (!empty($moderator_groups)) {
+ $query_customizations = [
+ 'where' => [
'group_name IN ({array_string:moderator_group_list})',
'hidden = {int:visible}',
'min_posts = {int:negative_one}',
'id_group NOT IN ({array_int:invalid_groups})',
- ),
- 'params' => array(
+ ],
+ 'params' => [
'visible' => Group::VISIBLE,
'negative_one' => -1,
- 'invalid_groups' => array(Group::ADMIN, Group::MOD),
+ 'invalid_groups' => [Group::ADMIN, Group::MOD],
'moderator_group_list' => $moderator_groups,
- ),
+ ],
'limit' => count($moderator_groups),
- );
+ ];
- foreach (Group::load(array(), $query_customizations) as $group)
+ foreach (Group::load([], $query_customizations) as $group) {
$boardOptions['moderator_groups'][] = $group->id;
+ }
}
}
- if (isset($boardOptions['moderators']))
- {
- if (!is_array($boardOptions['moderators']))
+ if (isset($boardOptions['moderators'])) {
+ if (!is_array($boardOptions['moderators'])) {
$boardOptions['moderators'] = array_filter(explode(',', $boardOptions['moderators']), 'strlen');
+ }
$boardOptions['moderators'] = array_unique(array_map('intval', $boardOptions['moderators']));
}
- if (isset($boardOptions['moderator_groups']))
- {
- if (!is_array($boardOptions['moderator_groups']))
+ if (isset($boardOptions['moderator_groups'])) {
+ if (!is_array($boardOptions['moderator_groups'])) {
$boardOptions['moderator_groups'] = array_filter(explode(',', $boardOptions['moderator_groups']), 'strlen');
+ }
$boardOptions['moderator_groups'] = array_unique(array_map('intval', $boardOptions['moderator_groups']));
}
@@ -1643,15 +1618,16 @@ public static function modify(int $board_id, array &$boardOptions): void
$board->save($boardOptions);
// If we moved any boards, save their changes too.
- if (!empty($moved_boards))
- {
- foreach (array_diff($moved_boards, array($board->id)) as $moved)
+ if (!empty($moved_boards)) {
+ foreach (array_diff($moved_boards, [$board->id]) as $moved) {
self::$loaded[$moved]->save();
+ }
}
// Log the changes unless told otherwise.
- if (empty($boardOptions['dont_log']))
- Logging::logAction('edit_board', array('board' => $this->id), 'admin');
+ if (empty($boardOptions['dont_log'])) {
+ Logging::logAction('edit_board', ['board' => $board->id], 'admin');
+ }
}
/**
@@ -1667,65 +1643,63 @@ public static function modify(int $board_id, array &$boardOptions): void
public static function create(array $boardOptions): int
{
// Trigger an error if one of the required values is not set.
- if (!isset($boardOptions['board_name']) || trim($boardOptions['board_name']) == '' || !isset($boardOptions['move_to']) || !isset($boardOptions['target_category']))
- {
+ if (!isset($boardOptions['board_name']) || trim($boardOptions['board_name']) == '' || !isset($boardOptions['move_to']) || !isset($boardOptions['target_category'])) {
Lang::load('Errors');
trigger_error(Lang::$txt['create_board_missing_options'], E_USER_ERROR);
}
- if (in_array($boardOptions['move_to'], array('child', 'before', 'after')) && !isset($boardOptions['target_board']))
- {
+ if (in_array($boardOptions['move_to'], ['child', 'before', 'after']) && !isset($boardOptions['target_board'])) {
Lang::load('Errors');
trigger_error(Lang::$txt['move_board_no_target'], E_USER_ERROR);
}
// Set every optional value to its default value.
- $boardOptions += array(
+ $boardOptions += [
'posts_count' => true,
'override_theme' => false,
'board_theme' => 0,
- 'access_groups' => array(),
+ 'access_groups' => [],
'board_description' => '',
'profile' => 1,
'moderators' => '',
'inherit_permissions' => true,
'dont_log' => true,
- );
+ ];
// This used to be done via a direct query, which is why these look like
// arrays that would be passed to our database API. We keep them this
// way now merely in order to maintain the signature of the hook.
- $board_columns = array(
+ $board_columns = [
'id_cat' => 'int',
'name' => 'string-255',
'description' => 'string',
'board_order' => 'int',
'member_groups' => 'string',
'redirect' => 'string',
- );
+ ];
- $board_parameters = array(
+ $board_parameters = [
$boardOptions['target_category'],
$boardOptions['board_name'],
'',
0,
'',
'',
- );
+ ];
- IntegrationHook::call('integrate_create_board', array(&$boardOptions, &$board_columns, &$board_parameters));
+ IntegrationHook::call('integrate_create_board', [&$boardOptions, &$board_columns, &$board_parameters]);
// Make a new instance and save it.
$board = new self(0, array_combine(array_keys($board_columns), $board_parameters));
$board->save();
// Uh-oh...
- if (empty($board->id))
+ if (empty($board->id)) {
return 0;
+ }
// Do we want the parent permissions to be inherited?
- if ($boardOptions['inherit_permissions'] && !empty($board->parent))
- {
+ if ($boardOptions['inherit_permissions'] && !empty($board->parent)) {
self::load($board->parent);
$boardOptions['profile'] = self::$loaded[$board->parent]->profile;
unset($boardOptions['inherit_permissions']);
@@ -1735,7 +1709,7 @@ public static function create(array $boardOptions): int
self::modify($board->id, $boardOptions);
// Created it.
- Logging::logAction('add_board', array('board' => $board->id), 'admin');
+ Logging::logAction('add_board', ['board' => $board->id], 'admin');
// Here you are, a new board, ready to be spammed.
return $board->id;
@@ -1753,63 +1727,57 @@ public static function create(array $boardOptions): int
* @param array $boards_to_remove The boards to remove
* @param int $moveChildrenTo The ID of the board to move the child boards to (null to remove the child boards, 0 to make them a top-level board)
*/
- public static function delete(array $boards_to_remove, int $moveChildrenTo = null): void
+ public static function delete(array $boards_to_remove, ?int $moveChildrenTo = null): void
{
// No boards to delete? Return!
- if (empty($boards_to_remove))
+ if (empty($boards_to_remove)) {
return;
+ }
Category::getTree();
- IntegrationHook::call('integrate_delete_board', array($boards_to_remove, &$moveChildrenTo));
+ IntegrationHook::call('integrate_delete_board', [$boards_to_remove, &$moveChildrenTo]);
// If $moveChildrenTo is set to null, include the children in the removal.
- if ($moveChildrenTo === null)
- {
+ if ($moveChildrenTo === null) {
// Get a list of the child boards that will also be removed.
- $child_boards_to_remove = array();
+ $child_boards_to_remove = [];
- foreach ($boards_to_remove as $board_to_remove)
- {
+ foreach ($boards_to_remove as $board_to_remove) {
Category::recursiveBoards($child_boards_to_remove, self::$loaded[$board_to_remove]);
}
// Merge the children with their parents.
- if (!empty($child_boards_to_remove))
- {
+ if (!empty($child_boards_to_remove)) {
$boards_to_remove = array_unique(array_merge($boards_to_remove, $child_boards_to_remove));
}
}
// Move the children to a safe home.
- else
- {
- foreach ($boards_to_remove as $id_board)
- {
+ else {
+ foreach ($boards_to_remove as $id_board) {
// @todo Separate category?
- if ($moveChildrenTo === 0)
- {
+ if ($moveChildrenTo === 0) {
self::fixChildren($id_board, 0, 0);
- }
- else
- {
+ } else {
self::fixChildren($id_board, self::$loaded[$moveChildrenTo]->child_level + 1, $moveChildrenTo);
}
}
}
// Delete ALL topics in the selected boards (done first so topics can't be marooned.)
- $topics = array();
+ $topics = [];
- $request = Db::$db->query('', '
- SELECT id_topic
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic
FROM {db_prefix}topics
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$topics[] = $row['id_topic'];
}
Db::$db->free_result($request);
@@ -1817,101 +1785,109 @@ public static function delete(array $boards_to_remove, int $moveChildrenTo = nul
Topic::remove($topics, false);
// Delete the board's logs.
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_mark_read
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_mark_read
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_boards
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_boards
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
- Db::$db->query('', '
- DELETE FROM {db_prefix}log_notify
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}log_notify
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
// Delete this board's moderators.
- Db::$db->query('', '
- DELETE FROM {db_prefix}moderators
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}moderators
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
// Delete this board's moderator groups.
- Db::$db->query('', '
- DELETE FROM {db_prefix}moderator_groups
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}moderator_groups
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
// Delete any extra events in the calendar.
- Db::$db->query('', '
- DELETE FROM {db_prefix}calendar
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}calendar
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
// Delete any message icons that only appear on these boards.
- Db::$db->query('', '
- DELETE FROM {db_prefix}message_icons
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}message_icons
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
// Delete the boards.
- Db::$db->query('', '
- DELETE FROM {db_prefix}boards
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}boards
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
// Delete permissions
- Db::$db->query('', '
- DELETE FROM {db_prefix}board_permissions_view
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}board_permissions_view
WHERE id_board IN ({array_int:boards_to_remove})',
- array(
+ [
'boards_to_remove' => $boards_to_remove,
- )
+ ],
);
// Latest message/topic might not be there anymore.
Logging::updateStats('message');
Logging::updateStats('topic');
- Config::updateModSettings(array(
+ Config::updateModSettings([
'calendar_updated' => time(),
- ));
+ ]);
// Plus reset the cache to stop people getting odd results.
- Config::updateModSettings(array('settings_updated' => time()));
+ Config::updateModSettings(['settings_updated' => time()]);
// Clean the cache as well.
CacheApi::clean('data');
// Let's do some serious logging.
- foreach ($boards_to_remove as $id_board)
- {
- Logging::logAction('delete_board', array('boardname' => self::$loaded[$id_board]->name), 'admin');
+ foreach ($boards_to_remove as $id_board) {
+ Logging::logAction('delete_board', ['boardname' => self::$loaded[$id_board]->name], 'admin');
}
self::reorder();
@@ -1928,20 +1904,18 @@ public static function reorder(): void
// Set the board order for each category.
$board_order = 0;
- foreach (Category::$loaded as $cat_id => $dummy)
- {
- foreach (Category::$boardList[$cat_id] as $board_id)
- {
- if (self::$loaded[$board_id]->order != ++$board_order)
- {
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ foreach (Category::$loaded as $cat_id => $dummy) {
+ foreach (Category::$boardList[$cat_id] as $board_id) {
+ if (self::$loaded[$board_id]->order != ++$board_order) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET board_order = {int:new_order}
WHERE id_board = {int:selected_board}',
- array(
+ [
'new_order' => $board_order,
'selected_board' => $board_id,
- )
+ ],
);
}
}
@@ -1962,37 +1936,40 @@ public static function reorder(): void
public static function fixChildren(int $parent, int $newLevel, int $newParent): void
{
// Grab all children of $parent...
- $children = array();
+ $children = [];
- $result = Db::$db->query('', '
- SELECT id_board
+ $result = Db::$db->query(
+ '',
+ 'SELECT id_board
FROM {db_prefix}boards
WHERE id_parent = {int:parent_board}',
- array(
+ [
'parent_board' => $parent,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($result))
- {
+
+ while ($row = Db::$db->fetch_assoc($result)) {
$children[] = $row['id_board'];
}
Db::$db->free_result($result);
// ...and set it to a new parent and child_level.
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET id_parent = {int:new_parent}, child_level = {int:new_child_level}
WHERE id_parent = {int:parent_board}',
- array(
+ [
'new_parent' => $newParent,
'new_child_level' => $newLevel,
'parent_board' => $parent,
- )
+ ],
);
// Recursively fix the children of the children.
- foreach ($children as $child)
+ foreach ($children as $child) {
self::fixChildren($child, $newLevel + 1, $child);
+ }
}
/**
@@ -2004,18 +1981,17 @@ public static function sort(array &$boards): void
{
$tree = Category::getTreeOrder();
- $ordered = array();
+ $ordered = [];
- foreach ($tree['boards'] as $board)
- {
- if (!empty($boards[$board]))
- {
+ foreach ($tree['boards'] as $board) {
+ if (!empty($boards[$board])) {
$ordered[$board] = $boards[$board];
- if (is_array($ordered[$board]) && !empty($ordered[$board]['children']))
+ if (is_array($ordered[$board]) && !empty($ordered[$board]['children'])) {
self::sort($ordered[$board]['children']);
- elseif (is_object($ordered[$board]) && !empty($ordered[$board]->children))
+ } elseif (is_object($ordered[$board]) && !empty($ordered[$board]->children)) {
Board::sort($ordered[$board]->children);
+ }
}
}
@@ -2030,42 +2006,45 @@ public static function sort(array &$boards): void
*/
public static function getModerators(array $boards): array
{
- if (empty($boards))
- return array();
+ if (empty($boards)) {
+ return [];
+ }
- $moderators = array();
+ $moderators = [];
- $request = Db::$db->query('', '
- SELECT mem.id_member, mem.real_name, mo.id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT mem.id_member, mem.real_name, mo.id_board
FROM {db_prefix}moderators AS mo
INNER JOIN {db_prefix}members AS mem ON (mem.id_member = mo.id_member)
WHERE mo.id_board IN ({array_int:boards})',
- array(
+ [
'boards' => $boards,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$row['id_board'] = (int) $row['id_board'];
$row['id_member'] = (int) $row['id_member'];
- if (empty($moderators[$row['id_board']]))
- $moderators[$row['id_board']] = array();
+ if (empty($moderators[$row['id_board']])) {
+ $moderators[$row['id_board']] = [];
+ }
- $moderators[$row['id_board']][$row['id_member']] = array(
+ $moderators[$row['id_board']][$row['id_member']] = [
'id' => $row['id_member'],
'name' => $row['real_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_member'],
'link' => '' . $row['real_name'] . '',
- );
+ ];
}
Db::$db->free_result($request);
// We might as well update the data in any loaded boards.
- foreach (self::$loaded as $board)
- {
- if (isset($moderators[$board->id]))
+ foreach (self::$loaded as $board) {
+ if (isset($moderators[$board->id])) {
$board->moderators = $moderators[$board->id];
+ }
}
return $moderators;
@@ -2079,41 +2058,44 @@ public static function getModerators(array $boards): array
*/
public static function getModeratorGroups(array $boards): array
{
- if (empty($boards))
- return array();
+ if (empty($boards)) {
+ return [];
+ }
- $groups = array();
+ $groups = [];
- $request = Db::$db->query('', '
- SELECT mg.id_group, mg.group_name, bg.id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT mg.id_group, mg.group_name, bg.id_board
FROM {db_prefix}moderator_groups AS bg
INNER JOIN {db_prefix}membergroups AS mg ON (mg.id_group = bg.id_group)
WHERE bg.id_board IN ({array_int:boards})',
- array(
+ [
'boards' => $boards,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$row['id_board'] = (int) $row['id_board'];
$row['id_group'] = (int) $row['id_group'];
- if (empty($groups[$row['id_board']]))
- $groups[$row['id_board']] = array();
+ if (empty($groups[$row['id_board']])) {
+ $groups[$row['id_board']] = [];
+ }
- $groups[$row['id_board']][$row['id_group']] = array(
+ $groups[$row['id_board']][$row['id_group']] = [
'id' => $row['id_group'],
'name' => $row['group_name'],
'href' => Config::$scripturl . '?action=groups;sa=members;group=' . $row['id_group'],
'link' => '' . $row['group_name'] . '',
- );
+ ];
}
// We might as well update the data in any loaded boards.
- foreach (self::$loaded as $board)
- {
- if (isset($groups[$board->id]))
+ foreach (self::$loaded as $board) {
+ if (isset($groups[$board->id])) {
$board->moderator_groups = $groups[$board->id];
+ }
}
return $groups;
@@ -2129,11 +2111,13 @@ public static function getModeratorGroups(array $boards): array
*/
public static function isChildOf($child, $parent): bool
{
- if (empty(self::$loaded[$child]->parent))
+ if (empty(self::$loaded[$child]->parent)) {
return false;
+ }
- if (self::$loaded[$child]->parent == $parent)
+ if (self::$loaded[$child]->parent == $parent) {
return true;
+ }
return self::isChildOf(self::$loaded[$child]->parent, $parent);
}
@@ -2149,36 +2133,32 @@ public static function isChildOf($child, $parent): bool
public static function getParents(int $id_parent): array
{
// First check if we have this cached already.
- if (($boards = CacheApi::get('board_parents-' . $id_parent, 480)) === null)
- {
- $boards = array();
+ if (($boards = CacheApi::get('board_parents-' . $id_parent, 480)) === null) {
+ $boards = [];
$original_parent = $id_parent;
// Loop while the parent is non-zero.
- while ($id_parent != 0)
- {
- $selects = array(
+ while ($id_parent != 0) {
+ $selects = [
'b.id_parent', 'b.name', 'b.id_board', 'b.child_level',
'b.member_groups', 'b.deny_member_groups',
- );
- $params = array('board_parent' => $id_parent);
- $joins = array();
- $where = array('b.id_board = {int:board_parent}');
- $order = array();
-
- foreach (self::queryData($selects, $params, $joins, $where, $order) as $row)
- {
- if (!isset($boards[$row['id_board']]))
- {
+ ];
+ $params = ['board_parent' => $id_parent];
+ $joins = [];
+ $where = ['b.id_board = {int:board_parent}'];
+ $order = [];
+
+ foreach (self::queryData($selects, $params, $joins, $where, $order) as $row) {
+ if (!isset($boards[$row['id_board']])) {
$id_parent = $row['id_parent'];
- $boards[$row['id_board']] = array(
+ $boards[$row['id_board']] = [
'url' => Config::$scripturl . '?board=' . $row['id_board'] . '.0',
'name' => $row['name'],
'child_level' => $row['child_level'],
'parent' => $row['id_parent'],
'groups' => explode(',', $row['member_groups']),
'deny_groups' => explode(',', $row['deny_member_groups']),
- );
+ ];
}
}
}
@@ -2186,10 +2166,11 @@ public static function getParents(int $id_parent): array
CacheApi::put('board_parents-' . $original_parent, $boards, 480);
}
- $loaded_boards = array();
+ $loaded_boards = [];
- foreach ($boards as $id => $props)
+ foreach ($boards as $id => $props) {
$loaded_boards[] = self::init($id, $props);
+ }
return $loaded_boards;
}
@@ -2207,22 +2188,23 @@ public static function getParents(int $id_parent): array
* If this is left empty, no WHERE clause will be used.
* @param array $order Zero or more conditions for the ORDER BY clause.
* If this is left empty, no ORDER BY clause will be used.
+ * @param array $group Zero or more conditions for the GROUP BY clause.
+ * If this is left empty, no GROUP BY clause will be used.
* @param int $limit Maximum number of results to retrieve.
* If this is left empty, all results will be retrieved.
*
* @return Generator Iterating over the result gives database rows.
*/
- public static function queryData(array $selects, array $params = array(), array $joins = array(), array $where = array(), array $order = array(), int $limit = 0)
+ public static function queryData(array $selects, array $params = [], array $joins = [], array $where = [], array $order = [], array $group = [], int $limit = 0)
{
// If we only want some child boards, use a CTE query for improved performance.
- if (!empty($params['id_parent']) && in_array('b.id_parent != 0', $where) && Db::$db->cte_support())
- {
+ if (!empty($params['id_parent']) && in_array('b.id_parent != 0', $where) && Db::$db->cte_support()) {
// Ensure we include all the necessary fields for the CTE query.
preg_match_all('/\bb\.(\w+)/', implode(', ', $selects), $matches);
$cte_fields = array_unique(array_merge(
$matches[1],
- array(
+ [
'child_level',
'id_board',
'name',
@@ -2237,35 +2219,33 @@ public static function queryData(array $selects, array $params = array(), array
'id_cat',
'id_last_msg',
'board_order',
- )
+ ],
));
$cte_selects = array_map(
- function ($field)
- {
+ function ($field) {
return 'b.' . $field;
},
- $cte_fields
+ $cte_fields,
);
- $cte_where1 = array('b.id_board = {int:id_parent}');
- $cte_where2 = array();
+ $cte_where1 = ['b.id_board = {int:id_parent}'];
+ $cte_where2 = [];
- if (in_array('{query_see_board}', $where))
- {
+ if (in_array('{query_see_board}', $where)) {
array_unshift($cte_where1, '{query_see_board}');
$cte_where2[] = '{query_see_board}';
- $where = array_diff($where, array('{query_see_board}'));
+ $where = array_diff($where, ['{query_see_board}']);
}
- if (in_array('b.child_level BETWEEN {int:child_level} AND {int:max_child_level}', $where))
- {
+ if (in_array('b.child_level BETWEEN {int:child_level} AND {int:max_child_level}', $where)) {
$cte_where2[] = 'b.child_level BETWEEN {int:child_level} AND {int:max_child_level}';
- $where = array_diff($where, array('b.child_level BETWEEN {int:child_level} AND {int:max_child_level}'));
+ $where = array_diff($where, ['b.child_level BETWEEN {int:child_level} AND {int:max_child_level}']);
}
- $request = Db::$db->query('', '
- WITH RECURSIVE
+ $request = Db::$db->query(
+ '',
+ 'WITH RECURSIVE
boards_cte (' . implode(', ', $cte_fields) . ')
AS
(
@@ -2285,26 +2265,23 @@ function ($field)
WHERE (' . implode(') AND (', $where) . ')') . (empty($order) ? '' : '
ORDER BY ' . implode(', ', $order)) . ($limit > 0 ? '
LIMIT ' . $limit : ''),
- $params
+ $params,
);
- }
- else
- {
- $request = Db::$db->query('', '
- SELECT
+ } else {
+ $request = Db::$db->query(
+ '',
+ 'SELECT
' . implode(', ', $selects) . '
FROM {db_prefix}boards AS b' . (empty($joins) ? '' : '
' . implode("\n\t\t\t\t", $joins)) . (empty($where) ? '' : '
WHERE (' . implode(') AND (', $where) . ')') . (empty($order) ? '' : '
ORDER BY ' . implode(', ', $order)) . ($limit > 0 ? '
LIMIT ' . $limit : ''),
- $params
+ $params,
);
-
}
- while ($row = Db::$db->fetch_assoc($request))
- {
+ while ($row = Db::$db->fetch_assoc($request)) {
yield $row;
}
Db::$db->free_result($request);
@@ -2338,50 +2315,51 @@ function ($field)
* @param array $props Properties to set for this board. Only used when $id
* is not null.
*/
- protected function __construct(?int $id = null, array $props = array())
+ protected function __construct(?int $id = null, array $props = [])
{
// This should already have been set, but just in case...
- if (!isset(self::$board_id))
+ if (!isset(self::$board_id)) {
self::$board_id = (int) ($_REQUEST['board'] ?? 0);
+ }
// No ID given, so load current board.
- if (!isset($id) || (!empty($id) && $id === self::$board_id))
- {
+ if (!isset($id) || (!empty($id) && $id === self::$board_id)) {
// Only do this once.
- if (!isset(self::$info))
- {
+ if (!isset(self::$info)) {
// Assume they are not a moderator.
- if (isset(User::$me))
+ if (isset(User::$me)) {
User::$me->is_mod = false;
+ }
// Start the linktree off empty..
- Utils::$context['linktree'] = array();
+ Utils::$context['linktree'] = [];
// Have they by chance specified a message id but nothing else?
- if (empty($_REQUEST['action']) && empty(Topic::$topic_id) && empty(self::$board_id) && !empty($_REQUEST['msg']))
- {
+ if (empty($_REQUEST['action']) && empty(Topic::$topic_id) && empty(self::$board_id) && !empty($_REQUEST['msg'])) {
$this->redirectFromMsg();
}
// Load this board only if it is specified.
- if (empty(self::$board_id) && empty(Topic::$topic_id))
+ if (empty(self::$board_id) && empty(Topic::$topic_id)) {
return;
+ }
// Load this board's info into the object properties.
$this->loadBoardInfo();
- if (empty($this->id))
+ if (empty($this->id)) {
return;
+ }
// At this point, we know that self::$board_id won't change.
self::$loaded[self::$board_id] = $this;
self::$info = $this;
- if (!empty(Topic::$topic_id))
+ if (!empty(Topic::$topic_id)) {
$_GET['board'] = (int) self::$board_id;
+ }
- if (!empty(self::$board_id))
- {
+ if (!empty(self::$board_id)) {
User::setModerators();
$this->checkAccess();
$this->buildLinkTree();
@@ -2392,27 +2370,24 @@ protected function __construct(?int $id = null, array $props = array())
Utils::$context['current_board'] = self::$board_id;
// No posting in redirection boards!
- if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'post' && !empty($this->redirect))
- {
+ if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'post' && !empty($this->redirect)) {
$this->error = 'post_in_redirect';
}
$this->blockOnError();
}
- }
- else
- {
+ } else {
// No props provided, so get the standard ones.
- if ($id > 0 && empty($props))
- {
- $request = Db::$db->query('', '
- SELECT *
+ if ($id > 0 && empty($props)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT *
FROM {db_prefix}boards
WHERE id_board = {int:id}
LIMIT 1',
- array(
+ [
'id' => $id,
- )
+ ],
);
$props = Db::$db->fetch_all($request);
Db::$db->free_result($request);
@@ -2424,14 +2399,12 @@ protected function __construct(?int $id = null, array $props = array())
}
// Add this board as a child of its parent.
- if (!empty($this->parent))
- {
+ if (!empty($this->parent)) {
self::init($this->parent)->children[$this->id] = $this;
}
// Plug this board into its category.
- if (!empty($this->cat) && $this->child_level == 0)
- {
+ if (!empty($this->cat) && $this->child_level == 0) {
$this->cat->children[$this->id] = $this;
}
}
@@ -2447,21 +2420,20 @@ protected function redirectFromMsg(): void
$_REQUEST['msg'] = (int) $_REQUEST['msg'];
// Looking through the message table can be slow, so try using the cache first.
- if ((Topic::$topic_id = CacheApi::get('msg_topic-' . $_REQUEST['msg'], 120)) === null)
- {
- $request = Db::$db->query('', '
- SELECT id_topic
+ if ((Topic::$topic_id = CacheApi::get('msg_topic-' . $_REQUEST['msg'], 120)) === null) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_topic
FROM {db_prefix}messages
WHERE id_msg = {int:id_msg}
LIMIT 1',
- array(
+ [
'id_msg' => $_REQUEST['msg'],
- )
+ ],
);
// So did it find anything?
- if (Db::$db->num_rows($request))
- {
+ if (Db::$db->num_rows($request)) {
list(Topic::$topic_id) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
@@ -2471,19 +2443,17 @@ protected function redirectFromMsg(): void
}
// Remember redirection is the key to avoiding fallout from your bosses.
- if (!empty(Topic::$topic_id))
- {
+ if (!empty(Topic::$topic_id)) {
$redirect_url = 'topic=' . Topic::$topic_id . '.msg' . $_REQUEST['msg'];
- if (($other_get_params = array_diff(array_keys($_GET), array('msg'))) !== array())
+ if (($other_get_params = array_diff(array_keys($_GET), ['msg'])) !== []) {
$redirect_url .= ';' . implode(';', $other_get_params);
+ }
$redirect_url .= '#msg' . $_REQUEST['msg'];
Utils::redirectexit($redirect_url);
- }
- else
- {
+ } else {
User::$me->loadPermissions();
Theme::load();
ErrorHandler::fatalLang('topic_gone', false);
@@ -2498,31 +2468,30 @@ protected function redirectFromMsg(): void
protected function loadBoardInfo(): void
{
// First, try the cache.
- if (!empty(CacheApi::$enable) && (empty(Topic::$topic_id) || CacheApi::$enable >= 3))
- {
- if (!empty(Topic::$topic_id))
- {
+ if (!empty(CacheApi::$enable) && (empty(Topic::$topic_id) || CacheApi::$enable >= 3)) {
+ if (!empty(Topic::$topic_id)) {
$temp = CacheApi::get('topic_board-' . Topic::$topic_id, 120);
- }
- else
- {
+ } else {
$temp = CacheApi::get('board-' . self::$board_id, 120);
}
- if (!empty($temp))
- {
- foreach ($temp as $key => $value)
- $this->{$key} = $value;
+ if (!empty($temp)) {
+ foreach ($temp as $key => $value) {
+ if ($key === 'cat') {
+ $this->{$key} = Category::init($value['id'], $value);
+ } else {
+ $this->{$key} = $value;
+ }
+ }
self::$board_id = $this->id;
}
}
// Cache gave us nothing, so query the database.
- if (empty($this->id))
- {
+ if (empty($this->id)) {
// Set up all the query components.
- $selects = array(
+ $selects = [
'b.id_board', 'b.id_cat', 'b.name', 'b.description',
'b.child_level', 'b.id_parent', 'b.board_order', 'b.redirect',
'b.member_groups', 'b.deny_member_groups', 'b.id_profile',
@@ -2531,25 +2500,24 @@ protected function loadBoardInfo(): void
'b.unapproved_posts', 'b.unapproved_topics', 'c.name AS cat_name',
'COALESCE(mg.id_group, 0) AS id_moderator_group', 'mg.group_name',
'COALESCE(mem.id_member, 0) AS id_moderator', 'mem.real_name',
- );
+ ];
- $params = array(
+ $params = [
'board_link' => self::$board_id,
- );
+ ];
- $joins = array(
+ $joins = [
'LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)',
'LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = {raw:board_link})',
'LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = modgs.id_group)',
'LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = {raw:board_link})',
'LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)',
- );
+ ];
- $where = array('b.id_board = {raw:board_link}');
- $order = array();
+ $where = ['b.id_board = {raw:board_link}'];
+ $order = [];
- if (!empty(Topic::$topic_id))
- {
+ if (!empty(Topic::$topic_id)) {
$selects[] = 't.approved';
$selects[] = 't.id_member_started';
@@ -2560,7 +2528,7 @@ protected function loadBoardInfo(): void
}
// Do any mods want to add some custom stuff to the query?
- IntegrationHook::call('integrate_load_board', array(&$selects, &$params, &$joins, &$where, &$order));
+ IntegrationHook::call('integrate_load_board', [&$selects, &$params, &$joins, &$where, &$order]);
$selects = array_unique($selects);
$params = array_unique($params);
@@ -2569,24 +2537,23 @@ protected function loadBoardInfo(): void
$order = array_unique($order);
// Run the query and iterate over the returned rows.
- foreach (self::queryData($selects, $params, $joins, $where, $order) as $row)
- {
+ foreach (self::queryData($selects, $params, $joins, $where, $order) as $row) {
$row['id_board'] = (int) $row['id_board'];
// The query as currently constructed will return multiple rows if
// there are multiple moderators and/or moderator groups. To avoid
// redundancy, we only set the rest of the data the first time.
- if (!isset($this->id))
- {
+ if (!isset($this->id)) {
// Set the current board.
- if (!empty($row['id_board']))
+ if (!empty($row['id_board'])) {
self::$board_id = $row['id_board'];
+ }
- $props = array(
+ $props = [
'id' => $row['id_board'],
- 'moderators' => array(),
- 'moderator_groups' => array(),
- 'cat' => Category::init($row['id_cat'], array('name' => $row['cat_name'])),
+ 'moderators' => [],
+ 'moderator_groups' => [],
+ 'cat' => Category::init($row['id_cat'], ['name' => $row['cat_name']]),
'name' => $row['name'],
'description' => $row['description'],
'num_topics' => (int) $row['num_topics'],
@@ -2606,59 +2573,56 @@ protected function loadBoardInfo(): void
'cur_topic_starter' => empty(Topic::$topic_id) ? 0 : $row['id_member_started'],
// Load the membergroups allowed, and check permissions.
- 'member_groups' => $row['member_groups'] == '' ? array() : array_filter(explode(',', $row['member_groups']), 'strlen'),
- 'deny_groups' => $row['deny_member_groups'] == '' ? array() : array_filter(explode(',', $row['deny_member_groups']), 'strlen'),
- );
+ 'member_groups' => $row['member_groups'] == '' ? [] : array_filter(explode(',', $row['member_groups']), 'strlen'),
+ 'deny_groups' => $row['deny_member_groups'] == '' ? [] : array_filter(explode(',', $row['deny_member_groups']), 'strlen'),
+ ];
- IntegrationHook::call('integrate_board_info', array(&$props, $row));
+ IntegrationHook::call('integrate_board_info', [&$props, $row]);
}
// This row included an individual moderator.
- if (!empty($row['id_moderator']))
- {
+ if (!empty($row['id_moderator'])) {
$row['id_moderator'] = (int) $row['id_moderator'];
- $props['moderators'][$row['id_moderator']] = array(
+ $props['moderators'][$row['id_moderator']] = [
'id' => $row['id_moderator'],
'name' => $row['real_name'],
'href' => Config::$scripturl . '?action=profile;u=' . $row['id_moderator'],
- 'link' => '' . $row['real_name'] . ''
- );
+ 'link' => '' . $row['real_name'] . '',
+ ];
}
// This row included a moderator group.
- if (!empty($row['id_moderator_group']))
- {
+ if (!empty($row['id_moderator_group'])) {
$row['id_moderator_group'] = (int) $row['id_moderator_group'];
- $props['moderator_groups'][$row['id_moderator_group']] = array(
+ $props['moderator_groups'][$row['id_moderator_group']] = [
'id' => $row['id_moderator_group'],
'name' => $row['group_name'],
'href' => Config::$scripturl . '?action=groups;sa=members;group=' . $row['id_moderator_group'],
- 'link' => '' . $row['group_name'] . ''
- );
+ 'link' => '' . $row['group_name'] . '',
+ ];
}
// Set the properties.
$this->set($props);
}
- if (!empty($this->id) && !empty(CacheApi::$enable) && (empty(Topic::$topic_id) || CacheApi::$enable >= 3))
- {
+ if (!empty($this->id) && !empty(CacheApi::$enable) && (empty(Topic::$topic_id) || CacheApi::$enable >= 3)) {
$to_cache = array_intersect_key((array) $this, array_flip(self::$cache_props['info']));
- if (!empty(Topic::$topic_id))
+ if (!empty(Topic::$topic_id)) {
CacheApi::put('topic_board-' . Topic::$topic_id, $to_cache, 120);
+ }
CacheApi::put('board-' . self::$board_id, $to_cache, 120);
}
}
// No board? Then the topic is invalid, there are no moderators, etc.
- if (empty($this->id))
- {
- $this->moderators = array();
- $this->moderator_groups = array();
+ if (empty($this->id)) {
+ $this->moderators = [];
+ $this->moderator_groups = [];
$this->error = 'exist';
Topic::$topic_id = null;
self::$board_id = 0;
@@ -2674,19 +2638,19 @@ protected function loadBoardInfo(): void
&& $this->unapproved_topics > 0
&& Config::$modSettings['postmod_active']
&& !User::$me->allowedTo('approve_posts')
- )
- {
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ ) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}topics
WHERE id_member_started = {int:id_member}
AND approved = {int:unapproved}
AND id_board = {int:board}',
- array(
+ [
'id_member' => User::$me->id,
'unapproved' => 0,
'board' => self::$board_id,
- )
+ ],
);
list($this->unapproved_user_topics) = Db::$db->fetch_row($request);
@@ -2698,15 +2662,13 @@ protected function loadBoardInfo(): void
*/
protected function checkAccess(): void
{
- if (User::$me->is_admin)
+ if (User::$me->is_admin) {
return;
+ }
- if (count(array_intersect(User::$me->groups, $this->member_groups)) == 0)
- {
+ if (count(array_intersect(User::$me->groups, $this->member_groups)) == 0) {
$this->error = 'access';
- }
- elseif (!empty(Config::$modSettings['deny_boards_access']) && count(array_intersect(User::$me->groups, $this->deny_groups)) != 0)
- {
+ } elseif (!empty(Config::$modSettings['deny_boards_access']) && count(array_intersect(User::$me->groups, $this->deny_groups)) != 0) {
$this->error = 'access';
}
}
@@ -2719,15 +2681,15 @@ protected function buildLinkTree(): void
// Build up the linktree.
Utils::$context['linktree'] = array_merge(
Utils::$context['linktree'],
- array(array(
+ [[
'url' => Config::$scripturl . '#c' . $this->cat['id'],
- 'name' => $this->cat['name']
- )),
+ 'name' => $this->cat['name'],
+ ]],
array_reverse($this->parent_boards),
- array(array(
+ [[
'url' => Config::$scripturl . '?board=' . $this->id . '.0',
- 'name' => $this->name
- ))
+ 'name' => $this->name,
+ ]],
);
}
@@ -2737,8 +2699,7 @@ protected function buildLinkTree(): void
protected function blockOnError(): void
{
// Hacker... you can't see this topic, I'll tell you that. (but moderators can!)
- if (!empty($this->error) && (!empty(Config::$modSettings['deny_boards_access']) || $this->error != 'access' || !User::$me->is_mod))
- {
+ if (!empty($this->error) && (!empty(Config::$modSettings['deny_boards_access']) || $this->error != 'access' || !User::$me->is_mod)) {
// The permissions and theme need loading, just to make sure everything goes smoothly.
User::$me->loadPermissions();
Theme::load();
@@ -2747,32 +2708,28 @@ protected function blockOnError(): void
$_GET['topic'] = '';
// The linktree should not give the game away mate!
- Utils::$context['linktree'] = array(
- array(
+ Utils::$context['linktree'] = [
+ [
'url' => Config::$scripturl,
- 'name' => Utils::$context['forum_name_html_safe']
- )
- );
+ 'name' => Utils::$context['forum_name_html_safe'],
+ ],
+ ];
// If it's a prefetching agent or we're requesting an attachment.
- if ((isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') || (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'dlattach'))
- {
+ if ((isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') || (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'dlattach')) {
ob_end_clean();
Utils::sendHttpStatus(403);
+
die;
}
- elseif ($this->error == 'post_in_redirect')
- {
+
+ if ($this->error == 'post_in_redirect') {
// Slightly different error message here...
ErrorHandler::fatalLang('cannot_post_redirect', false);
- }
- elseif (User::$me->is_guest)
- {
+ } elseif (User::$me->is_guest) {
Lang::load('Errors');
User::$me->kickIfGuest(Lang::$txt['topic_gone']);
- }
- else
- {
+ } else {
ErrorHandler::fatalLang('topic_gone', false);
}
}
@@ -2780,7 +2737,8 @@ protected function blockOnError(): void
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Board::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Board::exportStatic')) {
Board::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/BrowserDetector.php b/Sources/BrowserDetector.php
index aceb7c9462..003a31e846 100644
--- a/Sources/BrowserDetector.php
+++ b/Sources/BrowserDetector.php
@@ -35,11 +35,12 @@ class BrowserDetector
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
+ private static $backcompat = [
+ 'func_names' => [
'call' => 'detectBrowser',
- ),
- );
+ 'isBrowser' => 'isBrowser',
+ ],
+ ];
/*********************
* Internal properties
@@ -51,7 +52,7 @@ class BrowserDetector
* Holds all the browser information.
* Its contents will be placed into Utils::$context['browser']
*/
- private array $_browsers = array();
+ private array $_browsers = [];
/**
* @var bool
@@ -74,8 +75,9 @@ class BrowserDetector
*/
public static function call()
{
- if (!isset(self::$obj))
+ if (!isset(self::$obj)) {
self::$obj = new self();
+ }
self::$obj->detectBrowser();
}
@@ -89,8 +91,9 @@ public static function call()
public static function isBrowser($browser)
{
// Don't know any browser!
- if (!isset(self::$obj) || empty(self::$obj->_browsers))
+ if (!isset(self::$obj) || empty(self::$obj->_browsers)) {
self::call();
+ }
return !empty(self::$obj->_browsers[$browser]) || !empty(self::$obj->_browsers['is_' . $browser]);
}
@@ -109,20 +112,25 @@ public function detectBrowser()
$this->_browsers['needs_size_fix'] = false;
// One at a time, one at a time, and in this order too
- if ($this->isOpera())
+ if ($this->isOpera()) {
$this->setupOpera();
+ }
// Meh...
- elseif ($this->isEdge())
+ elseif ($this->isEdge()) {
$this->setupEdge();
+ }
// Them webkits need to be set up too
- elseif ($this->isWebkit())
+ elseif ($this->isWebkit()) {
$this->setupWebkit();
+ }
// We may have work to do on Firefox...
- elseif ($this->isFirefox())
+ elseif ($this->isFirefox()) {
$this->setupFirefox();
+ }
// Old friend, old frenemy
- elseif ($this->isIe())
+ elseif ($this->isIe()) {
$this->setupIe();
+ }
// Just a few mobile checks
$this->isOperaMini();
@@ -132,17 +140,17 @@ public function detectBrowser()
$this->isIe11();
// Be you robot or human?
- if (User::$me->possibly_robot)
- {
+ if (User::$me->possibly_robot) {
// This isn't meant to be reliable, it's just meant to catch most bots to prevent PHPSESSID from showing up.
$this->_browsers['possibly_robot'] = !empty(User::$me->possibly_robot);
// Robots shouldn't be logging in or registering. So, they aren't a bot. Better to be wrong than sorry (or people won't be able to log in!), anyway.
- if ((isset($_REQUEST['action']) && in_array($_REQUEST['action'], array('login', 'login2', 'register', 'signup'))) || !User::$me->is_guest)
+ if ((isset($_REQUEST['action']) && in_array($_REQUEST['action'], ['login', 'login2', 'register', 'signup'])) || !User::$me->is_guest) {
$this->_browsers['possibly_robot'] = false;
- }
- else
+ }
+ } else {
$this->_browsers['possibly_robot'] = false;
+ }
// Fill out the historical array as needed to support old mods that don't use isBrowser
$this->fillInformation();
@@ -160,139 +168,165 @@ public function detectBrowser()
/**
* Determine if the browser is Opera or not
*
- * @return boolean Whether or not this is Opera
+ * @return bool Whether or not this is Opera
*/
public function isOpera()
{
- if (!isset($this->_browsers['is_opera']))
+ if (!isset($this->_browsers['is_opera'])) {
$this->_browsers['is_opera'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false;
+ }
+
return $this->_browsers['is_opera'];
}
/**
* Determine if the browser is IE or not
*
- * @return boolean true Whether or not the browser is IE
+ * @return bool true Whether or not the browser is IE
*/
public function isIe()
{
// I'm IE, Yes I'm the real IE; All you other IEs are just imitating.
- if (!isset($this->_browsers['is_ie']))
+ if (!isset($this->_browsers['is_ie'])) {
$this->_browsers['is_ie'] = !$this->isOpera() && !$this->isGecko() && !$this->isWebTv() && preg_match('~MSIE \d+~', $_SERVER['HTTP_USER_AGENT']) === 1;
+ }
+
return $this->_browsers['is_ie'];
}
/**
* Determine if the browser is IE11 or not
*
- * @return boolean Whether or not the browser is IE11
+ * @return bool Whether or not the browser is IE11
*/
public function isIe11()
{
// IE11 is a bit different than earlier versions
// The isGecko() part is to ensure we get this right...
- if (!isset($this->_browsers['is_ie11']))
+ if (!isset($this->_browsers['is_ie11'])) {
$this->_browsers['is_ie11'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== false && $this->isGecko();
+ }
+
return $this->_browsers['is_ie11'];
}
/**
* Determine if the browser is Edge or not
*
- * @return boolean Whether or not the browser is Edge
+ * @return bool Whether or not the browser is Edge
*/
public function isEdge()
{
- if (!isset($this->_browsers['is_edge']))
+ if (!isset($this->_browsers['is_edge'])) {
$this->_browsers['is_edge'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Edge') !== false;
+ }
+
return $this->_browsers['is_edge'];
}
/**
* Determine if the browser is a Webkit based one or not
*
- * @return boolean Whether or not this is a Webkit-based browser
+ * @return bool Whether or not this is a Webkit-based browser
*/
public function isWebkit()
{
- if (!isset($this->_browsers['is_webkit']))
+ if (!isset($this->_browsers['is_webkit'])) {
$this->_browsers['is_webkit'] = strpos($_SERVER['HTTP_USER_AGENT'], 'AppleWebKit') !== false;
+ }
+
return $this->_browsers['is_webkit'];
}
/**
* Determine if the browser is Firefox or one of its variants
*
- * @return boolean Whether or not this is Firefox (or one of its variants)
+ * @return bool Whether or not this is Firefox (or one of its variants)
*/
public function isFirefox()
{
- if (!isset($this->_browsers['is_firefox']))
+ if (!isset($this->_browsers['is_firefox'])) {
$this->_browsers['is_firefox'] = preg_match('~(?:Firefox|Ice[wW]easel|IceCat|Shiretoko|Minefield)/~', $_SERVER['HTTP_USER_AGENT']) === 1 && $this->isGecko();
+ }
+
return $this->_browsers['is_firefox'];
}
/**
* Determine if the browser is WebTv or not
*
- * @return boolean Whether or not this is WebTV
+ * @return bool Whether or not this is WebTV
*/
public function isWebTv()
{
- if (!isset($this->_browsers['is_web_tv']))
+ if (!isset($this->_browsers['is_web_tv'])) {
$this->_browsers['is_web_tv'] = strpos($_SERVER['HTTP_USER_AGENT'], 'WebTV') !== false;
+ }
+
return $this->_browsers['is_web_tv'];
}
/**
* Determine if the browser is konqueror or not
*
- * @return boolean Whether or not this is Konqueror
+ * @return bool Whether or not this is Konqueror
*/
public function isKonqueror()
{
- if (!isset($this->_browsers['is_konqueror']))
+ if (!isset($this->_browsers['is_konqueror'])) {
$this->_browsers['is_konqueror'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== false;
+ }
+
return $this->_browsers['is_konqueror'];
}
/**
* Determine if the browser is Gecko or not
*
- * @return boolean Whether or not this is a Gecko-based browser
+ * @return bool Whether or not this is a Gecko-based browser
*/
public function isGecko()
{
- if (!isset($this->_browsers['is_gecko']))
+ if (!isset($this->_browsers['is_gecko'])) {
$this->_browsers['is_gecko'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false && !$this->isWebkit() && !$this->isKonqueror();
+ }
+
return $this->_browsers['is_gecko'];
}
/**
* Determine if the browser is Opera Mini or not
*
- * @return boolean Whether or not this is Opera Mini
+ * @return bool Whether or not this is Opera Mini
*/
public function isOperaMini()
{
- if (!isset($this->_browsers['is_opera_mini']))
+ if (!isset($this->_browsers['is_opera_mini'])) {
$this->_browsers['is_opera_mini'] = (isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA']) || stripos($_SERVER['HTTP_USER_AGENT'], 'opera mini') !== false);
- if ($this->_browsers['is_opera_mini'])
+ }
+
+ if ($this->_browsers['is_opera_mini']) {
$this->_is_mobile = true;
+ }
+
return $this->_browsers['is_opera_mini'];
}
/**
* Determine if the browser is Opera Mobile or not
*
- * @return boolean Whether or not this is Opera Mobile
+ * @return bool Whether or not this is Opera Mobile
*/
public function isOperaMobi()
{
- if (!isset($this->_browsers['is_opera_mobi']))
+ if (!isset($this->_browsers['is_opera_mobi'])) {
$this->_browsers['is_opera_mobi'] = stripos($_SERVER['HTTP_USER_AGENT'], 'opera mobi') !== false;
- if ($this->_browsers['is_opera_mobi'])
+ }
+
+ if ($this->_browsers['is_opera_mobi']) {
$this->_is_mobile = true;
+ }
+
return $this->_browsers['is_opera_mini'];
}
@@ -307,34 +341,35 @@ public function isOperaMobi()
*/
private function setupWebkit()
{
- $this->_browsers += array(
+ $this->_browsers += [
'is_chrome' => strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false,
'is_iphone' => (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'iPod') !== false) && strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') === false,
'is_blackberry' => stripos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'PlayBook') !== false,
'is_android' => strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false,
'is_nokia' => strpos($_SERVER['HTTP_USER_AGENT'], 'SymbianOS') !== false,
- );
+ ];
// blackberry, playbook, iphone, nokia, android and ipods set a mobile flag
- if ($this->_browsers['is_iphone'] || $this->_browsers['is_blackberry'] || $this->_browsers['is_android'] || $this->_browsers['is_nokia'])
+ if ($this->_browsers['is_iphone'] || $this->_browsers['is_blackberry'] || $this->_browsers['is_android'] || $this->_browsers['is_nokia']) {
$this->_is_mobile = true;
+ }
// @todo what to do with the blaPad? ... for now leave it detected as Safari ...
$this->_browsers['is_safari'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false && !$this->_browsers['is_chrome'] && !$this->_browsers['is_iphone'];
$this->_browsers['is_ipad'] = strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') !== false;
// if Chrome, get the major version
- if ($this->_browsers['is_chrome'])
- {
- if (preg_match('~chrome[/]([0-9][0-9]?[.])~i', $_SERVER['HTTP_USER_AGENT'], $match) === 1)
+ if ($this->_browsers['is_chrome']) {
+ if (preg_match('~chrome[/]([0-9][0-9]?[.])~i', $_SERVER['HTTP_USER_AGENT'], $match) === 1) {
$this->_browsers['is_chrome' . (int) $match[1]] = true;
+ }
}
// or if Safari get its major version
- if ($this->_browsers['is_safari'])
- {
- if (preg_match('~version/?(.*)safari.*~i', $_SERVER['HTTP_USER_AGENT'], $match) === 1)
+ if ($this->_browsers['is_safari']) {
+ if (preg_match('~version/?(.*)safari.*~i', $_SERVER['HTTP_USER_AGENT'], $match) === 1) {
$this->_browsers['is_safari' . (int) trim($match[1])] = true;
+ }
}
}
@@ -350,21 +385,20 @@ private function setupIe()
$this->_browsers['is_ie_compat_view'] = false;
// get the version of the browser from the msie tag
- if (preg_match('~MSIE\s?([0-9][0-9]?.[0-9])~i', $_SERVER['HTTP_USER_AGENT'], $msie_match) === 1)
- {
+ if (preg_match('~MSIE\s?([0-9][0-9]?.[0-9])~i', $_SERVER['HTTP_USER_AGENT'], $msie_match) === 1) {
$msie_match[1] = trim($msie_match[1]);
$msie_match[1] = (($msie_match[1] - (int) $msie_match[1]) == 0) ? (int) $msie_match[1] : $msie_match[1];
$this->_browsers['is_ie' . $msie_match[1]] = true;
}
// "modern" ie uses trident 4=ie8, 5=ie9, 6=ie10, 7=ie11 even in compatibility view
- if (preg_match('~Trident/([0-9.])~i', $_SERVER['HTTP_USER_AGENT'], $trident_match) === 1)
- {
+ if (preg_match('~Trident/([0-9.])~i', $_SERVER['HTTP_USER_AGENT'], $trident_match) === 1) {
$this->_browsers['is_ie' . ((int) $trident_match[1] + 4)] = true;
// If trident is set, see the (if any) msie tag in the user agent matches ... if not its in some compatibility view
- if (isset($msie_match[1]) && ($msie_match[1] < $trident_match[1] + 4))
+ if (isset($msie_match[1]) && ($msie_match[1] < $trident_match[1] + 4)) {
$this->_browsers['is_ie_compat_view'] = true;
+ }
}
// Detect true IE6 and IE7 and not IE in compat mode.
@@ -372,17 +406,16 @@ private function setupIe()
$this->_browsers['is_ie6'] = !empty($this->_browsers['is_ie6']) && ($this->_browsers['is_ie_compat_view'] === false);
// IE mobile 7 or 9, ... shucks why not
- if ((!empty($this->_browsers['is_ie7']) && strpos($_SERVER['HTTP_USER_AGENT'], 'IEMobile/7') !== false) || (!empty($this->_browsers['is_ie9']) && strpos($_SERVER['HTTP_USER_AGENT'], 'IEMobile/9') !== false))
- {
+ if ((!empty($this->_browsers['is_ie7']) && strpos($_SERVER['HTTP_USER_AGENT'], 'IEMobile/7') !== false) || (!empty($this->_browsers['is_ie9']) && strpos($_SERVER['HTTP_USER_AGENT'], 'IEMobile/9') !== false)) {
$this->_browsers['is_ie_mobi'] = true;
$this->_is_mobile = true;
}
// And some throwbacks to a bygone era, deposited here like cholesterol in your arteries
- $this->_browsers += array(
+ $this->_browsers += [
'is_ie4' => !empty($this->_browsers['is_ie4']) && !$this->_browsers['is_web_tv'],
- 'is_mac_ie' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5.') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') !== false
- );
+ 'is_mac_ie' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5.') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') !== false,
+ ];
// Before IE8 we need to fix IE... lots!
$this->_browsers['ie_standards_fix'] = (($this->_browsers['is_ie6'] === true) || ($this->_browsers['is_ie7'] === true)) ? true : false;
@@ -398,8 +431,9 @@ private function setupIe()
*/
private function setupFirefox()
{
- if (preg_match('~(?:Firefox|Ice[wW]easel|IceCat|Shiretoko|Minefield)[\/ \(]([^ ;\)]+)~', $_SERVER['HTTP_USER_AGENT'], $match) === 1)
+ if (preg_match('~(?:Firefox|Ice[wW]easel|IceCat|Shiretoko|Minefield)[\/ \(]([^ ;\)]+)~', $_SERVER['HTTP_USER_AGENT'], $match) === 1) {
$this->_browsers['is_firefox' . (int) $match[1]] = true;
+ }
}
/**
@@ -410,11 +444,13 @@ private function setupFirefox()
private function setupOpera()
{
// Opera 10+ uses the version tag at the end of the string
- if (preg_match('~\sVersion/([0-9]+)\.[0-9]+(?:\s*|$)~', $_SERVER['HTTP_USER_AGENT'], $match))
+ if (preg_match('~\sVersion/([0-9]+)\.[0-9]+(?:\s*|$)~', $_SERVER['HTTP_USER_AGENT'], $match)) {
$this->_browsers['is_opera' . (int) $match[1]] = true;
+ }
// Opera pre 10 is supposed to uses the Opera tag alone, as do some spoofers
- elseif (preg_match('~Opera[ /]([0-9]+)(?!\\.[89])~', $_SERVER['HTTP_USER_AGENT'], $match))
+ elseif (preg_match('~Opera[ /]([0-9]+)(?!\.[89])~', $_SERVER['HTTP_USER_AGENT'], $match)) {
$this->_browsers['is_opera' . (int) $match[1]] = true;
+ }
// Needs size fix?
$this->_browsers['needs_size_fix'] = !empty($this->_browsers['is_opera6']);
@@ -425,8 +461,9 @@ private function setupOpera()
*/
private function setupEdge()
{
- if (preg_match('~Edge[\/]([0-9][0-9]?[\.][0-9][0-9])~i', $_SERVER['HTTP_USER_AGENT'], $match) === 1)
+ if (preg_match('~Edge[\/]([0-9][0-9]?[\.][0-9][0-9])~i', $_SERVER['HTTP_USER_AGENT'], $match) === 1) {
$this->_browsers['is_edge' . (int) $match[1]] = true;
+ }
}
/**
@@ -437,12 +474,11 @@ private function setupEdge()
*/
private function setupBrowserPriority()
{
- if ($this->_is_mobile)
+ if ($this->_is_mobile) {
Utils::$context['browser_body_id'] = 'mobile';
- else
- {
+ } else {
// add in any specific detection conversions here if you want a special body id e.g. 'is_opera9' => 'opera9'
- $browser_priority = array(
+ $browser_priority = [
'is_ie6' => 'ie6',
'is_ie7' => 'ie7',
'is_ie8' => 'ie8',
@@ -459,14 +495,13 @@ private function setupBrowserPriority()
'is_opera12' => 'opera12',
'is_opera' => 'opera',
'is_konqueror' => 'konqueror',
- );
+ ];
Utils::$context['browser_body_id'] = 'smf';
$active = array_reverse(array_keys($this->_browsers, true));
- foreach ($active as $browser)
- {
- if (array_key_exists($browser, $browser_priority))
- {
+
+ foreach ($active as $browser) {
+ if (array_key_exists($browser, $browser_priority)) {
Utils::$context['browser_body_id'] = $browser_priority[$browser];
break;
}
@@ -480,7 +515,7 @@ private function setupBrowserPriority()
*/
private function fillInformation()
{
- $this->_browsers += array(
+ $this->_browsers += [
'is_opera' => false,
'is_opera6' => false,
'is_opera7' => false,
@@ -511,12 +546,13 @@ private function fillInformation()
'ie_standards_fix' => false,
'needs_size_fix' => false,
'possibly_robot' => false,
- );
+ ];
}
}
// Export public static functions to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\BrowserDetector::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\BrowserDetector::exportStatic')) {
BrowserDetector::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Cache/APIs/Apcu.php b/Sources/Cache/APIs/Apcu.php
index c1e5471a9f..74642146fd 100644
--- a/Sources/Cache/APIs/Apcu.php
+++ b/Sources/Cache/APIs/Apcu.php
@@ -16,8 +16,9 @@
use SMF\Cache\CacheApi;
use SMF\Cache\CacheApiInterface;
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
/**
* Our Cache API class
@@ -33,8 +34,9 @@ public function isSupported($test = false)
{
$supported = function_exists('apcu_fetch') && function_exists('apcu_store');
- if ($test)
+ if ($test) {
return $supported;
+ }
return parent::isSupported() && $supported;
}
@@ -67,11 +69,11 @@ public function putData($key, $value, $ttl = null)
$key = $this->prefix . strtr($key, ':/', '-_');
// An extended key is needed to counteract a bug in APC.
- if ($value === null)
+ if ($value === null) {
return apcu_delete($key . 'smf');
+ }
- else
- return apcu_store($key . 'smf', $value, $ttl !== null ? $ttl : $this->ttl);
+ return apcu_store($key . 'smf', $value, $ttl !== null ? $ttl : $this->ttl);
}
/**
diff --git a/Sources/Cache/APIs/FileBased.php b/Sources/Cache/APIs/FileBased.php
index 0c7653c0e3..e5c06f23e9 100644
--- a/Sources/Cache/APIs/FileBased.php
+++ b/Sources/Cache/APIs/FileBased.php
@@ -13,16 +13,17 @@
namespace SMF\Cache\APIs;
-use GlobIterator;
use FilesystemIterator;
+use GlobIterator;
+use SMF\Cache\CacheApi;
+use SMF\Cache\CacheApiInterface;
use SMF\Config;
use SMF\Lang;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Cache\CacheApiInterface;
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
/**
* Our Cache API class
@@ -32,7 +33,7 @@
class FileBased extends CacheApi implements CacheApiInterface
{
/**
- * @var string The path to the current $cachedir directory.
+ * @var string The path to the current directory.
*/
private $cachedir = null;
@@ -54,24 +55,26 @@ public function isSupported($test = false)
{
$supported = is_writable($this->cachedir);
- if ($test)
+ if ($test) {
return $supported;
+ }
return parent::isSupported() && $supported;
}
private function readFile($file)
{
- if (($fp = @fopen($file, 'rb')) !== false)
- {
- if (!flock($fp, LOCK_SH))
- {
+ if (($fp = @fopen($file, 'rb')) !== false) {
+ if (!flock($fp, LOCK_SH)) {
fclose($fp);
+
return false;
}
$string = '';
- while (!feof($fp))
+
+ while (!feof($fp)) {
$string .= fread($fp, 8192);
+ }
flock($fp, LOCK_UN);
fclose($fp);
@@ -84,22 +87,22 @@ private function readFile($file)
private function writeFile($file, $string)
{
- if (($fp = fopen($file, 'cb')) !== false)
- {
- if (!flock($fp, LOCK_EX))
- {
+ if (($fp = fopen($file, 'cb')) !== false) {
+ if (!flock($fp, LOCK_EX)) {
fclose($fp);
+
return false;
}
ftruncate($fp, 0);
$bytes = 0;
$pieces = str_split($string, 8192);
- foreach ($pieces as $piece)
- {
- if (($val = fwrite($fp, $piece, 8192)) !== false)
+
+ foreach ($pieces as $piece) {
+ if (($val = fwrite($fp, $piece, 8192)) !== false) {
$bytes += $val;
- else
+ } else {
return false;
+ }
}
fflush($fp);
flock($fp, LOCK_UN);
@@ -124,21 +127,20 @@ public function connect()
*/
public function getData($key, $ttl = null)
{
- $file = sprintf('%s/data_%s.cache',
+ $file = sprintf(
+ '%s/data_%s.cache',
$this->cachedir,
- $this->prefix . strtr($key, ':/', '-_')
+ $this->prefix . strtr($key, ':/', '-_'),
);
// SMF Data returns $value and $expired. $expired has a unix timestamp of when this expires.
- if (file_exists($file) && ($raw = $this->readFile($file)) !== false)
- {
- if (($value = Utils::jsonDecode($raw, true, false)) !== array() && isset($value['expiration']) && $value['expiration'] >= time())
+ if (file_exists($file) && ($raw = $this->readFile($file)) !== false) {
+ if (($value = Utils::jsonDecode($raw, true, false)) !== [] && isset($value['expiration']) && $value['expiration'] >= time()) {
return $value['value'];
- else
- @unlink($file);
- }
+ }
- return null;
+ @unlink($file);
+ }
}
/**
@@ -146,33 +148,33 @@ public function getData($key, $ttl = null)
*/
public function putData($key, $value, $ttl = null)
{
- $file = sprintf('%s/data_%s.cache',
+ $file = sprintf(
+ '%s/data_%s.cache',
$this->cachedir,
- $this->prefix . strtr($key, ':/', '-_')
+ $this->prefix . strtr($key, ':/', '-_'),
);
$ttl = $ttl !== null ? $ttl : $this->ttl;
- if ($value === null)
+ if ($value === null) {
@unlink($file);
- else
- {
+ } else {
$cache_data = json_encode(
- array(
+ [
'expiration' => time() + $ttl,
- 'value' => $value
- ),
- JSON_NUMERIC_CHECK
+ 'value' => $value,
+ ],
+ JSON_NUMERIC_CHECK,
);
// Write out the cache file, check that the cache write was successful; all the data must be written
// If it fails due to low diskspace, or other, remove the cache file
- if ($this->writeFile($file, $cache_data) !== strlen($cache_data))
- {
+ if ($this->writeFile($file, $cache_data) !== strlen($cache_data)) {
@unlink($file);
+
return false;
}
- else
- return true;
+
+ return true;
}
}
@@ -182,14 +184,16 @@ public function putData($key, $value, $ttl = null)
public function cleanCache($type = '')
{
// No directory = no game.
- if (!is_dir($this->cachedir))
+ if (!is_dir($this->cachedir)) {
return;
+ }
// Remove the files in SMF's own disk cache, if any
$files = new GlobIterator($this->cachedir . '/' . $type . '*.cache', FilesystemIterator::NEW_CURRENT_AND_KEY);
- foreach ($files as $file => $info)
+ foreach ($files as $file => $info) {
unlink($this->cachedir . '/' . $file);
+ }
// Make this invalid.
$this->invalidateCache();
@@ -219,41 +223,41 @@ public function cacheSettings(array &$config_vars)
$class_name = $this->getImplementationClassKeyName();
$class_name_txt_key = strtolower($class_name);
- $config_vars[] = Lang::$txt['cache_'. $class_name_txt_key .'_settings'];
- $config_vars[] = array('cachedir', Lang::$txt['cachedir'], 'file', 'text', 36, 'cache_cachedir');
+ $config_vars[] = Lang::$txt['cache_' . $class_name_txt_key . '_settings'];
+ $config_vars[] = ['cachedir', Lang::$txt['cachedir'], 'file', 'text', 36, 'cache_cachedir'];
- if (!isset(Utils::$context['settings_post_javascript']))
+ if (!isset(Utils::$context['settings_post_javascript'])) {
Utils::$context['settings_post_javascript'] = '';
+ }
- if (empty(Utils::$context['settings_not_writable']))
+ if (empty(Utils::$context['settings_not_writable'])) {
Utils::$context['settings_post_javascript'] .= '
$("#cache_accelerator").change(function (e) {
var cache_type = e.currentTarget.value;
- $("#cachedir").prop("disabled", cache_type != "'. $class_name .'");
+ $("#cachedir").prop("disabled", cache_type != "' . $class_name . '");
});';
+ }
}
/**
* Sets the $cachedir or uses the SMF default $cachedir..
*
- * @access public
* @param string $dir A valid path
- * @return boolean If this was successful or not.
+ * @return bool If this was successful or not.
*/
public function setCachedir($dir = null)
{
// If its invalid, use SMF's.
- if (is_null($dir) || !is_writable($dir))
+ if (is_null($dir) || !is_writable($dir)) {
$this->cachedir = Config::$cachedir;
-
- else
+ } else {
$this->cachedir = $dir;
+ }
}
/**
* Gets the current $cachedir.
*
- * @access public
* @return string the value of $ttl.
*/
public function getCachedir()
diff --git a/Sources/Cache/APIs/MemcacheImplementation.php b/Sources/Cache/APIs/MemcacheImplementation.php
index 23496f2af4..d50efce3cb 100644
--- a/Sources/Cache/APIs/MemcacheImplementation.php
+++ b/Sources/Cache/APIs/MemcacheImplementation.php
@@ -14,13 +14,15 @@
namespace SMF\Cache\APIs;
use Memcache;
-use SMF\Config;
-use SMF\Lang;
use SMF\Cache\CacheApi;
use SMF\Cache\CacheApiInterface;
+use SMF\Config;
+use SMF\Lang;
+use SMF\Utils;
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
/**
* Our Cache API class
@@ -29,7 +31,7 @@
*/
class MemcacheImplementation extends CacheApi implements CacheApiInterface
{
- const CLASS_KEY = 'cache_memcached';
+ public const CLASS_KEY = 'cache_memcached';
/**
* @var object
@@ -51,19 +53,17 @@ class MemcacheImplementation extends CacheApi implements CacheApiInterface
public function __construct()
{
$this->servers = array_map(
- function($server)
- {
+ function ($server) {
// Normal host names do not contain slashes, while e.g. unix sockets do. Assume alternative transport pipe with port 0.
- if (strpos($server, '/') !== false)
- return array($server, 0);
-
- else
- {
- $server = explode(':', $server);
- return array($server[0], isset($server[1]) ? (int) $server[1] : 11211);
+ if (strpos($server, '/') !== false) {
+ return [$server, 0];
}
+
+ $server = explode(':', $server);
+
+ return [$server[0], isset($server[1]) ? (int) $server[1] : 11211];
},
- array_map('trim', explode(',', Config::$cache_memcached))
+ array_map('trim', explode(',', Config::$cache_memcached)),
);
parent::__construct();
@@ -76,8 +76,9 @@ public function isSupported($test = false)
{
$supported = class_exists('Memcache');
- if ($test)
+ if ($test) {
return $supported;
+ }
return parent::isSupported() && $supported && !empty($this->servers);
}
@@ -94,25 +95,25 @@ public function connect()
$level = 0;
// We should keep trying if a server times out, but only for the amount of servers we have.
- while (!$connected && $level < count($this->servers))
- {
+ while (!$connected && $level < count($this->servers)) {
++$level;
$server = $this->servers[array_rand($this->servers)];
// No server, can't connect to this.
- if (empty($server[0]))
+ if (empty($server[0])) {
continue;
+ }
$host = $server[0];
$port = $server[1];
// Don't wait too long: yes, we want the server, but we might be able to run the query faster!
- if (empty(Config::$db_persist))
+ if (empty(Config::$db_persist)) {
$connected = $this->memcache->connect($host, $port);
-
- else
+ } else {
$connected = $this->memcache->pconnect($host, $port);
+ }
}
return $connected;
@@ -128,8 +129,9 @@ public function getData($key, $ttl = null)
$value = $this->memcache->get($key);
// $value should return either data or false (from failure, key not found or empty array).
- if ($value === false)
- return null;
+ if ($value === false) {
+ return;
+ }
return $value;
}
@@ -167,27 +169,28 @@ public function cleanCache($type = '')
*/
public function cacheSettings(array &$config_vars)
{
- if (!in_array(Lang::$txt[self::CLASS_KEY .'_settings'], $config_vars))
- {
- $config_vars[] = Lang::$txt[self::CLASS_KEY .'_settings'];
- $config_vars[] = array(
+ if (!in_array(Lang::$txt[self::CLASS_KEY . '_settings'], $config_vars)) {
+ $config_vars[] = Lang::$txt[self::CLASS_KEY . '_settings'];
+ $config_vars[] = [
self::CLASS_KEY,
- Lang::$txt[self::CLASS_KEY .'_servers'],
+ Lang::$txt[self::CLASS_KEY . '_servers'],
'file',
'text',
0,
- 'subtext' => Lang::$txt[self::CLASS_KEY .'_servers_subtext']);
+ 'subtext' => Lang::$txt[self::CLASS_KEY . '_servers_subtext']];
}
- if (!isset(Utils::$context['settings_post_javascript']))
+ if (!isset(Utils::$context['settings_post_javascript'])) {
Utils::$context['settings_post_javascript'] = '';
+ }
- if (empty(Utils::$context['settings_not_writable']))
+ if (empty(Utils::$context['settings_not_writable'])) {
Utils::$context['settings_post_javascript'] .= '
$("#cache_accelerator").change(function (e) {
var cache_type = e.currentTarget.value;
- $("#'. self::CLASS_KEY .'").prop("disabled", cache_type != "MemcacheImplementation" && cache_type != "MemcachedImplementation");
+ $("#' . self::CLASS_KEY . '").prop("disabled", cache_type != "MemcacheImplementation" && cache_type != "MemcachedImplementation");
});';
+ }
}
/**
@@ -195,14 +198,16 @@ public function cacheSettings(array &$config_vars)
*/
public function getVersion()
{
- if (!is_object($this->memcache))
+ if (!is_object($this->memcache)) {
return false;
+ }
// This gets called in Subs-Admin getServerVersions when loading up support information. If we can't get a connection, return nothing.
$result = $this->memcache->getVersion();
- if (!empty($result))
+ if (!empty($result)) {
return $result;
+ }
return false;
}
diff --git a/Sources/Cache/APIs/MemcachedImplementation.php b/Sources/Cache/APIs/MemcachedImplementation.php
index 32c7ceb0ba..23552147ee 100644
--- a/Sources/Cache/APIs/MemcachedImplementation.php
+++ b/Sources/Cache/APIs/MemcachedImplementation.php
@@ -14,13 +14,15 @@
namespace SMF\Cache\APIs;
use Memcached;
-use SMF\Config;
-use SMF\Lang;
use SMF\Cache\CacheApi;
use SMF\Cache\CacheApiInterface;
+use SMF\Config;
+use SMF\Lang;
+use SMF\Utils;
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
/**
* Our Cache API class
@@ -29,7 +31,7 @@
*/
class MemcachedImplementation extends CacheApi implements CacheApiInterface
{
- const CLASS_KEY = 'cache_memcached';
+ public const CLASS_KEY = 'cache_memcached';
/**
* @var object
@@ -51,19 +53,17 @@ class MemcachedImplementation extends CacheApi implements CacheApiInterface
public function __construct()
{
$this->servers = array_map(
- function($server)
- {
+ function ($server) {
// Normal host names do not contain slashes, while e.g. unix sockets do. Assume alternative transport pipe with port 0.
- if (strpos($server, '/') !== false)
- return array($server, 0);
-
- else
- {
- $server = explode(':', $server);
- return array($server[0], isset($server[1]) ? (int) $server[1] : 11211);
+ if (strpos($server, '/') !== false) {
+ return [$server, 0];
}
+
+ $server = explode(':', $server);
+
+ return [$server[0], isset($server[1]) ? (int) $server[1] : 11211];
},
- explode(',', Config::$cache_memcached)
+ explode(',', Config::$cache_memcached),
);
parent::__construct();
@@ -76,8 +76,9 @@ public function isSupported($test = false)
{
$supported = class_exists('Memcached');
- if ($test)
+ if ($test) {
return $supported;
+ }
return parent::isSupported() && $supported && !empty($this->servers);
}
@@ -87,7 +88,7 @@ public function isSupported($test = false)
*/
public function connect()
{
- $this->memcached = new Memcached;
+ $this->memcached = new Memcached();
return $this->addServers();
}
@@ -103,22 +104,22 @@ protected function addServers()
{
$currentServers = $this->memcached->getServerList();
$retVal = !empty($currentServers);
- foreach ($this->servers as $server)
- {
+
+ foreach ($this->servers as $server) {
// Figure out if we have this server or not
$foundServer = false;
- foreach ($currentServers as $currentServer)
- {
- if ($server[0] == $currentServer['host'] && $server[1] == $currentServer['port'])
- {
+
+ foreach ($currentServers as $currentServer) {
+ if ($server[0] == $currentServer['host'] && $server[1] == $currentServer['port']) {
$foundServer = true;
break;
}
}
// Found it?
- if (empty($foundServer))
+ if (empty($foundServer)) {
$retVal |= $this->memcached->addServer($server[0], $server[1]);
+ }
}
return $retVal;
@@ -134,8 +135,9 @@ public function getData($key, $ttl = null)
$value = $this->memcached->get($key);
// $value should return either data or false (from failure, key not found or empty array).
- if ($value === false)
- return null;
+ if ($value === false) {
+ return;
+ }
return $value;
}
@@ -174,27 +176,28 @@ public function quit()
*/
public function cacheSettings(array &$config_vars)
{
- if (!in_array(Lang::$txt[self::CLASS_KEY .'_settings'], $config_vars))
- {
- $config_vars[] = Lang::$txt[self::CLASS_KEY .'_settings'];
- $config_vars[] = array(
+ if (!in_array(Lang::$txt[self::CLASS_KEY . '_settings'], $config_vars)) {
+ $config_vars[] = Lang::$txt[self::CLASS_KEY . '_settings'];
+ $config_vars[] = [
self::CLASS_KEY,
- Lang::$txt[self::CLASS_KEY .'_servers'],
+ Lang::$txt[self::CLASS_KEY . '_servers'],
'file',
'text',
0,
- 'subtext' => Lang::$txt[self::CLASS_KEY .'_servers_subtext']);
+ 'subtext' => Lang::$txt[self::CLASS_KEY . '_servers_subtext']];
}
- if (!isset(Utils::$context['settings_post_javascript']))
+ if (!isset(Utils::$context['settings_post_javascript'])) {
Utils::$context['settings_post_javascript'] = '';
+ }
- if (empty(Utils::$context['settings_not_writable']))
+ if (empty(Utils::$context['settings_not_writable'])) {
Utils::$context['settings_post_javascript'] .= '
$("#cache_accelerator").change(function (e) {
var cache_type = e.currentTarget.value;
- $("#'. self::CLASS_KEY .'").prop("disabled", cache_type != "MemcacheImplementation" && cache_type != "MemcachedImplementation");
+ $("#' . self::CLASS_KEY . '").prop("disabled", cache_type != "MemcacheImplementation" && cache_type != "MemcachedImplementation");
});';
+ }
}
/**
@@ -202,14 +205,16 @@ public function cacheSettings(array &$config_vars)
*/
public function getVersion()
{
- if (!is_object($this->memcached))
+ if (!is_object($this->memcached)) {
return false;
+ }
// This gets called in Subs-Admin getServerVersions when loading up support information. If we can't get a connection, return nothing.
$result = $this->memcached->getVersion();
- if (!empty($result))
+ if (!empty($result)) {
return current($result);
+ }
return false;
}
diff --git a/Sources/Cache/APIs/Postgres.php b/Sources/Cache/APIs/Postgres.php
index de2bb7c3a7..27a1296079 100644
--- a/Sources/Cache/APIs/Postgres.php
+++ b/Sources/Cache/APIs/Postgres.php
@@ -13,13 +13,14 @@
namespace SMF\Cache\APIs;
-use SMF\Config;
-use SMF\Db\DatabaseApi as Db;
use SMF\Cache\CacheApi;
use SMF\Cache\CacheApiInterface;
+use SMF\Config;
+use SMF\Db\DatabaseApi as Db;
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
/**
* PostgreSQL Cache API class
@@ -28,10 +29,14 @@
*/
class Postgres extends CacheApi implements CacheApiInterface
{
- /** @var string */
+ /**
+ * @var string
+ */
private $db_prefix;
- /** @var resource result of pg_connect. */
+ /**
+ * @var resource result of pg_connect.
+ */
private $db_connection;
public function __construct()
@@ -47,31 +52,34 @@ public function __construct()
*/
public function connect()
{
- $result = pg_query_params($this->db_connection, 'SELECT 1
+ $result = pg_query_params(
+ $this->db_connection,
+ 'SELECT 1
FROM pg_tables
WHERE schemaname = $1
AND tablename = $2',
- array(
+ [
'public',
$this->db_prefix . 'cache',
- )
+ ],
);
- if (pg_affected_rows($result) === 0)
+ if (pg_affected_rows($result) === 0) {
pg_query($this->db_connection, 'CREATE UNLOGGED TABLE ' . $this->db_prefix . 'cache (key text, value text, ttl bigint, PRIMARY KEY (key))');
+ }
$this->prepareQueries(
- array(
+ [
'smf_cache_get_data',
'smf_cache_put_data',
'smf_cache_delete_data',
- ),
- array(
+ ],
+ [
'SELECT value FROM ' . $this->db_prefix . 'cache WHERE key = $1 AND ttl >= $2 LIMIT 1',
'INSERT INTO ' . $this->db_prefix . 'cache(key,value,ttl) VALUES($1,$2,$3)
ON CONFLICT(key) DO UPDATE SET value = $2, ttl = $3',
'DELETE FROM ' . $this->db_prefix . 'cache WHERE key = $1',
- )
+ ],
);
return true;
@@ -88,19 +96,21 @@ private function prepareQueries(array $stmtnames, array $queries)
$result = pg_query_params(
$this->db_connection,
'SELECT name FROM pg_prepared_statements WHERE name = ANY ($1)',
- array('{' . implode(', ', $stmtnames) . '}')
+ ['{' . implode(', ', $stmtnames) . '}'],
);
- $arr = pg_num_rows($result) == 0 ? array() : array_map(
- function($el)
- {
+ $arr = pg_num_rows($result) == 0 ? [] : array_map(
+ function ($el) {
return $el['name'];
},
- pg_fetch_all($result)
+ pg_fetch_all($result),
);
- foreach ($stmtnames as $idx => $stmtname)
- if (!in_array($stmtname, $arr))
+
+ foreach ($stmtnames as $idx => $stmtname) {
+ if (!in_array($stmtname, $arr)) {
pg_prepare($this->db_connection, $stmtname, $queries[$idx]);
+ }
+ }
}
/**
@@ -108,14 +118,16 @@ function($el)
*/
public function isSupported($test = false)
{
- if (Db::$db->title !== POSTGRE_TITLE)
+ if (Db::$db->title !== POSTGRE_TITLE) {
return false;
+ }
$result = pg_query($this->db_connection, 'SHOW server_version_num');
$res = pg_fetch_assoc($result);
- if ($res['server_version_num'] < 90500)
+ if ($res['server_version_num'] < 90500) {
return false;
+ }
return $test ? true : parent::isSupported();
}
@@ -125,10 +137,11 @@ public function isSupported($test = false)
*/
public function getData($key, $ttl = null)
{
- $result = pg_execute($this->db_connection, 'smf_cache_get_data', array($key, time()));
+ $result = pg_execute($this->db_connection, 'smf_cache_get_data', [$key, time()]);
- if (pg_affected_rows($result) === 0)
- return null;
+ if (pg_affected_rows($result) === 0) {
+ return;
+ }
$res = pg_fetch_assoc($result);
@@ -142,10 +155,11 @@ public function putData($key, $value, $ttl = null)
{
$ttl = time() + (int) ($ttl !== null ? $ttl : $this->ttl);
- if ($value === null)
- $result = pg_execute($this->db_connection, 'smf_cache_delete_data', array($key));
- else
- $result = pg_execute($this->db_connection, 'smf_cache_put_data', array($key, $value, $ttl));
+ if ($value === null) {
+ $result = pg_execute($this->db_connection, 'smf_cache_delete_data', [$key]);
+ } else {
+ $result = pg_execute($this->db_connection, 'smf_cache_put_data', [$key, $value, $ttl]);
+ }
return pg_affected_rows($result) > 0;
}
@@ -155,10 +169,11 @@ public function putData($key, $value, $ttl = null)
*/
public function cleanCache($type = '')
{
- if ($type == 'expired')
+ if ($type == 'expired') {
pg_query($this->db_connection, 'DELETE FROM ' . $this->db_prefix . 'cache WHERE ttl < ' . time() . ';');
- else
+ } else {
pg_query($this->db_connection, 'TRUNCATE ' . $this->db_prefix . 'cache');
+ }
$this->invalidateCache();
@@ -187,7 +202,6 @@ public function housekeeping()
/**
* Create the temp table of valid data.
*
- * @return void
*/
private function createTempTable()
{
@@ -197,7 +211,6 @@ private function createTempTable()
/**
* Delete the temp table.
*
- * @return void
*/
private function deleteTempTable()
{
@@ -207,7 +220,6 @@ private function deleteTempTable()
/**
* Retrieve the valid data from temp table.
*
- * @return void
*/
private function retrieveData()
{
diff --git a/Sources/Cache/APIs/Sqlite.php b/Sources/Cache/APIs/Sqlite.php
index bef28c2dee..6a70cce0ac 100755
--- a/Sources/Cache/APIs/Sqlite.php
+++ b/Sources/Cache/APIs/Sqlite.php
@@ -13,15 +13,16 @@
namespace SMF\Cache\APIs;
+use SMF\Cache\CacheApi;
+use SMF\Cache\CacheApiInterface;
use SMF\Config;
use SMF\Lang;
use SMF\Utils;
-use SMF\Cache\CacheApi;
-use SMF\Cache\CacheApiInterface;
use SQLite3;
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
/**
* SQLite Cache API class
@@ -31,7 +32,7 @@
class Sqlite extends CacheApi implements CacheApiInterface
{
/**
- * @var string The path to the current $cachedir directory.
+ * @var string The path to the current directory.
*/
private $cachedir = null;
@@ -56,8 +57,8 @@ public function connect()
$database = $this->cachedir . '/' . 'SQLite3Cache.db3';
$this->cacheDB = new SQLite3($database);
$this->cacheDB->busyTimeout(1000);
- if (filesize($database) == 0)
- {
+
+ if (filesize($database) == 0) {
$this->cacheDB->exec('CREATE TABLE cache (key text unique, value blob, ttl int);');
$this->cacheDB->exec('CREATE INDEX ttls ON cache(ttl);');
}
@@ -68,10 +69,11 @@ public function connect()
*/
public function isSupported($test = false)
{
- $supported = class_exists("SQLite3") && is_writable($this->cachedir);
+ $supported = class_exists('SQLite3') && is_writable($this->cachedir);
- if ($test)
+ if ($test) {
return $supported;
+ }
return parent::isSupported() && $supported;
}
@@ -85,8 +87,10 @@ public function getData($key, $ttl = null)
$result = $this->cacheDB->query($query);
$value = null;
- while ($res = $result->fetchArray(SQLITE3_ASSOC))
+
+ while ($res = $result->fetchArray(SQLITE3_ASSOC)) {
$value = $res['value'];
+ }
return !empty($value) ? $value : null;
}
@@ -97,10 +101,12 @@ public function getData($key, $ttl = null)
public function putData($key, $value, $ttl = null)
{
$ttl = time() + (int) ($ttl !== null ? $ttl : $this->ttl);
- if ($value === null)
+
+ if ($value === null) {
$query = 'DELETE FROM cache WHERE key = \'' . $this->cacheDB->escapeString($key) . '\';';
- else
+ } else {
$query = 'REPLACE INTO cache VALUES (\'' . $this->cacheDB->escapeString($key) . '\', \'' . $this->cacheDB->escapeString($value) . '\', ' . $ttl . ');';
+ }
$result = $this->cacheDB->exec($query);
return $result;
@@ -111,10 +117,11 @@ public function putData($key, $value, $ttl = null)
*/
public function cleanCache($type = '')
{
- if ($type == 'expired')
+ if ($type == 'expired') {
$query = 'DELETE FROM cache WHERE ttl < ' . time() . ';';
- else
+ } else {
$query = 'DELETE FROM cache;';
+ }
$result = $this->cacheDB->exec($query);
@@ -134,52 +141,50 @@ public function cacheSettings(array &$config_vars)
$class_name = $this->getImplementationClassKeyName();
$class_name_txt_key = strtolower($class_name);
- $config_vars[] = Lang::$txt['cache_'. $class_name_txt_key .'_settings'];
- $config_vars[] = array(
- 'cachedir_'. $class_name_txt_key,
- Lang::$txt['cachedir_'. $class_name_txt_key],
+ $config_vars[] = Lang::$txt['cache_' . $class_name_txt_key . '_settings'];
+ $config_vars[] = [
+ 'cachedir_' . $class_name_txt_key,
+ Lang::$txt['cachedir_' . $class_name_txt_key],
'file',
'text',
36,
- 'cache_'. $class_name_txt_key .'_cachedir',
- );
+ 'cache_' . $class_name_txt_key . '_cachedir',
+ ];
- if (!isset(Utils::$context['settings_post_javascript']))
+ if (!isset(Utils::$context['settings_post_javascript'])) {
Utils::$context['settings_post_javascript'] = '';
+ }
- if (empty(Utils::$context['settings_not_writable']))
+ if (empty(Utils::$context['settings_not_writable'])) {
Utils::$context['settings_post_javascript'] .= '
$("#cache_accelerator").change(function (e) {
var cache_type = e.currentTarget.value;
- $("#cachedir_'. $class_name_txt_key .'").prop("disabled", cache_type != "'. $class_name .'");
+ $("#cachedir_' . $class_name_txt_key . '").prop("disabled", cache_type != "' . $class_name . '");
});';
+ }
}
/**
* Sets the $cachedir or uses the SMF default $cachedir..
*
- * @access public
- *
* @param string $dir A valid path
*
- * @return boolean If this was successful or not.
+ * @return bool If this was successful or not.
*/
public function setCachedir($dir = null)
{
// If its invalid, use SMF's.
- if (!isset($dir) || !is_writable($dir))
- {
- if (!isset(Config::$cachedir_sqlite) || !is_writable(Config::$cachedir_sqlite))
- {
+ if (!isset($dir) || !is_writable($dir)) {
+ if (!isset(Config::$cachedir_sqlite) || !is_writable(Config::$cachedir_sqlite)) {
Config::$cachedir_sqlite = Config::$cachedir;
- Config::updateSettingsFile(array('cachedir_sqlite' => Config::$cachedir_sqlite));
+ Config::updateSettingsFile(['cachedir_sqlite' => Config::$cachedir_sqlite]);
}
$this->cachedir = Config::$cachedir_sqlite;
- }
- else
+ } else {
$this->cachedir = $dir;
+ }
}
/**
@@ -187,8 +192,9 @@ public function setCachedir($dir = null)
*/
public function getVersion()
{
- if (null == $this->cacheDB)
+ if (null == $this->cacheDB) {
$this->connect();
+ }
return $this->cacheDB->version()['versionString'];
}
diff --git a/Sources/Cache/APIs/Zend.php b/Sources/Cache/APIs/Zend.php
index c409162022..88e8af7911 100644
--- a/Sources/Cache/APIs/Zend.php
+++ b/Sources/Cache/APIs/Zend.php
@@ -16,8 +16,9 @@
use SMF\Cache\CacheApi;
use SMF\Cache\CacheApiInterface;
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
/**
* Our Cache API class
@@ -33,8 +34,9 @@ public function isSupported($test = false)
{
$supported = function_exists('zend_shm_cache_fetch') || function_exists('output_cache_get');
- if ($test)
+ if ($test) {
return $supported;
+ }
return parent::isSupported() && $supported;
}
@@ -52,11 +54,13 @@ public function getData($key, $ttl = null)
$key = $this->prefix . strtr($key, ':/', '-_');
// Zend's pricey stuff.
- if (function_exists('zend_shm_cache_fetch'))
+ if (function_exists('zend_shm_cache_fetch')) {
return zend_shm_cache_fetch('SMF::' . $key);
+ }
- elseif (function_exists('output_cache_get'))
+ if (function_exists('output_cache_get')) {
return output_cache_get($key, $ttl);
+ }
}
/**
@@ -66,11 +70,13 @@ public function putData($key, $value, $ttl = null)
{
$key = $this->prefix . strtr($key, ':/', '-_');
- if (function_exists('zend_shm_cache_store'))
+ if (function_exists('zend_shm_cache_store')) {
return zend_shm_cache_store('SMF::' . $key, $value, $ttl);
+ }
- elseif (function_exists('output_cache_put'))
+ if (function_exists('output_cache_put')) {
return output_cache_put($key, $value);
+ }
}
/**
diff --git a/Sources/Cache/APIs/index.php b/Sources/Cache/APIs/index.php
index 69278ce68e..976d292448 100644
--- a/Sources/Cache/APIs/index.php
+++ b/Sources/Cache/APIs/index.php
@@ -1,8 +1,8 @@
array(
+ private static $backcompat = [
+ 'func_names' => [
'load' => 'loadCacheAccelerator',
'detect' => 'loadCacheAPIs',
'clean' => 'clean_cache',
'quickGet' => 'cache_quick_get',
'put' => 'cache_put_data',
'get' => 'cache_get_data',
- ),
- 'prop_names' => array(
+ ],
+ 'prop_names' => [
'loadedApi' => 'cacheAPI',
'hits' => 'cache_hits',
'count_hits' => 'cache_count',
'misses' => 'cache_misses',
'count_misses' => 'cache_count_misses',
- ),
- );
+ ],
+ ];
/**************************
* Public static properties
@@ -88,7 +87,7 @@ abstract class CacheApi
*
* For backward compatibilty, also referenced as global $cache_hits.
*/
- public static array $hits = array();
+ public static array $hits = [];
/**
* @var int
@@ -106,7 +105,7 @@ abstract class CacheApi
*
* For backward compatibilty, also referenced as global $cache_misses.
*/
- public static array $misses = array();
+ public static array $misses = [];
/**
* @var int
@@ -148,7 +147,6 @@ abstract class CacheApi
/**
* Does basic setup of a cache method when we create the object but before we call connect.
*
- * @access public
*/
public function __construct()
{
@@ -158,14 +156,14 @@ public function __construct()
/**
* Checks whether we can use the cache method performed by this API.
*
- * @access public
* @param bool $test Test if this is supported or enabled.
* @return bool Whether or not the cache is supported
*/
public function isSupported($test = false)
{
- if ($test)
+ if ($test) {
return true;
+ }
return !empty(self::$enable);
}
@@ -173,37 +171,33 @@ public function isSupported($test = false)
/**
* Sets the cache prefix.
*
- * @access public
* @param string $prefix The prefix to use.
* If empty, the prefix will be generated automatically.
* @return bool If this was successful or not.
*/
public function setPrefix($prefix = '')
{
- if (!is_string($prefix))
+ if (!is_string($prefix)) {
$prefix = '';
+ }
// Use the supplied prefix, if there is one.
- if (!empty($prefix))
- {
+ if (!empty($prefix)) {
$this->prefix = $prefix;
return true;
}
// Ideally the prefix should reflect the last time the cache was reset.
- if (!empty(Config::$cachedir) && file_exists(Config::$cachedir . '/index.php'))
- {
+ if (!empty(Config::$cachedir) && file_exists(Config::$cachedir . '/index.php')) {
$mtime = filemtime(Config::$cachedir . '/index.php');
}
// Fall back to the last time that Settings.php was updated.
- elseif (!empty(Config::$boarddir) && file_exists(SMF_SETTINGS_FILE))
- {
+ elseif (!empty(Config::$boarddir) && file_exists(SMF_SETTINGS_FILE)) {
$mtime = filemtime(SMF_SETTINGS_FILE);
}
// This should never happen, but just in case...
- else
- {
+ else {
$mtime = filemtime(realpath($_SERVER['SCRIPT_FILENAME']));
}
@@ -215,7 +209,6 @@ public function setPrefix($prefix = '')
/**
* Gets the prefix as defined from set or the default.
*
- * @access public
* @return string the value of $key.
*/
public function getPrefix()
@@ -226,7 +219,6 @@ public function getPrefix()
/**
* Sets a default Time To Live, if this isn't specified we let the class define it.
*
- * @access public
* @param int $ttl The default TTL
* @return bool If this was successful or not.
*/
@@ -240,7 +232,6 @@ public function setDefaultTTL($ttl = 120)
/**
* Gets the TTL as defined from set or the default.
*
- * @access public
* @return int the value of $ttl.
*/
public function getDefaultTTL()
@@ -257,8 +248,9 @@ public function invalidateCache()
{
// Invalidate cache, to be sure!
// ... as long as index.php can be modified, anyway.
- if (is_writable(Config::$cachedir . '/' . 'index.php'))
+ if (is_writable(Config::$cachedir . '/' . 'index.php')) {
@touch(Config::$cachedir . '/' . 'index.php');
+ }
return true;
}
@@ -266,7 +258,6 @@ public function invalidateCache()
/**
* Closes connections to the cache method.
*
- * @access public
* @return bool Whether the connections were closed.
*/
public function quit()
@@ -277,7 +268,6 @@ public function quit()
/**
* Specify custom settings that the cache API supports.
*
- * @access public
* @param array $config_vars Additional config_vars, see ManageSettings.php for usage.
*/
public function cacheSettings(array &$config_vars)
@@ -287,7 +277,6 @@ public function cacheSettings(array &$config_vars)
/**
* Gets the latest version of SMF this is compatible with.
*
- * @access public
* @return string the value of $key.
*/
public function getCompatibleVersion()
@@ -298,7 +287,6 @@ public function getCompatibleVersion()
/**
* Gets the min version that we support.
*
- * @access public
* @return string the value of $key.
*/
public function getMinimumVersion()
@@ -309,7 +297,6 @@ public function getMinimumVersion()
/**
* Gets the Version of the Caching API.
*
- * @access public
* @return string the value of $key.
*/
public function getVersion()
@@ -321,8 +308,6 @@ public function getVersion()
* Run housekeeping of this cache
* exp. clean up old data or do optimization
*
- * @access public
- * @return void
*/
public function housekeeping()
{
@@ -331,18 +316,17 @@ public function housekeeping()
/**
* Gets the class identifier of the current caching API implementation.
*
- * @access public
* @return string the unique identifier for the current class implementation.
*/
public function getImplementationClassKeyName()
{
$class_name = get_class($this);
- if ($position = strrpos($class_name, '\\'))
+ if ($position = strrpos($class_name, '\\')) {
return substr($class_name, $position + 1);
+ }
- else
- return get_class($this);
+ return get_class($this);
}
/***********************
@@ -361,22 +345,27 @@ public function getImplementationClassKeyName()
*/
final public static function load($overrideCache = '', $fallbackSMF = true)
{
- if (!isset(self::$enable))
+ if (!isset(self::$enable)) {
self::$enable = min(max((int) Config::$cache_enable, 0), 3);
+ }
- if (!isset(self::$accelerator))
+ if (!isset(self::$accelerator)) {
self::$accelerator = Config::$cache_accelerator;
+ }
// Is caching enabled?
- if (empty(self::$enable) && empty($overrideCache))
+ if (empty(self::$enable) && empty($overrideCache)) {
return false;
+ }
// Not overriding this and we have a cacheAPI, send it back.
- if (empty($overrideCache) && is_object(self::$loadedApi))
+ if (empty($overrideCache) && is_object(self::$loadedApi)) {
return self::$loadedApi;
+ }
- elseif (is_null(self::$loadedApi))
+ if (is_null(self::$loadedApi)) {
self::$loadedApi = false;
+ }
// What accelerator we are going to try.
$cache_class_name = !empty(self::$accelerator) ? self::$accelerator : self::APIS_DEFAULT;
@@ -385,35 +374,39 @@ final public static function load($overrideCache = '', $fallbackSMF = true)
// Do some basic tests.
$cache_api = false;
- if (class_exists($fully_qualified_class_name))
- {
+
+ if (class_exists($fully_qualified_class_name)) {
$cache_api = new $fully_qualified_class_name();
// There are rules you know...
- if (!($cache_api instanceof CacheApiInterface) || !($cache_api instanceof CacheApi))
+ if (!($cache_api instanceof CacheApiInterface) || !($cache_api instanceof CacheApi)) {
$cache_api = false;
+ }
// No Support? NEXT!
- if ($cache_api && !$cache_api->isSupported())
- {
+ if ($cache_api && !$cache_api->isSupported()) {
// Can we save ourselves?
- if (!empty($fallbackSMF) && $overrideCache == '' && $cache_class_name !== self::APIS_DEFAULT)
+ if (!empty($fallbackSMF) && $overrideCache == '' && $cache_class_name !== self::APIS_DEFAULT) {
return self::load(self::APIS_NAMESPACE . self::APIS_DEFAULT, false);
+ }
$cache_api = false;
}
// Connect up to the accelerator.
- if ($cache_api && $cache_api->connect() === false)
+ if ($cache_api && $cache_api->connect() === false) {
$cache_api = false;
+ }
// Don't set this if we are overriding the cache.
- if ($cache_api && empty($overrideCache))
+ if ($cache_api && empty($overrideCache)) {
self::$loadedApi = $cache_api;
+ }
}
- if (!$cache_api && !empty($fallbackSMF) && $overrideCache == '' && $cache_class_name !== self::APIS_DEFAULT)
+ if (!$cache_api && !empty($fallbackSMF) && $overrideCache == '' && $cache_class_name !== self::APIS_DEFAULT) {
$cache_api = self::load(self::APIS_NAMESPACE . self::APIS_DEFAULT, false);
+ }
return $cache_api;
}
@@ -423,33 +416,35 @@ final public static function load($overrideCache = '', $fallbackSMF = true)
*/
final public static function detect()
{
- $loadedApis = array();
+ $loadedApis = [];
$api_classes = new \GlobIterator(self::APIS_FOLDER . '/*.php', \FilesystemIterator::NEW_CURRENT_AND_KEY);
- foreach ($api_classes as $file_path => $file_info)
- {
+ foreach ($api_classes as $file_path => $file_info) {
$class_name = $file_info->getBasename('.php');
$fully_qualified_class_name = self::APIS_NAMESPACE . $class_name;
- if (!class_exists($fully_qualified_class_name))
+ if (!class_exists($fully_qualified_class_name)) {
continue;
+ }
/* @var CacheApiInterface $cache_api */
$cache_api = new $fully_qualified_class_name();
// Deal with it!
- if (!($cache_api instanceof CacheApiInterface) || !($cache_api instanceof CacheApi))
+ if (!($cache_api instanceof CacheApiInterface) || !($cache_api instanceof CacheApi)) {
continue;
+ }
// No Support? NEXT!
- if (!$cache_api->isSupported(true))
+ if (!$cache_api->isSupported(true)) {
continue;
+ }
$loadedApis[$class_name] = $cache_api;
}
- IntegrationHook::call('integrate_load_cache_apis', array(&$loadedApis));
+ IntegrationHook::call('integrate_load_cache_apis', [&$loadedApis]);
return $loadedApis;
}
@@ -469,8 +464,9 @@ final public static function detect()
final public static function clean($type = '')
{
// If we can't get to the API, can't do this.
- if (empty(self::$loadedApi))
+ if (empty(self::$loadedApi)) {
return;
+ }
// Ask the API to do the heavy lifting. cleanCache also calls invalidateCache to be sure.
self::$loadedApi->cleanCache($type);
@@ -492,8 +488,9 @@ final public static function clean($type = '')
*/
final public static function quickGet($key, $file, $function, $params, $level = 1)
{
- if (class_exists('SMF\\IntegrationHook', false))
- IntegrationHook::call('pre_cache_quick_get', array(&$key, &$file, &$function, &$params, &$level));
+ if (class_exists('SMF\\IntegrationHook', false)) {
+ IntegrationHook::call('pre_cache_quick_get', [&$key, &$file, &$function, &$params, &$level]);
+ }
/* Refresh the cache if either:
1. Caching is disabled.
@@ -502,23 +499,26 @@ final public static function quickGet($key, $file, $function, $params, $level =
4. The cached item has a custom expiration condition evaluating to true.
5. The expire time set in the cache item has passed (needed for Zend).
*/
- if (empty(self::$enable) || self::$enable < $level || !is_array($cache_block = self::get($key, 3600)) || (!empty($cache_block['refresh_eval']) && eval($cache_block['refresh_eval'])) || (!empty($cache_block['expires']) && $cache_block['expires'] < time()))
- {
- if (!empty($file) && is_file(Config::$sourcedir . '/' . $file))
- require_once(Config::$sourcedir . '/' . $file);
+ if (empty(self::$enable) || self::$enable < $level || !is_array($cache_block = self::get($key, 3600)) || (!empty($cache_block['refresh_eval']) && eval($cache_block['refresh_eval'])) || (!empty($cache_block['expires']) && $cache_block['expires'] < time())) {
+ if (!empty($file) && is_file(Config::$sourcedir . '/' . $file)) {
+ require_once Config::$sourcedir . '/' . $file;
+ }
$cache_block = call_user_func_array($function, $params);
- if (!empty(self::$enable) && self::$enable >= $level)
+ if (!empty(self::$enable) && self::$enable >= $level) {
self::put($key, $cache_block, $cache_block['expires'] - time());
+ }
}
// Some cached data may need a freshening up after retrieval.
- if (!empty($cache_block['post_retri_eval']))
+ if (!empty($cache_block['post_retri_eval'])) {
eval($cache_block['post_retri_eval']);
+ }
- if (class_exists('SMF\\IntegrationHook', false))
- IntegrationHook::call('post_cache_quick_get', array(&$cache_block));
+ if (class_exists('SMF\\IntegrationHook', false)) {
+ IntegrationHook::call('post_cache_quick_get', [&$cache_block]);
+ }
return $cache_block['data'];
}
@@ -540,13 +540,14 @@ final public static function quickGet($key, $file, $function, $params, $level =
*/
final public static function put($key, $value, $ttl = 120)
{
- if (empty(self::$enable) || empty(self::$loadedApi))
+ if (empty(self::$enable) || empty(self::$loadedApi)) {
return;
+ }
self::$count_hits++;
- if (isset(Config::$db_show_debug) && Config::$db_show_debug === true)
- {
- self::$hits[self::$count_hits] = array('k' => $key, 'd' => 'put', 's' => $value === null ? 0 : strlen(Utils::jsonEncode($value)));
+
+ if (isset(Config::$db_show_debug) && Config::$db_show_debug === true) {
+ self::$hits[self::$count_hits] = ['k' => $key, 'd' => 'put', 's' => $value === null ? 0 : strlen(Utils::jsonEncode($value))];
$st = microtime(true);
}
@@ -554,11 +555,13 @@ final public static function put($key, $value, $ttl = 120)
$value = $value === null ? null : Utils::jsonEncode($value);
self::$loadedApi->putData($key, $value, $ttl);
- if (class_exists('SMF\\IntegrationHook', false))
- IntegrationHook::call('cache_put_data', array(&$key, &$value, &$ttl));
+ if (class_exists('SMF\\IntegrationHook', false)) {
+ IntegrationHook::call('cache_put_data', [&$key, &$value, &$ttl]);
+ }
- if (isset(Config::$db_show_debug) && Config::$db_show_debug === true)
+ if (isset(Config::$db_show_debug) && Config::$db_show_debug === true) {
self::$hits[self::$count_hits]['t'] = microtime(true) - $st;
+ }
}
/**
@@ -572,13 +575,14 @@ final public static function put($key, $value, $ttl = 120)
*/
final public static function get($key, $ttl = 120)
{
- if (empty(self::$enable) || empty(self::$loadedApi))
- return null;
+ if (empty(self::$enable) || empty(self::$loadedApi)) {
+ return;
+ }
self::$count_hits++;
- if (isset(Config::$db_show_debug) && Config::$db_show_debug === true)
- {
- self::$hits[self::$count_hits] = array('k' => $key, 'd' => 'get');
+
+ if (isset(Config::$db_show_debug) && Config::$db_show_debug === true) {
+ self::$hits[self::$count_hits] = ['k' => $key, 'd' => 'get'];
$st = microtime(true);
$original_key = $key;
}
@@ -586,27 +590,27 @@ final public static function get($key, $ttl = 120)
// Ask the API to get the data.
$value = self::$loadedApi->getData($key, $ttl);
- if (isset(Config::$db_show_debug) && Config::$db_show_debug === true)
- {
+ if (isset(Config::$db_show_debug) && Config::$db_show_debug === true) {
self::$hits[self::$count_hits]['t'] = microtime(true) - $st;
self::$hits[self::$count_hits]['s'] = isset($value) ? strlen($value) : 0;
- if (empty($value))
- {
+ if (empty($value)) {
self::$count_misses++;
- self::$misses[self::$count_misses] = array('k' => $original_key, 'd' => 'get');
+ self::$misses[self::$count_misses] = ['k' => $original_key, 'd' => 'get'];
}
}
- if (class_exists('SMF\\IntegrationHook', false) && isset($value))
- IntegrationHook::call('cache_get_data', array(&$key, &$ttl, &$value));
+ if (class_exists('SMF\\IntegrationHook', false) && isset($value)) {
+ IntegrationHook::call('cache_get_data', [&$key, &$ttl, &$value]);
+ }
return empty($value) ? null : Utils::jsonDecode($value, true);
}
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\CacheApi::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\CacheApi::exportStatic')) {
CacheApi::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Cache/CacheApiInterface.php b/Sources/Cache/CacheApiInterface.php
index c806278353..99d89d6a29 100644
--- a/Sources/Cache/CacheApiInterface.php
+++ b/Sources/Cache/CacheApiInterface.php
@@ -13,16 +13,15 @@
namespace SMF\Cache;
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
-
+}
interface CacheApiInterface
{
/**
* Checks whether we can use the cache method performed by this API.
*
- * @access public
* @param bool $test Test if this is supported or enabled.
* @return bool Whether or not the cache is supported
*/
@@ -31,7 +30,6 @@ public function isSupported($test = false);
/**
* Connects to the cache method. This defines our $key. If this fails, we return false, otherwise we return true.
*
- * @access public
* @return bool Whether or not the cache method was connected to.
*/
public function connect();
@@ -39,7 +37,6 @@ public function connect();
/**
* Retrieves an item from the cache.
*
- * @access public
* @param string $key The key to use, the prefix is applied to the key name.
* @param int $ttl Overrides the default TTL. Not really used anymore,
* but is kept for backwards compatibility.
@@ -52,7 +49,6 @@ public function getData($key, $ttl = null);
* Stores a value, regardless of whether or not the key already exists (in
* which case it will overwrite the existing value for that key).
*
- * @access public
* @param string $key The key to use, the prefix is applied to the key name.
* @param mixed $value The data we wish to save. Use null to delete.
* @param int $ttl How long (in seconds) the data should be cached for.
@@ -73,7 +69,6 @@ public function cleanCache($type = '');
/**
* Gets the class identifier of the current caching API implementation.
*
- * @access public
* @return string the unique identifier for the current class implementation.
*/
public function getImplementationClassKeyName();
diff --git a/Sources/Cache/index.php b/Sources/Cache/index.php
index 69278ce68e..976d292448 100644
--- a/Sources/Cache/index.php
+++ b/Sources/Cache/index.php
@@ -1,8 +1,8 @@
array(
- 'load' => false,
- 'init' => false,
+ private static $backcompat = [
+ 'func_names' => [
'modify' => 'modifyCategory',
'create' => 'createCategory',
'delete' => 'deleteCategories',
'sort' => 'sortCategories',
+ 'getTreeOrder' => 'getTreeOrder',
'getTree' => 'getBoardTree',
- 'setParsedDescriptions' => 'setCategoryParsedDescription',
- 'getParsedDescriptions' => 'getCategoriesParsedDescription',
- ),
- 'prop_names' => array(
+ 'recursiveBoards' => 'recursiveBoards',
+ ],
+ 'prop_names' => [
'loaded' => 'cat_tree',
'boardList' => 'boardList',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -111,7 +110,7 @@ class Category implements \ArrayAccess
*
* Boards that are children of this category.
*/
- public array $children = array();
+ public array $children = [];
/**
* @var string
@@ -165,14 +164,14 @@ class Category implements \ArrayAccess
*
* All loaded instances of this class.
*/
- public static array $loaded = array();
+ public static array $loaded = [];
/**
* @var array
*
* A list of boards grouped by category ID.
*/
- public static array $boardList = array();
+ public static array $boardList = [];
/*********************
* Internal properties
@@ -183,12 +182,12 @@ class Category implements \ArrayAccess
*
* Alternate names for some object properties.
*/
- protected array $prop_aliases = array(
+ protected array $prop_aliases = [
'id_cat' => 'id',
'cat_order' => 'order',
'href' => 'url',
'boards' => 'children',
- );
+ ];
/****************************
* Internal static properties
@@ -199,17 +198,17 @@ class Category implements \ArrayAccess
*
* Holds results of Category::getTreeOrder().
*/
- protected static array $tree_order = array(
- 'cats' => array(),
- 'boards' => array(),
- );
+ protected static array $tree_order = [
+ 'cats' => [],
+ 'boards' => [],
+ ];
/**
* @var array
*
* Holds parsed versions of category descriptions.
*/
- protected static array $parsed_descriptions = array();
+ protected static array $parsed_descriptions = [];
/****************
* Public methods
@@ -220,29 +219,28 @@ class Category implements \ArrayAccess
*/
public function parseDescription(): void
{
- if (empty($this->description))
+ if (empty($this->description)) {
return;
+ }
// Save the unparsed description in case we need it later.
- if (!isset($this->custom['unparsed_description']))
+ if (!isset($this->custom['unparsed_description'])) {
$this->custom['unparsed_description'] = $this->description;
+ }
- if (!empty(CacheApi::$enable))
- {
- if (empty(self::$parsed_descriptions))
- self::$parsed_descriptions = CacheApi::get('parsed_category_descriptions', 864000) ?? array();
+ if (!empty(CacheApi::$enable)) {
+ if (empty(self::$parsed_descriptions)) {
+ self::$parsed_descriptions = CacheApi::get('parsed_category_descriptions', 864000) ?? [];
+ }
- if (!isset(self::$parsed_descriptions[$this->id]))
- {
+ if (!isset(self::$parsed_descriptions[$this->id])) {
self::$parsed_descriptions[$this->id] = BBCodeParser::load()->parse($this->description, false, '', Utils::$context['description_allowed_tags']);
CacheApi::put('parsed_category_descriptions', self::$parsed_descriptions, 864000);
}
$this->description = self::$parsed_descriptions[$this->id];
- }
- else
- {
+ } else {
$this->description = BBCodeParser::load()->parse($this->description, false, '', Utils::$context['description_allowed_tags']);
}
}
@@ -252,8 +250,9 @@ public function parseDescription(): void
*/
public function unparseDescription(): void
{
- if (isset($this->custom['unparsed_description']))
+ if (isset($this->custom['unparsed_description'])) {
$this->description = $this->custom['unparsed_description'];
+ }
}
/***********************
@@ -263,46 +262,38 @@ public function unparseDescription(): void
/**
* Loads categories by ID number and/or by custom query.
*
- * If both arguments are empty, loads nothing.
+ * If both arguments are empty, loads all categories.
*
- * @param array|int $ids The ID numbers of zero or more boards.
+ * @param array|int $ids The ID numbers of zero or more categories.
* @param array $query_customizations Customizations to the SQL query.
- * @return array Instances of this class for the loaded boards.
+ * @return array Instances of this class for the loaded categories.
*/
- public static function load(array|int $ids = array(), array $query_customizations = array()): array
+ public static function load(array|int $ids = [], array $query_customizations = []): array
{
- $loaded = array();
+ $loaded = [];
$ids = array_unique(array_map('intval', (array) $ids));
- if (empty($query_customizations) && empty($ids))
- return $loaded;
-
- $selects = $query_customizations['selects'] ?? array('c.*');
- $joins = $query_customizations['joins'] ?? array();
- $where = $query_customizations['where'] ?? array();
- $order = $query_customizations['order'] ?? array();
- $group = $query_customizations['group'] ?? array();
+ $selects = $query_customizations['selects'] ?? ['c.*'];
+ $joins = $query_customizations['joins'] ?? [];
+ $where = $query_customizations['where'] ?? [];
+ $order = $query_customizations['order'] ?? ['c.cat_order'];
+ $group = $query_customizations['group'] ?? [];
$limit = $query_customizations['limit'] ?? 0;
- $params = $query_customizations['params'] ?? array();
+ $params = $query_customizations['params'] ?? [];
- if ($ids !== array())
- {
+ if ($ids !== []) {
$where[] = 'c.id_cat IN ({array_int:ids})';
$params['ids'] = $ids;
}
- foreach (Board::queryData($selects, $params, $joins, $where, $order, $group, $limit) as $row)
- {
+ foreach (self::queryData($selects, $params, $joins, $where, $order, $group, $limit) as $row) {
$row['id_cat'] = (int) $row['id_cat'];
- if (isset(self::$loaded[$row['id_cat']]))
- {
+ if (isset(self::$loaded[$row['id_cat']])) {
self::$loaded[$row['id_cat']]->set($row);
$loaded[] = self::$loaded[$row['id_cat']];
- }
- else
- {
+ } else {
$loaded[] = self::init($row['id_cat'], $row);
}
}
@@ -328,14 +319,11 @@ public static function load(array|int $ids = array(), array $query_customization
* @param array $props Array of properties to set.
* @return object An instance of this class.
*/
- public static function init(int $id, array $props = array()): object
+ public static function init(int $id, array $props = []): object
{
- if (!isset(self::$loaded[$id]))
- {
+ if (!isset(self::$loaded[$id])) {
new self($id, $props);
- }
- else
- {
+ } else {
self::$loaded[$id]->set($props);
}
@@ -352,56 +340,58 @@ public static function init(int $id, array $props = array()): object
*/
public static function modify(int $category_id, array $catOptions): void
{
- $catUpdates = array();
- $catParameters = array();
+ $catUpdates = [];
+ $catParameters = [];
$cat_id = $category_id;
- IntegrationHook::call('integrate_pre_modify_category', array($cat_id, &$catOptions));
+ IntegrationHook::call('integrate_pre_modify_category', [$cat_id, &$catOptions]);
// Wanna change the categories position?
- if (isset($catOptions['move_after']))
- {
+ if (isset($catOptions['move_after'])) {
// Store all categories in the proper order.
- $cats = array();
- $cat_order = array();
+ $cats = [];
+ $cat_order = [];
// Setting 'move_after' to '0' moves the category to the top.
- if ($catOptions['move_after'] == 0)
+ if ($catOptions['move_after'] == 0) {
$cats[] = $category_id;
+ }
// Grab the categories sorted by cat_order.
- $request = Db::$db->query('', '
- SELECT id_cat, cat_order
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_cat, cat_order
FROM {db_prefix}categories
ORDER BY cat_order',
- array(
- )
+ [
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- if ($row['id_cat'] != $category_id)
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if ($row['id_cat'] != $category_id) {
$cats[] = $row['id_cat'];
+ }
- if ($row['id_cat'] == $catOptions['move_after'])
+ if ($row['id_cat'] == $catOptions['move_after']) {
$cats[] = $category_id;
+ }
$cat_order[$row['id_cat']] = $row['cat_order'];
}
Db::$db->free_result($request);
// Set the new order for the categories.
- foreach ($cats as $index => $cat)
- {
- if ($index != $cat_order[$cat])
- {
- Db::$db->query('', '
- UPDATE {db_prefix}categories
+ foreach ($cats as $index => $cat) {
+ if ($index != $cat_order[$cat]) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}categories
SET cat_order = {int:new_order}
WHERE id_cat = {int:current_category}',
- array(
+ [
'new_order' => $index,
'current_category' => $cat,
- )
+ ],
);
}
}
@@ -410,48 +400,45 @@ public static function modify(int $category_id, array $catOptions): void
Board::reorder();
}
- if (isset($catOptions['cat_name']))
- {
+ if (isset($catOptions['cat_name'])) {
$catUpdates[] = 'name = {string:cat_name}';
$catParameters['cat_name'] = $catOptions['cat_name'];
}
- if (isset($catOptions['cat_desc']))
- {
+ if (isset($catOptions['cat_desc'])) {
$catUpdates[] = 'description = {string:cat_desc}';
$catParameters['cat_desc'] = $catOptions['cat_desc'];
- if (!empty(CacheApi::$enable))
+ if (!empty(CacheApi::$enable)) {
CacheApi::put('parsed_category_descriptions', null);
+ }
}
// Can a user collapse this category or is it too important?
- if (isset($catOptions['is_collapsible']))
- {
+ if (isset($catOptions['is_collapsible'])) {
$catUpdates[] = 'can_collapse = {int:is_collapsible}';
$catParameters['is_collapsible'] = $catOptions['is_collapsible'] ? 1 : 0;
}
$cat_id = $category_id;
- IntegrationHook::call('integrate_modify_category', array($cat_id, &$catUpdates, &$catParameters));
+ IntegrationHook::call('integrate_modify_category', [$cat_id, &$catUpdates, &$catParameters]);
// Do the updates (if any).
- if (!empty($catUpdates))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}categories
+ if (!empty($catUpdates)) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}categories
SET
' . implode(',
', $catUpdates) . '
WHERE id_cat = {int:current_category}',
- array_merge($catParameters, array(
+ array_merge($catParameters, [
'current_category' => $category_id,
- ))
+ ]),
);
- if (empty($catOptions['dont_log']))
- {
- Logging::logAction('edit_cat', array('catname' => isset($catOptions['cat_name']) ? $catOptions['cat_name'] : $category_id), 'admin');
+ if (empty($catOptions['dont_log'])) {
+ Logging::logAction('edit_cat', ['catname' => $catOptions['cat_name'] ?? $category_id], 'admin');
}
}
}
@@ -470,49 +457,52 @@ public static function modify(int $category_id, array $catOptions): void
public static function create(array $catOptions): int
{
// Check required values.
- if (!isset($catOptions['cat_name']) || trim($catOptions['cat_name']) == '')
- {
+ if (!isset($catOptions['cat_name']) || trim($catOptions['cat_name']) == '') {
Lang::load('Errors');
trigger_error(Lang::$txt['create_category_no_name'], E_USER_ERROR);
}
// Set default values.
- if (!isset($catOptions['cat_desc']))
+ if (!isset($catOptions['cat_desc'])) {
$catOptions['cat_desc'] = '';
+ }
- if (!isset($catOptions['move_after']))
+ if (!isset($catOptions['move_after'])) {
$catOptions['move_after'] = 0;
+ }
- if (!isset($catOptions['is_collapsible']))
+ if (!isset($catOptions['is_collapsible'])) {
$catOptions['is_collapsible'] = true;
+ }
// Don't log an edit right after.
$catOptions['dont_log'] = true;
- $cat_columns = array(
+ $cat_columns = [
'name' => 'string-48',
'description' => 'string',
- );
- $cat_parameters = array(
+ ];
+ $cat_parameters = [
$catOptions['cat_name'],
$catOptions['cat_desc'],
- );
+ ];
- IntegrationHook::call('integrate_create_category', array(&$catOptions, &$cat_columns, &$cat_parameters));
+ IntegrationHook::call('integrate_create_category', [&$catOptions, &$cat_columns, &$cat_parameters]);
// Add the category to the database.
- $category_id = Db::$db->insert('',
+ $category_id = Db::$db->insert(
+ '',
'{db_prefix}categories',
$cat_columns,
$cat_parameters,
- array('id_cat'),
- 1
+ ['id_cat'],
+ 1,
);
// Set the given properties to the newly created category.
self::modify($category_id, $catOptions);
- Logging::logAction('add_cat', array('catname' => $catOptions['cat_name']), 'admin');
+ Logging::logAction('add_cat', ['catname' => $catOptions['cat_name']], 'admin');
// Return the database ID of the category.
return $category_id;
@@ -529,67 +519,67 @@ public static function create(array $catOptions): int
* @param array $categories The IDs of the categories to delete
* @param int $moveBoardsTo The ID of the category to move any boards to or null to delete the boards
*/
- public static function delete(array $categories, int $moveBoardsTo = null): void
+ public static function delete(array $categories, ?int $moveBoardsTo = null): void
{
self::getTree();
- IntegrationHook::call('integrate_delete_category', array($categories, &$moveBoardsTo));
+ IntegrationHook::call('integrate_delete_category', [$categories, &$moveBoardsTo]);
// With no category set to move the boards to, delete them all.
- if ($moveBoardsTo === null)
- {
- $boards_inside = array();
+ if ($moveBoardsTo === null) {
+ $boards_inside = [];
- $request = Db::$db->query('', '
- SELECT id_board
+ $request = Db::$db->query(
+ '',
+ 'SELECT id_board
FROM {db_prefix}boards
WHERE id_cat IN ({array_int:category_list})',
- array(
+ [
'category_list' => $categories,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
+
+ while ($row = Db::$db->fetch_assoc($request)) {
$boards_inside[] = $row['id_board'];
}
Db::$db->free_result($request);
- if (!empty($boards_inside))
+ if (!empty($boards_inside)) {
Board::delete($boards_inside, null);
+ }
}
// Make sure the safe category is really safe.
- elseif (in_array($moveBoardsTo, $categories))
- {
+ elseif (in_array($moveBoardsTo, $categories)) {
Lang::load('Errors');
trigger_error(Lang::$txt['cannot_move_to_deleted_category'], E_USER_ERROR);
}
// Move the boards inside the categories to a safe category.
- else
- {
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ else {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET id_cat = {int:new_parent_cat}
WHERE id_cat IN ({array_int:category_list})',
- array(
+ [
'category_list' => $categories,
'new_parent_cat' => $moveBoardsTo,
- )
+ ],
);
}
// Do the deletion of the category itself
- Db::$db->query('', '
- DELETE FROM {db_prefix}categories
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}categories
WHERE id_cat IN ({array_int:category_list})',
- array(
+ [
'category_list' => $categories,
- )
+ ],
);
// Log what we've done.
- foreach ($categories as $category)
- {
- Logging::logAction('delete_cat', array('catname' => self::$loaded[$category]['node']['name']), 'admin');
+ foreach ($categories as $category) {
+ Logging::logAction('delete_cat', ['catname' => self::$loaded[$category]['node']['name']], 'admin');
}
// Get all boards back into the right order.
@@ -605,20 +595,15 @@ public static function sort(array &$categories): void
{
$tree = self::getTreeOrder();
- $ordered = array();
+ $ordered = [];
- foreach ($tree['cats'] as $cat)
- {
- if (!empty($categories[$cat]))
- {
+ foreach ($tree['cats'] as $cat) {
+ if (!empty($categories[$cat])) {
$ordered[$cat] = $categories[$cat];
- if (is_array($ordered[$cat]) && !empty($ordered[$cat]['boards']))
- {
+ if (is_array($ordered[$cat]) && !empty($ordered[$cat]['boards'])) {
Board::sort($ordered[$cat]['boards']);
- }
- elseif (is_object($ordered[$cat]) && !empty($ordered[$cat]->children))
- {
+ } elseif (is_object($ordered[$cat]) && !empty($ordered[$cat]->children)) {
Board::sort($ordered[$cat]->children);
}
}
@@ -635,25 +620,28 @@ public static function sort(array &$categories): void
*/
public static function getTreeOrder(): array
{
- if (!empty(self::$tree_order['boards']))
+ if (!empty(self::$tree_order['boards'])) {
return self::$tree_order;
+ }
- if (($cached = CacheApi::get('board_order', 86400)) !== null)
- {
+ if (($cached = CacheApi::get('board_order', 86400)) !== null) {
self::$tree_order = $cached;
+
return $cached;
}
- $request = Db::$db->query('', '
- SELECT b.id_board, b.id_cat
+ $request = Db::$db->query(
+ '',
+ 'SELECT b.id_board, b.id_cat
FROM {db_prefix}categories AS c
JOIN {db_prefix}boards AS b ON (b.id_cat = c.id_cat)
- ORDER BY c.cat_order, b.board_order'
+ ORDER BY c.cat_order, b.board_order',
);
- foreach (Db::$db->fetch_all($request) as $row)
- {
- if (!in_array($row['id_cat'], self::$tree_order['cats']))
+
+ foreach (Db::$db->fetch_all($request) as $row) {
+ if (!in_array($row['id_cat'], self::$tree_order['cats'])) {
self::$tree_order['cats'][] = $row['id_cat'];
+ }
self::$tree_order['boards'][] = $row['id_board'];
}
@@ -673,21 +661,21 @@ public static function getTreeOrder(): array
*/
public static function getTree(): void
{
- $selects = array(
+ $selects = [
'COALESCE(b.id_board, 0) AS id_board', 'b.name', 'b.description',
'b.id_parent', 'b.child_level', 'b.board_order', 'b.redirect',
'b.member_groups', 'b.deny_member_groups', 'b.id_profile',
'b.id_theme', 'b.override_theme', 'b.count_posts', 'b.num_posts',
'b.num_topics', 'c.id_cat', 'c.cat_order', 'c.can_collapse',
'c.name AS cat_name', 'c.description AS cat_desc',
- );
- $params = array();
- $joins = array('LEFT JOIN {db_prefix}categories AS c ON (b.id_cat = c.id_cat)');
- $where = array('{query_see_board}');
- $order = array('c.cat_order', 'b.child_level', 'b.board_order');
+ ];
+ $params = [];
+ $joins = ['LEFT JOIN {db_prefix}boards AS b ON (b.id_cat = c.id_cat)'];
+ $where = ['{query_see_board}'];
+ $order = ['c.cat_order', 'b.child_level', 'b.board_order'];
// Let mods add extra columns, parameters, etc., to the SELECT query
- IntegrationHook::call('integrate_pre_boardtree', array(&$selects, &$params, &$joins, &$where, &$order));
+ IntegrationHook::call('integrate_pre_boardtree', [&$selects, &$params, &$joins, &$where, &$order]);
$selects = array_unique($selects);
$params = array_unique($params);
@@ -696,20 +684,20 @@ public static function getTree(): void
$order = array_unique($order);
// Getting all the board and category information you'd ever wanted.
- self::$loaded = array();
+ self::$loaded = [];
$last_board_order = 0;
+ $prevBoard = 0;
+ $curLevel = 0;
- foreach (Board::queryData($selects, $params, $joins, $where, $order) as $row)
- {
- if (!isset(self::$loaded[$row['id_cat']]))
- {
- self::init($row['id_cat'], array(
+ foreach (self::queryData($selects, $params, $joins, $where, $order) as $row) {
+ if (!isset(self::$loaded[$row['id_cat']])) {
+ self::init($row['id_cat'], [
'name' => $row['cat_name'],
'description' => $row['cat_desc'],
'order' => $row['cat_order'],
'can_collapse' => $row['can_collapse'],
'last_board_order' => $last_board_order,
- ));
+ ]);
$prevBoard = 0;
$curLevel = 0;
}
@@ -718,10 +706,10 @@ public static function getTree(): void
unset($row['id_cat'], $row['cat_name'], $row['cat_desc'], $row['cat_order'], $row['can_collapse']);
- if (!empty($row['id_board']))
- {
- if ($row['child_level'] != $curLevel)
+ if (!empty($row['id_board'])) {
+ if ($row['child_level'] != $curLevel) {
$prevBoard = 0;
+ }
$row['member_groups'] = explode(',', $row['member_groups']);
$row['deny_member_groups'] = explode(',', $row['deny_member_groups']);
@@ -732,29 +720,27 @@ public static function getTree(): void
$prevBoard = $row['id_board'];
$last_board_order = $row['board_order'];
- if (empty($row['child_level']))
- {
+ if (empty($row['child_level'])) {
Board::$loaded[$row['id_board']]->is_first = empty(self::$loaded[$row['cat']->id]['children']);
self::$loaded[$row['cat']->id]->children[$row['id_board']] = Board::$loaded[$row['id_board']];
- }
- else
- {
+ } else {
// Parent doesn't exist!
- if (!isset(Board::$loaded[$row['id_parent']]))
- ErrorHandler::fatalLang('no_valid_parent', false, array($row['name']));
+ if (!isset(Board::$loaded[$row['id_parent']])) {
+ ErrorHandler::fatalLang('no_valid_parent', false, [$row['name']]);
+ }
// Wrong childlevel...we can silently fix this...
- if (Board::$loaded[$row['id_parent']]->child_level != $row['child_level'] - 1)
- {
- Db::$db->query('', '
- UPDATE {db_prefix}boards
+ if (Board::$loaded[$row['id_parent']]->child_level != $row['child_level'] - 1) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}boards
SET child_level = {int:new_child_level}
WHERE id_board = {int:selected_board}',
- array(
+ [
'new_child_level' => Board::$loaded[$row['id_parent']]->child_level + 1,
'selected_board' => $row['id_board'],
- )
+ ],
);
Board::$loaded[$row['id_board']]->child_level = Board::$loaded[$row['id_parent']]->child_level + 1;
@@ -766,15 +752,14 @@ public static function getTree(): void
}
// If mods want to do anything with this board before we move on, now's the time
- IntegrationHook::call('integrate_boardtree_board', array($row));
+ IntegrationHook::call('integrate_boardtree_board', [$row]);
}
// Get a list of all the boards in each category (using recursion).
- self::$boardList = array();
+ self::$boardList = [];
- foreach (self::$loaded as $id => $node)
- {
- self::$boardList[$id] = array();
+ foreach (self::$loaded as $id => $node) {
+ self::$boardList[$id] = [];
self::recursiveBoards(self::$boardList[$id], $node);
}
}
@@ -789,11 +774,11 @@ public static function getTree(): void
*/
public static function recursiveBoards(&$list, &$tree): void
{
- if (empty($tree->children))
+ if (empty($tree->children)) {
return;
+ }
- foreach ($tree->children as $child)
- {
+ foreach ($tree->children as $child) {
$list[] = $child->id;
self::recursiveBoards($list, $child);
}
@@ -816,22 +801,22 @@ public static function recursiveBoards(&$list, &$tree): void
* @param int $id The ID number of the category.
* @param array $props Array of properties to set.
*/
- protected function __construct(int $id, array $props = array())
+ protected function __construct(int $id, array $props = [])
{
// No props provided, so get the standard ones.
- if (empty($props))
- {
- $request = Db::$db->query('', '
- SELECT *
+ if (empty($props)) {
+ $request = Db::$db->query(
+ '',
+ 'SELECT *
FROM {db_prefix}categories
WHERE id_cat = {int:id}
LIMIT 1',
- array(
+ [
'id' => $id,
- )
+ ],
);
- if (Db::$db->num_rows($request) > 0)
- {
+
+ if (Db::$db->num_rows($request) > 0) {
$props = Db::$db->fetch_all($request);
}
Db::$db->free_result($request);
@@ -841,30 +826,74 @@ protected function __construct(int $id, array $props = array())
$this->set($props);
self::$loaded[$this->id] = $this;
- if (count(self::$loaded) > 1)
- {
+ if (count(self::$loaded) > 1) {
uasort(
self::$loaded,
- function ($a, $b)
- {
+ function ($a, $b) {
return ($a->order ?? 0) <=> ($b->order ?? 0);
- }
+ },
);
- foreach (self::$loaded as $id => $info)
+ foreach (self::$loaded as $id => $info) {
self::$loaded[$id]->is_first = false;
+ }
self::$loaded[array_key_first(self::$loaded)]->is_first = true;
- }
- else
- {
+ } else {
$this->is_first = true;
}
}
+
+ /*************************
+ * Internal static methods
+ *************************/
+
+ /**
+ * Generator that runs queries about category data and yields the result rows.
+ *
+ * @param array $selects Table columns to select.
+ * @param array $params Parameters to substitute into query text.
+ * @param array $joins Zero or more *complete* JOIN clauses.
+ * E.g.: 'LEFT JOIN {db_prefix}boards AS b ON (c.id_cat = b.id_cat)'
+ * Note: 'FROM {db_prefix}categories AS c' is always part of the query.
+ * @param array $where Zero or more conditions for the WHERE clause.
+ * Conditions will be placed in parentheses and concatenated with AND.
+ * If this is left empty, no WHERE clause will be used.
+ * @param array $order Zero or more conditions for the ORDER BY clause.
+ * If this is left empty, no ORDER BY clause will be used.
+ * @param array $group Zero or more conditions for the GROUP BY clause.
+ * If this is left empty, no GROUP BY clause will be used.
+ * @param int|string $limit Maximum number of results to retrieve.
+ * If this is left empty, all results will be retrieved.
+ *
+ * @return Generator Iterating over the result gives database rows.
+ */
+ protected static function queryData(array $selects, array $params = [], array $joins = [], array $where = [], array $order = [], array $group = [], int|string $limit = 0)
+ {
+ $request = Db::$db->query(
+ '',
+ 'SELECT
+ ' . implode(', ', $selects) . '
+ FROM {db_prefix}categories AS c' . (empty($joins) ? '' : '
+ ' . implode("\n\t\t\t\t", $joins)) . (empty($where) ? '' : '
+ WHERE (' . implode(') AND (', $where) . ')') . (empty($group) ? '' : '
+ GROUP BY ' . implode(', ', $group)) . (empty($order) ? '' : '
+ ORDER BY ' . implode(', ', $order)) . (!empty($limit) ? '
+ LIMIT ' . $limit : ''),
+ $params,
+ );
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ yield $row;
+ }
+
+ Db::$db->free_result($request);
+ }
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Category::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Category::exportStatic')) {
Category::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Class-BrowserDetect.php b/Sources/Class-BrowserDetect.php
index c13aa2df8b..4395fc95cc 100644
--- a/Sources/Class-BrowserDetect.php
+++ b/Sources/Class-BrowserDetect.php
@@ -13,8 +13,9 @@
* @version 3.0 Alpha 1
*/
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
class_alias('SMF\\BrowserDetector', '\\browser_detector');
diff --git a/Sources/Class-CurlFetchWeb.php b/Sources/Class-CurlFetchWeb.php
index f0998a136b..0baf341d8a 100644
--- a/Sources/Class-CurlFetchWeb.php
+++ b/Sources/Class-CurlFetchWeb.php
@@ -13,8 +13,9 @@
* @version 3.0 Alpha 1
*/
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
class_alias('SMF\\WebFetch\\APIs\\CurlFetcher', '\\curl_fetch_web_data');
diff --git a/Sources/Class-Graphics.php b/Sources/Class-Graphics.php
index b31a905fa5..6159808d0a 100644
--- a/Sources/Class-Graphics.php
+++ b/Sources/Class-Graphics.php
@@ -13,8 +13,9 @@
* @version 3.0 Alpha 1
*/
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
class_alias('SMF\\Graphics\\Gif\\ColorTable', '\\gif_color_table');
class_alias('SMF\\Graphics\\Gif\\File', '\\gif_file');
diff --git a/Sources/Class-Package.php b/Sources/Class-Package.php
index 62d7b0add8..49b3792b6d 100644
--- a/Sources/Class-Package.php
+++ b/Sources/Class-Package.php
@@ -13,8 +13,9 @@
* @version 3.0 Alpha 1
*/
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
class_alias('SMF\\PackageManager\\XmlArray', '\\xmlArray');
class_alias('SMF\\PackageManager\\FtpConnection', '\\ftp_connection');
diff --git a/Sources/Class-Punycode.php b/Sources/Class-Punycode.php
index a1a229b8a7..134d2a9a16 100644
--- a/Sources/Class-Punycode.php
+++ b/Sources/Class-Punycode.php
@@ -13,8 +13,9 @@
* @version 3.0 Alpha 1
*/
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
class_alias('SMF\\Punycode', '\\Punycode');
diff --git a/Sources/Class-SearchAPI.php b/Sources/Class-SearchAPI.php
index 71a67efbe1..793d8cbf1f 100644
--- a/Sources/Class-SearchAPI.php
+++ b/Sources/Class-SearchAPI.php
@@ -13,8 +13,9 @@
* @version 3.0 Alpha 1
*/
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
class_alias('SMF\\Search\\SearchApiInterface', '\\search_api_interface');
class_alias('SMF\\Search\\SearchApi', '\\search_api');
diff --git a/Sources/Class-TOTP.php b/Sources/Class-TOTP.php
index c2c40f5767..8e3b0dbfc4 100644
--- a/Sources/Class-TOTP.php
+++ b/Sources/Class-TOTP.php
@@ -13,8 +13,9 @@
* @version 3.0 Alpha 1
*/
-if (!defined('SMF'))
+if (!defined('SMF')) {
die('No direct access...');
+}
class_alias('SMF\\TOTP\\Auth', '\\TOTP\\Auth');
diff --git a/Sources/Config.php b/Sources/Config.php
index c7b2010156..28a4c441ca 100644
--- a/Sources/Config.php
+++ b/Sources/Config.php
@@ -30,7 +30,7 @@ class Config
*/
public static bool $backward_compatibility = true;
- ########## Maintenance ##########
+ # ######### Maintenance ##########
/**
* @var int 0, 1, 2
*
@@ -53,7 +53,7 @@ class Config
*/
public static $mmessage;
- ########## Forum info ##########
+ # ######### Forum info ##########
/**
* @var string
*
@@ -85,7 +85,7 @@ class Config
*/
public static $cookiename;
- ########## Database info ##########
+ # ######### Database info ##########
/**
* @var string
*
@@ -163,7 +163,7 @@ class Config
*/
public static $db_mb4;
- ########## Cache info ##########
+ # ######### Cache info ##########
/**
* @var string
*
@@ -199,7 +199,7 @@ class Config
*/
public static $cachedir_sqlite;
- ########## Image proxy ##########
+ # ######### Image proxy ##########
/**
* @var bool
*
@@ -219,7 +219,7 @@ class Config
*/
public static $image_proxy_maxsize;
- ########## Directories/Files ##########
+ # ######### Directories/Files ##########
# Note: These directories do not have to be changed unless you move things.
/**
* @var string
@@ -246,7 +246,7 @@ class Config
*/
public static $tasksdir;
- ######### Legacy settings #########
+ # ######## Legacy settings #########
/**
* @var string
*
@@ -254,7 +254,7 @@ class Config
*/
public static $db_character_set;
- ######### Developer settings #########
+ # ######## Developer settings #########
/**
* @var bool
*
@@ -269,21 +269,21 @@ class Config
*/
public static $db_last_error;
- ######### Custom settings #########
+ # ######## Custom settings #########
/**
* @var array
*
* Holds any custom settings found in Settings.php.
*/
- public static $custom = array();
+ public static $custom = [];
- ######### Runtime configuration values #########
+ # ######## Runtime configuration values #########
/**
* @var array
*
* Holds settings loaded from the settings table in the database.
*/
- public static $modSettings = array();
+ public static $modSettings = [];
/**
* @var string
@@ -344,8 +344,8 @@ class Config
* expression to decide where the replacement entry should be inserted.
* Note: 'replace_pattern' should be avoided unless ABSOLUTELY necessary.
*/
- protected static $settings_defs = array(
- array(
+ protected static $settings_defs = [
+ [
'text' =>
"\n" .
'/**' . "\n" .
@@ -362,8 +362,8 @@ class Config
' */' . "\n" .
'',
'search_pattern' => '~/\*\*.*?@package\h+SMF\b.*?\*/\n{0,2}~s',
- ),
- 'maintenance' => array(
+ ],
+ 'maintenance' => [
'text' => <<<'END'
########## Maintenance ##########
@@ -378,8 +378,8 @@ class Config
END,
'default' => 0,
'type' => 'integer',
- ),
- 'mtitle' => array(
+ ],
+ 'mtitle' => [
'text' => <<<'END'
/**
* @var string
@@ -389,8 +389,8 @@ class Config
END,
'default' => 'Maintenance Mode',
'type' => 'string',
- ),
- 'mmessage' => array(
+ ],
+ 'mmessage' => [
'text' => <<<'END'
/**
* @var string
@@ -400,8 +400,8 @@ class Config
END,
'default' => 'Okay faithful users...we\'re attempting to restore an older backup of the database...news will be posted once we\'re back!',
'type' => 'string',
- ),
- 'mbname' => array(
+ ],
+ 'mbname' => [
'text' => <<<'END'
########## Forum Info ##########
@@ -413,8 +413,8 @@ class Config
END,
'default' => 'My Community',
'type' => 'string',
- ),
- 'language' => array(
+ ],
+ 'language' => [
'text' => <<<'END'
/**
* @var string
@@ -424,8 +424,8 @@ class Config
END,
'default' => 'english',
'type' => 'string',
- ),
- 'boardurl' => array(
+ ],
+ 'boardurl' => [
'text' => <<<'END'
/**
* @var string
@@ -435,8 +435,8 @@ class Config
END,
'default' => 'http://127.0.0.1/smf',
'type' => 'string',
- ),
- 'webmaster_email' => array(
+ ],
+ 'webmaster_email' => [
'text' => <<<'END'
/**
* @var string
@@ -446,8 +446,8 @@ class Config
END,
'default' => 'noreply@myserver.com',
'type' => 'string',
- ),
- 'cookiename' => array(
+ ],
+ 'cookiename' => [
'text' => <<<'END'
/**
* @var string
@@ -457,8 +457,8 @@ class Config
END,
'default' => 'SMFCookie11',
'type' => 'string',
- ),
- 'auth_secret' => array(
+ ],
+ 'auth_secret' => [
'text' => <<<'END'
/**
* @var string
@@ -474,8 +474,8 @@ class Config
'default' => null,
'auto_delete' => 1,
'type' => 'string',
- ),
- 'db_type' => array(
+ ],
+ 'db_type' => [
'text' => <<<'END'
########## Database Info ##########
@@ -488,8 +488,8 @@ class Config
END,
'default' => 'mysql',
'type' => 'string',
- ),
- 'db_port' => array(
+ ],
+ 'db_port' => [
'text' => <<<'END'
/**
* @var int
@@ -500,8 +500,8 @@ class Config
END,
'default' => 0,
'type' => 'integer',
- ),
- 'db_server' => array(
+ ],
+ 'db_server' => [
'text' => <<<'END'
/**
* @var string
@@ -512,8 +512,8 @@ class Config
'default' => 'localhost',
'required' => true,
'type' => 'string',
- ),
- 'db_name' => array(
+ ],
+ 'db_name' => [
'text' => <<<'END'
/**
* @var string
@@ -524,8 +524,8 @@ class Config
'default' => 'smf',
'required' => true,
'type' => 'string',
- ),
- 'db_user' => array(
+ ],
+ 'db_user' => [
'text' => <<<'END'
/**
* @var string
@@ -536,8 +536,8 @@ class Config
'default' => 'root',
'required' => true,
'type' => 'string',
- ),
- 'db_passwd' => array(
+ ],
+ 'db_passwd' => [
'text' => <<<'END'
/**
* @var string
@@ -549,8 +549,8 @@ class Config
'required' => true,
'type' => 'string',
'is_password' => true,
- ),
- 'ssi_db_user' => array(
+ ],
+ 'ssi_db_user' => [
'text' => <<<'END'
/**
* @var string
@@ -560,8 +560,8 @@ class Config
END,
'default' => '',
'type' => 'string',
- ),
- 'ssi_db_passwd' => array(
+ ],
+ 'ssi_db_passwd' => [
'text' => <<<'END'
/**
* @var string
@@ -572,8 +572,8 @@ class Config
'default' => '',
'type' => 'string',
'is_password' => true,
- ),
- 'db_prefix' => array(
+ ],
+ 'db_prefix' => [
'text' => <<<'END'
/**
* @var string
@@ -585,8 +585,8 @@ class Config
'default' => 'smf_',
'required' => true,
'type' => 'string',
- ),
- 'db_persist' => array(
+ ],
+ 'db_persist' => [
'text' => <<<'END'
/**
* @var bool
@@ -596,8 +596,8 @@ class Config
END,
'default' => false,
'type' => 'boolean',
- ),
- 'db_error_send' => array(
+ ],
+ 'db_error_send' => [
'text' => <<<'END'
/**
* @var bool
@@ -607,8 +607,8 @@ class Config
END,
'default' => false,
'type' => 'boolean',
- ),
- 'db_mb4' => array(
+ ],
+ 'db_mb4' => [
'text' => <<<'END'
/**
* @var null|bool
@@ -618,9 +618,9 @@ class Config
*/
END,
'default' => null,
- 'type' => array('NULL', 'boolean'),
- ),
- 'cache_accelerator' => array(
+ 'type' => ['NULL', 'boolean'],
+ ],
+ 'cache_accelerator' => [
'text' => <<<'END'
########## Cache Info ##########
@@ -633,8 +633,8 @@ class Config
END,
'default' => '',
'type' => 'string',
- ),
- 'cache_enable' => array(
+ ],
+ 'cache_enable' => [
'text' => <<<'END'
/**
* @var int
@@ -645,8 +645,8 @@ class Config
END,
'default' => 0,
'type' => 'integer',
- ),
- 'cache_memcached' => array(
+ ],
+ 'cache_memcached' => [
'text' => <<<'END'
/**
* @var array
@@ -657,8 +657,8 @@ class Config
END,
'default' => '',
'type' => 'string',
- ),
- 'cachedir' => array(
+ ],
+ 'cachedir' => [
'text' => <<<'END'
/**
* @var string
@@ -669,8 +669,8 @@ class Config
'default' => 'dirname(__FILE__) . \'/cache\'',
'raw_default' => true,
'type' => 'string',
- ),
- 'cachedir_sqlite' => array(
+ ],
+ 'cachedir_sqlite' => [
'text' => <<<'END'
/**
* @var string
@@ -682,8 +682,8 @@ class Config
'default' => '',
'auto_delete' => 2,
'type' => 'string',
- ),
- 'image_proxy_enabled' => array(
+ ],
+ 'image_proxy_enabled' => [
'text' => <<<'END'
########## Image Proxy ##########
@@ -695,8 +695,8 @@ class Config
END,
'default' => true,
'type' => 'boolean',
- ),
- 'image_proxy_secret' => array(
+ ],
+ 'image_proxy_secret' => [
'text' => <<<'END'
/**
* @var string
@@ -706,8 +706,8 @@ class Config
END,
'default' => 'smfisawesome',
'type' => 'string',
- ),
- 'image_proxy_maxsize' => array(
+ ],
+ 'image_proxy_maxsize' => [
'text' => <<<'END'
/**
* @var int
@@ -717,8 +717,8 @@ class Config
END,
'default' => 5192,
'type' => 'integer',
- ),
- 'boarddir' => array(
+ ],
+ 'boarddir' => [
'text' => <<<'END'
########## Directories/Files ##########
@@ -732,8 +732,8 @@ class Config
'default' => 'dirname(__FILE__)',
'raw_default' => true,
'type' => 'string',
- ),
- 'sourcedir' => array(
+ ],
+ 'sourcedir' => [
'text' => <<<'END'
/**
* @var string
@@ -744,8 +744,8 @@ class Config
'default' => 'dirname(__FILE__) . \'/Sources\'',
'raw_default' => true,
'type' => 'string',
- ),
- 'packagesdir' => array(
+ ],
+ 'packagesdir' => [
'text' => <<<'END'
/**
* @var string
@@ -756,8 +756,8 @@ class Config
'default' => 'dirname(__FILE__) . \'/Packages\'',
'raw_default' => true,
'type' => 'string',
- ),
- 'tasksdir' => array(
+ ],
+ 'tasksdir' => [
'text' => <<<'END'
/**
* @var string
@@ -765,11 +765,11 @@ class Config
* Path to the tasks directory.
*/
END,
- 'default' => '$sourcedir . \'/tasks\'',
+ 'default' => '$sourcedir . \'/Tasks\'',
'raw_default' => true,
'type' => 'string',
- ),
- array(
+ ],
+ [
'text' => <<<'END'
# Make sure the paths are correct... at least try to fix them.
@@ -777,16 +777,16 @@ class Config
$boarddir = dirname(__FILE__);
if (!is_dir(realpath($sourcedir)) && is_dir($boarddir . '/Sources'))
$sourcedir = $boarddir . '/Sources';
- if (!is_dir(realpath($tasksdir)) && is_dir($sourcedir . '/tasks'))
- $tasksdir = $sourcedir . '/tasks';
+ if (!is_dir(realpath($tasksdir)) && is_dir($sourcedir . '/Tasks'))
+ $tasksdir = $sourcedir . '/Tasks';
if (!is_dir(realpath($packagesdir)) && is_dir($boarddir . '/Packages'))
$packagesdir = $boarddir . '/Packages';
if (!is_dir(realpath($cachedir)) && is_dir($boarddir . '/cache'))
$cachedir = $boarddir . '/cache';
END,
- 'search_pattern' => '~\n?(#[^\n]+)?(?:\n\h*if\s*\((?:\!file_exists\(\$(?'.'>boarddir|sourcedir|tasksdir|packagesdir|cachedir)\)|\!is_dir\(realpath\(\$(?'.'>boarddir|sourcedir|tasksdir|packagesdir|cachedir)\)\))[^;]+\n\h*\$(?'.'>boarddir|sourcedir|tasksdir|packagesdir|cachedir)[^\n]+;)+~sm',
- ),
- 'db_character_set' => array(
+ 'search_pattern' => '~\n?(#[^\n]+)?(?:\n\h*if\s*\((?:\!file_exists\(\$(?' . '>boarddir|sourcedir|tasksdir|packagesdir|cachedir)\)|\!is_dir\(realpath\(\$(?' . '>boarddir|sourcedir|tasksdir|packagesdir|cachedir)\)\))[^;]+\n\h*\$(?' . '>boarddir|sourcedir|tasksdir|packagesdir|cachedir)[^\n]+;)+~sm',
+ ],
+ 'db_character_set' => [
'text' => <<<'END'
######### Legacy Settings #########
@@ -798,8 +798,8 @@ class Config
END,
'default' => 'utf8',
'type' => 'string',
- ),
- 'db_show_debug' => array(
+ ],
+ 'db_show_debug' => [
'text' => <<<'END'
######### Developer Settings #########
@@ -812,8 +812,8 @@ class Config
'default' => false,
'auto_delete' => 2,
'type' => 'boolean',
- ),
- array(
+ ],
+ [
'text' => <<<'END'
########## Error-Catching ##########
@@ -830,20 +830,20 @@ class Config
END,
// Designed to match both 2.0 and 2.1 versions of this code.
'search_pattern' => '~\n?#+ Error.Catching #+\n[^\n]*?settings\.\n(?:\$db_last_error = \d{1,11};|if \(file_exists.*?\$db_last_error = 0;(?' . '>\s*}))(?=\n|\?' . '>|$)~s',
- ),
+ ],
// Temporary variable used during the upgrade process.
- 'upgradeData' => array(
+ 'upgradeData' => [
'default' => '',
'auto_delete' => 1,
'type' => 'string',
- ),
+ ],
// This should be removed if found.
- 'db_last_error' => array(
+ 'db_last_error' => [
'default' => 0,
'auto_delete' => 1,
'type' => 'integer',
- ),
- );
+ ],
+ ];
/**
* @var string
@@ -878,14 +878,12 @@ class Config
public static function load(): void
{
// Load Settings.php.
- if (!in_array(SMF_SETTINGS_FILE, get_included_files()))
- {
- require(SMF_SETTINGS_FILE);
+ if (!in_array(SMF_SETTINGS_FILE, get_included_files())) {
+ require SMF_SETTINGS_FILE;
}
// If it has already been included, make sure to avoid possible problems
// with already defined constants, etc.
- else
- {
+ else {
extract((array) self::getCurrentSettings(filemtime(SMF_SETTINGS_FILE), SMF_SETTINGS_FILE));
}
@@ -900,31 +898,27 @@ public static function load(): void
*/
public static function set(array $settings): void
{
- foreach ($settings as $var => $val)
- {
- if (property_exists(__CLASS__, $var))
+ foreach ($settings as $var => $val) {
+ if (property_exists(__CLASS__, $var)) {
self::${$var} = $val;
- else
+ } else {
self::$custom[$var] = $val;
+ }
}
// Anything missing?
$class_vars = get_class_vars(__CLASS__);
- foreach ($class_vars['settings_defs'] as $var => $def)
- {
- if (is_string($var) && property_exists(__CLASS__, $var) && !isset(self::${$var}))
- {
- if (!empty($def['raw_default']))
- {
- $default = strtr($def['default'], array(
+
+ foreach ($class_vars['settings_defs'] as $var => $def) {
+ if (is_string($var) && property_exists(__CLASS__, $var) && !isset(self::${$var})) {
+ if (!empty($def['raw_default'])) {
+ $default = strtr($def['default'], [
'__FILE__' => var_export(SMF_SETTINGS_FILE, true),
'__DIR__' => var_export(dirname(SMF_SETTINGS_FILE), true),
- ));
+ ]);
self::${$var} = eval($default);
- }
- else
- {
+ } else {
self::${$var} = $def['default'];
}
@@ -934,42 +928,33 @@ public static function set(array $settings): void
}
// Ensure there are no trailing slashes in these settings.
- foreach (array('boardurl', 'boarddir', 'sourcedir', 'packagesdir', 'tasksdir', 'cachedir') as $var)
- {
- self::${$var} = rtrim(self::${$var}, "\\/");
+ foreach (['boardurl', 'boarddir', 'sourcedir', 'packagesdir', 'tasksdir', 'cachedir'] as $var) {
+ self::${$var} = rtrim(self::${$var}, '\\/');
}
// Make sure the paths are correct... at least try to fix them.
// @todo Remove similar path correction code from Settings.php.
- if (empty(self::$boarddir) || !is_dir(realpath(self::$boarddir)))
- {
+ if (empty(self::$boarddir) || !is_dir(realpath(self::$boarddir))) {
self::$boarddir = !empty($_SERVER['SCRIPT_FILENAME']) ? dirname(realpath($_SERVER['SCRIPT_FILENAME'])) : dirname(__DIR__);
}
- if ((empty(self::$sourcedir) || !is_dir(realpath(self::$sourcedir))) && is_dir(self::$boarddir . '/Sources'))
- {
+ if ((empty(self::$sourcedir) || !is_dir(realpath(self::$sourcedir))) && is_dir(self::$boarddir . '/Sources')) {
self::$sourcedir = self::$boarddir . '/Sources';
}
- if ((empty(self::$tasksdir) || !is_dir(realpath(self::$tasksdir))) && is_dir(self::$sourcedir . '/tasks'))
- {
- self::$tasksdir = self::$sourcedir . '/tasks';
+ if ((empty(self::$tasksdir) || !is_dir(realpath(self::$tasksdir))) && is_dir(self::$sourcedir . '/Tasks')) {
+ self::$tasksdir = self::$sourcedir . '/Tasks';
}
- if ((empty(self::$packagesdir) || !is_dir(realpath(self::$packagesdir))) && is_dir(self::$boarddir . '/Packages'))
- {
+ if ((empty(self::$packagesdir) || !is_dir(realpath(self::$packagesdir))) && is_dir(self::$boarddir . '/Packages')) {
self::$packagesdir = self::$boarddir . '/Packages';
}
// Make absolutely sure the cache directory is defined and writable.
- if (empty(self::$cachedir) || !is_dir(self::$cachedir) || !is_writable(self::$cachedir))
- {
- if (is_dir(self::$boarddir . '/cache') && is_writable(self::$boarddir . '/cache'))
- {
+ if (empty(self::$cachedir) || !is_dir(self::$cachedir) || !is_writable(self::$cachedir)) {
+ if (is_dir(self::$boarddir . '/cache') && is_writable(self::$boarddir . '/cache')) {
self::$cachedir = self::$boarddir . '/cache';
- }
- else
- {
+ } else {
self::$cachedir = self::getTempDir() . '/smf_cache_' . md5(self::$boarddir);
@mkdir(self::$cachedir, 0750);
}
@@ -980,16 +965,11 @@ public static function set(array $settings): void
// For backward compatibility, make settings available as global variables.
// Must do this manually because SMF\BackwardCompatibility is not loaded yet.
- if (self::$backward_compatibility && !self::$exported)
- {
- foreach ($settings as $var => $val)
- {
- if (property_exists(__CLASS__, $var))
- {
+ if (self::$backward_compatibility && !self::$exported) {
+ foreach ($settings as $var => $val) {
+ if (property_exists(__CLASS__, $var)) {
$GLOBALS[$var] = &self::${$var};
- }
- else
- {
+ } else {
$GLOBALS[$var] = &self::$custom[$var];
}
}
@@ -998,7 +978,7 @@ public static function set(array $settings): void
$GLOBALS['scripturl'] = &self::$scripturl;
eval('function reloadSettings() { return ' . __CLASS__ . '::reloadModSettings(); }');
- eval('function updateSettings() { return ' . __CLASS__ . '::updateModSettings(); }');
+ eval('function updateSettings(...$args) { return ' . __CLASS__ . '::updateModSettings(...$args); }');
eval('function get_auth_secret() { return ' . __CLASS__ . '::getAuthSecret(); }');
eval('function get_settings_defs() { return ' . __CLASS__ . '::getSettingsDefs(); }');
eval('function updateSettingsFile(...$args) { return ' . __CLASS__ . '::updateSettingsFile(...$args); }');
@@ -1024,56 +1004,52 @@ public static function reloadModSettings(): void
Cache\CacheApi::load();
// Try to load it from the cache first; it'll never get cached if the setting is off.
- if ((self::$modSettings = Cache\CacheApi::get('modSettings', 90)) == null)
- {
- self::$modSettings = array();
+ if ((self::$modSettings = Cache\CacheApi::get('modSettings', 90)) == null) {
+ self::$modSettings = [];
- $request = Db\DatabaseApi::$db->query('', '
- SELECT variable, value
+ $request = Db\DatabaseApi::$db->query(
+ '',
+ 'SELECT variable, value
FROM {db_prefix}settings',
- array(
- )
+ [
+ ],
);
- if (!$request)
- {
+
+ if (!$request) {
ErrorHandler::displayDbError();
}
- foreach (Db\DatabaseApi::$db->fetch_all($request) as $row)
- {
+
+ foreach (Db\DatabaseApi::$db->fetch_all($request) as $row) {
self::$modSettings[$row['variable']] = $row['value'];
}
Db\DatabaseApi::$db->free_result($request);
// Do a few things to protect against missing settings or settings with invalid values...
- if (empty(self::$modSettings['defaultMaxTopics']) || self::$modSettings['defaultMaxTopics'] <= 0 || self::$modSettings['defaultMaxTopics'] > 999)
- {
+ if (empty(self::$modSettings['defaultMaxTopics']) || self::$modSettings['defaultMaxTopics'] <= 0 || self::$modSettings['defaultMaxTopics'] > 999) {
self::$modSettings['defaultMaxTopics'] = 20;
}
- if (empty(self::$modSettings['defaultMaxMessages']) || self::$modSettings['defaultMaxMessages'] <= 0 || self::$modSettings['defaultMaxMessages'] > 999)
- {
+ if (empty(self::$modSettings['defaultMaxMessages']) || self::$modSettings['defaultMaxMessages'] <= 0 || self::$modSettings['defaultMaxMessages'] > 999) {
self::$modSettings['defaultMaxMessages'] = 15;
}
- if (empty(self::$modSettings['defaultMaxMembers']) || self::$modSettings['defaultMaxMembers'] <= 0 || self::$modSettings['defaultMaxMembers'] > 999)
- {
+ if (empty(self::$modSettings['defaultMaxMembers']) || self::$modSettings['defaultMaxMembers'] <= 0 || self::$modSettings['defaultMaxMembers'] > 999) {
self::$modSettings['defaultMaxMembers'] = 30;
}
- if (empty(self::$modSettings['defaultMaxListItems']) || self::$modSettings['defaultMaxListItems'] <= 0 || self::$modSettings['defaultMaxListItems'] > 999)
- {
+ if (empty(self::$modSettings['defaultMaxListItems']) || self::$modSettings['defaultMaxListItems'] <= 0 || self::$modSettings['defaultMaxListItems'] > 999) {
self::$modSettings['defaultMaxListItems'] = 15;
}
- if (!is_array(self::$modSettings['attachmentUploadDir']))
- {
+ if (!is_array(self::$modSettings['attachmentUploadDir'])) {
$attachmentUploadDir = Utils::jsonDecode(self::$modSettings['attachmentUploadDir'], true, false);
self::$modSettings['attachmentUploadDir'] = !empty($attachmentUploadDir) ? $attachmentUploadDir : self::$modSettings['attachmentUploadDir'];
}
- if (!empty(Cache\CacheApi::$enable))
+ if (!empty(Cache\CacheApi::$enable)) {
Cache\CacheApi::put('modSettings', self::$modSettings, 90);
+ }
}
// Going anything further when the files don't match the database can make nasty messes (unless we're actively installing or upgrading)
@@ -1087,18 +1063,18 @@ public static function reloadModSettings(): void
)
&& !empty(self::$modSettings['smfVersion'])
&& version_compare(
- strtolower(strtr(self::$modSettings['smfVersion'], array(' ' => '.'))),
- strtolower(strtr(SMF_VERSION, array(' ' => '.'))),
- '!='
+ strtolower(strtr(self::$modSettings['smfVersion'], [' ' => '.'])),
+ strtolower(strtr(SMF_VERSION, [' ' => '.'])),
+ '!=',
)
- )
- {
+ ) {
// Wipe the cached self::$modSettings values so they don't interfere with anything later.
Cache\CacheApi::put('modSettings', null);
// Redirect to the upgrader if we can.
- if (file_exists(self::$boarddir . '/upgrade.php'))
+ if (file_exists(self::$boarddir . '/upgrade.php')) {
header('location: ' . self::$boardurl . '/upgrade.php');
+ }
die('SMF file version (' . SMF_VERSION . ') does not match SMF database version (' . self::$modSettings['smfVersion'] . '). Run the SMF upgrader to fix this. More information.');
}
@@ -1109,77 +1085,64 @@ public static function reloadModSettings(): void
self::$modSettings['browser_cache'] = !empty(self::$modSettings['browser_cache']) ? (int) self::$modSettings['browser_cache'] : 0;
// Disable image proxy if we don't have SSL enabled
- if (empty(self::$modSettings['force_ssl']))
+ if (empty(self::$modSettings['force_ssl'])) {
self::$image_proxy_enabled = false;
+ }
// Setting the timezone is a requirement for some functions.
- if (isset(self::$modSettings['default_timezone']) && in_array(self::$modSettings['default_timezone'], timezone_identifiers_list()))
- {
+ if (isset(self::$modSettings['default_timezone']) && in_array(self::$modSettings['default_timezone'], timezone_identifiers_list())) {
date_default_timezone_set(self::$modSettings['default_timezone']);
- }
- else
- {
+ } else {
// Get PHP's default timezone, if set
$ini_tz = ini_get('date.timezone');
self::$modSettings['default_timezone'] = !empty($ini_tz) ? $ini_tz : '';
// If date.timezone is unset, invalid, or just plain weird, make a best guess
- if (!in_array(self::$modSettings['default_timezone'], timezone_identifiers_list()))
- {
+ if (!in_array(self::$modSettings['default_timezone'], timezone_identifiers_list())) {
$server_offset = @mktime(0, 0, 0, 1, 1, 1970) * -1;
self::$modSettings['default_timezone'] = timezone_name_from_abbr('', $server_offset, 0);
- if (empty(self::$modSettings['default_timezone']))
+ if (empty(self::$modSettings['default_timezone'])) {
self::$modSettings['default_timezone'] = 'UTC';
+ }
}
date_default_timezone_set(self::$modSettings['default_timezone']);
}
// Check the load averages?
- if (!empty(self::$modSettings['loadavg_enable']))
- {
- if ((self::$modSettings['load_average'] = Cache\CacheApi::get('loadavg', 90)) == null)
- {
+ if (!empty(self::$modSettings['loadavg_enable'])) {
+ if ((self::$modSettings['load_average'] = Cache\CacheApi::get('loadavg', 90)) == null) {
self::$modSettings['load_average'] = @file_get_contents('/proc/loadavg');
- if (!empty(self::$modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', self::$modSettings['load_average'], $matches) != 0)
- {
+ if (!empty(self::$modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', self::$modSettings['load_average'], $matches) != 0) {
self::$modSettings['load_average'] = (float) $matches[1];
- }
- elseif ((self::$modSettings['load_average'] = @shell_exec('uptime')) != null && preg_match('~load averages?: (\d+\.\d+)~i', self::$modSettings['load_average'], $matches) != 0)
- {
+ } elseif ((self::$modSettings['load_average'] = @shell_exec('uptime')) != null && preg_match('~load averages?: (\d+\.\d+)~i', self::$modSettings['load_average'], $matches) != 0) {
self::$modSettings['load_average'] = (float) $matches[1];
- }
- else
- {
+ } else {
unset(self::$modSettings['load_average']);
}
- if (!empty(self::$modSettings['load_average']) || self::$modSettings['load_average'] === 0.0)
- {
+ if (!empty(self::$modSettings['load_average']) || self::$modSettings['load_average'] === 0.0) {
Cache\CacheApi::put('loadavg', self::$modSettings['load_average'], 90);
}
}
- if (!empty(self::$modSettings['load_average']) || self::$modSettings['load_average'] === 0.0)
- {
- IntegrationHook::call('integrate_load_average', array(self::$modSettings['load_average']));
+ if (!empty(self::$modSettings['load_average']) || self::$modSettings['load_average'] === 0.0) {
+ IntegrationHook::call('integrate_load_average', [self::$modSettings['load_average']]);
}
- if (!empty(self::$modSettings['loadavg_forum']) && !empty(self::$modSettings['load_average']) && self::$modSettings['load_average'] >= self::$modSettings['loadavg_forum'])
- {
+ if (!empty(self::$modSettings['loadavg_forum']) && !empty(self::$modSettings['load_average']) && self::$modSettings['load_average'] >= self::$modSettings['loadavg_forum']) {
ErrorHandler::displayLoadAvgError();
}
}
// Ensure we know who can manage boards.
- if (!isset(self::$modSettings['board_manager_groups']))
- {
+ if (!isset(self::$modSettings['board_manager_groups'])) {
$board_managers = User::groupsAllowedTo('manage_boards', null);
$board_managers = implode(',', $board_managers['allowed']);
- Config::updateModSettings(array('board_manager_groups' => $board_managers));
+ Config::updateModSettings(['board_manager_groups' => $board_managers]);
}
// Is post moderation alive and well? Everywhere else assumes this has been defined, so let's make sure it is.
@@ -1188,12 +1151,11 @@ public static function reloadModSettings(): void
// Here to justify the name of this function. :P
// It should be added to the install and upgrade scripts.
// But since the converters need to be updated also. This is easier.
- if (empty(self::$modSettings['currentAttachmentUploadDir']))
- {
- Config::updateModSettings(array(
- 'attachmentUploadDir' => Utils::jsonEncode(array(1 => self::$modSettings['attachmentUploadDir'])),
+ if (empty(self::$modSettings['currentAttachmentUploadDir'])) {
+ Config::updateModSettings([
+ 'attachmentUploadDir' => Utils::jsonEncode([1 => self::$modSettings['attachmentUploadDir']]),
'currentAttachmentUploadDir' => 1,
- ));
+ ]);
}
// Respect PHP's limits.
@@ -1204,25 +1166,24 @@ public static function reloadModSettings(): void
self::$modSettings['attachmentNumPerPostLimit'] = !isset(self::$modSettings['attachmentNumPerPostLimit']) ? 4 : self::$modSettings['attachmentNumPerPostLimit'];
// Integration is cool.
- if (defined('SMF_INTEGRATION_SETTINGS'))
- {
+ if (defined('SMF_INTEGRATION_SETTINGS')) {
$integration_settings = Utils::jsonDecode(SMF_INTEGRATION_SETTINGS, true);
- foreach ($integration_settings as $hook => $function)
+ foreach ($integration_settings as $hook => $function) {
IntegrationHook::add($hook, $function, false);
+ }
}
// Any files to pre include?
- if (!empty(self::$modSettings['integrate_pre_include']))
- {
+ if (!empty(self::$modSettings['integrate_pre_include'])) {
$pre_includes = explode(',', self::$modSettings['integrate_pre_include']);
- foreach ($pre_includes as $include)
- {
- $include = strtr(trim($include), array('$boarddir' => self::$boarddir, '$sourcedir' => self::$sourcedir));
+ foreach ($pre_includes as $include) {
+ $include = strtr(trim($include), ['$boarddir' => self::$boarddir, '$sourcedir' => self::$sourcedir]);
- if (file_exists($include))
- require_once($include);
+ if (file_exists($include)) {
+ require_once $include;
+ }
}
}
@@ -1252,16 +1213,15 @@ public static function reloadModSettings(): void
*/
public static function updateModSettings(array $change_array, bool $update = false): void
{
- if (empty($change_array) || !is_array($change_array))
+ if (empty($change_array) || !is_array($change_array)) {
return;
+ }
- $to_remove = array();
+ $to_remove = [];
// Go check if there is any setting to be removed.
- foreach ($change_array as $k => $v)
- {
- if ($v === null)
- {
+ foreach ($change_array as $k => $v) {
+ if ($v === null) {
// Found some, remove them from the original array and add them to ours.
unset($change_array[$k]);
$to_remove[] = $k;
@@ -1269,30 +1229,29 @@ public static function updateModSettings(array $change_array, bool $update = fal
}
// Proceed with the deletion.
- if (!empty($to_remove))
- {
- Db\DatabaseApi::$db->query('', '
- DELETE FROM {db_prefix}settings
+ if (!empty($to_remove)) {
+ Db\DatabaseApi::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}settings
WHERE variable IN ({array_string:remove})',
- array(
+ [
'remove' => $to_remove,
- )
+ ],
);
}
// In some cases, this may be better and faster, but for large sets we don't want so many UPDATEs.
- if ($update)
- {
- foreach ($change_array as $variable => $value)
- {
- Db\DatabaseApi::$db->query('', '
- UPDATE {db_prefix}settings
+ if ($update) {
+ foreach ($change_array as $variable => $value) {
+ Db\DatabaseApi::$db->query(
+ '',
+ 'UPDATE {db_prefix}settings
SET value = {' . ($value === false || $value === true ? 'raw' : 'string') . ':value}
WHERE variable = {string:variable}',
- array(
+ [
'value' => $value === true ? 'value + 1' : ($value === false ? 'value - 1' : $value),
'variable' => $variable,
- )
+ ],
);
self::$modSettings[$variable] = $value === true ? self::$modSettings[$variable] + 1 : ($value === false ? self::$modSettings[$variable] - 1 : $value);
@@ -1304,30 +1263,34 @@ public static function updateModSettings(array $change_array, bool $update = fal
return;
}
- $replace_array = array();
- foreach ($change_array as $variable => $value)
- {
+ $replace_array = [];
+
+ foreach ($change_array as $variable => $value) {
// Don't bother if it's already like that ;).
- if ((self::$modSettings[$variable] ?? null) == $value)
+ if ((self::$modSettings[$variable] ?? null) == $value) {
continue;
+ }
// If the variable isn't set, but would only be set to nothingness, then don't bother setting it.
- if (!isset(self::$modSettings[$variable]) && empty($value))
+ if (!isset(self::$modSettings[$variable]) && empty($value)) {
continue;
+ }
- $replace_array[] = array($variable, $value);
+ $replace_array[] = [$variable, $value];
self::$modSettings[$variable] = $value;
}
- if (empty($replace_array))
+ if (empty($replace_array)) {
return;
+ }
- Db\DatabaseApi::$db->insert('replace',
+ Db\DatabaseApi::$db->insert(
+ 'replace',
'{db_prefix}settings',
- array('variable' => 'string-255', 'value' => 'string-65534'),
+ ['variable' => 'string-255', 'value' => 'string-65534'],
$replace_array,
- array('variable')
+ ['variable'],
);
// Kill the cache - it needs redoing now, but we won't bother ourselves with that here.
@@ -1342,25 +1305,24 @@ public static function updateModSettings(array $change_array, bool $update = fal
*/
public static function getAuthSecret(): string
{
- if (empty(self::$auth_secret))
- {
- if (!is_callable('random_bytes'))
- require_once(self::$sourcedir . '/random_compat/random.php');
+ if (empty(self::$auth_secret)) {
+ if (!is_callable('random_bytes')) {
+ require_once self::$sourcedir . '/random_compat/random.php';
+ }
self::$auth_secret = bin2hex(random_bytes(32));
// It is important to store this in Settings.php, not the database.
// If saving fails, we should alert, log, and set a static value.
- if (!self::updateSettingsFile(array('auth_secret' => self::$auth_secret)))
- {
- if (class_exists('SMF\\Utils', false))
+ if (!self::updateSettingsFile(['auth_secret' => self::$auth_secret])) {
+ if (class_exists('SMF\\Utils', false)) {
Utils::$context['auth_secret_missing'] = true;
+ }
self::$auth_secret = hash_file('sha256', SMF_SETTINGS_FILE);
// Set the last error to now, but only every 15 minutes. Don't need to flood the logs.
- if (empty(self::$db_last_error) || (self::$db_last_error + 60*15) <= time())
- {
+ if (empty(self::$db_last_error) || (self::$db_last_error + 60 * 15) <= time()) {
self::updateDbLastError(time());
Lang::load('Errors');
ErrorHandler::log(Lang::$txt['auth_secret_missing'], 'critical');
@@ -1385,8 +1347,9 @@ public static function getSettingsDefs(): array
// Allow mods the option to define comments, defaults, etc., for their settings.
// Check if IntegrationHook exists, in case we are calling from installer or upgrader.
- if (class_exists('SMF\\IntegrationHook', false))
- IntegrationHook::call('integrate_update_settings_file', array(&self::$settings_defs));
+ if (class_exists('SMF\\IntegrationHook', false)) {
+ IntegrationHook::call('integrate_update_settings_file', [&self::$settings_defs]);
+ }
// Return the setting definitions, including any added by mods.
return self::$settings_defs;
@@ -1425,37 +1388,35 @@ public static function getSettingsDefs(): array
* Default false.
* @return bool True on success, false on failure.
*/
- public static function updateSettingsFile(array $config_vars, bool|null $keep_quotes = null, bool $rebuild = false): bool
+ public static function updateSettingsFile(array $config_vars, ?bool $keep_quotes = null, bool $rebuild = false): bool
{
static $mtime;
// Should we try to unescape the strings?
- if (empty($keep_quotes))
- {
- foreach ($config_vars as $var => $val)
- {
- if (is_string($val) && ($keep_quotes === false || strpos($val, '\'') === 0 && strrpos($val, '\'') === strlen($val) - 1))
- {
+ if (empty($keep_quotes)) {
+ foreach ($config_vars as $var => $val) {
+ if (is_string($val) && ($keep_quotes === false || strpos($val, '\'') === 0 && strrpos($val, '\'') === strlen($val) - 1)) {
$config_vars[$var] = trim(stripcslashes($val), '\'');
}
}
}
// Updating the db_last_error, then don't mess around with Settings.php
- if (isset($config_vars['db_last_error']))
- {
+ if (isset($config_vars['db_last_error'])) {
self::updateDbLastError($config_vars['db_last_error']);
- if (count($config_vars) === 1 && empty($rebuild))
+ if (count($config_vars) === 1 && empty($rebuild)) {
return true;
+ }
// Make sure we delete this from Settings.php, if present.
$config_vars['db_last_error'] = 0;
}
// Rebuilding should not be undertaken lightly, so we're picky about the parameter.
- if (!is_bool($rebuild))
+ if (!is_bool($rebuild)) {
$rebuild = false;
+ }
$mtime = isset($mtime) ? (int) $mtime : (defined('TIME_START') ? TIME_START : $_SERVER['REQUEST_TIME']);
@@ -1464,23 +1425,19 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
*****************/
// Is Settings.php where we expect it to be, or do we need to find it?
- if (defined('SMF_SETTINGS_FILE') && is_file(SMF_SETTINGS_FILE))
- {
+ if (defined('SMF_SETTINGS_FILE') && is_file(SMF_SETTINGS_FILE)) {
$settingsFile = SMF_SETTINGS_FILE;
$backupFile = defined('SMF_SETTINGS_BACKUP_FILE') ? SMF_SETTINGS_BACKUP_FILE : dirname(SMF_SETTINGS_FILE) . DIRECTORY_SEPARATOR . pathinfo(SMF_SETTINGS_FILE, PATHINFO_FILENAME) . '_bak.php';
- }
- else
- {
- foreach (get_included_files() as $settingsFile)
- {
- if (basename($settingsFile) === 'Settings.php')
+ } else {
+ foreach (get_included_files() as $settingsFile) {
+ if (basename($settingsFile) === 'Settings.php') {
break;
+ }
}
// Fallback in case Settings.php isn't loaded (e.g. while installing)
- if (basename($settingsFile) !== 'Settings.php')
- {
+ if (basename($settingsFile) !== 'Settings.php') {
$settingsFile = (!empty(self::$boarddir) && @realpath(self::$boarddir) ? self::$boarddir : (!empty($_SERVER['SCRIPT_FILENAME']) ? dirname($_SERVER['SCRIPT_FILENAME']) : dirname(__DIR__))) . DIRECTORY_SEPARATOR . 'Settings.php';
}
@@ -1488,8 +1445,9 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
}
// File not found? Attempt an emergency on-the-fly fix!
- if (!file_exists($settingsFile))
+ if (!file_exists($settingsFile)) {
@touch($settingsFile);
+ }
// When was Settings.php last changed?
$last_settings_change = filemtime($settingsFile);
@@ -1498,12 +1456,14 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
$settings_vars = self::getCurrentSettings($mtime, $settingsFile);
// If Settings.php is empty for some reason, see if we can use the backup.
- if (empty($settings_vars) && file_exists($backupFile))
+ if (empty($settings_vars) && file_exists($backupFile)) {
$settings_vars = self::getCurrentSettings($mtime, $backupFile);
+ }
// False means there was a problem with the file and we can't safely continue.
- if ($settings_vars === false)
+ if ($settings_vars === false) {
return false;
+ }
// It works best to set everything afresh.
$new_settings_vars = array_merge($settings_vars, $config_vars);
@@ -1515,24 +1475,22 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
$settings_defs = self::getSettingsDefs();
// If Settings.php is empty or invalid, try to recover using whatever we have now.
- if ($settings_vars === array())
- {
- foreach ($settings_defs as $var => $setting_def)
- {
- if (isset(self::${$var}) || isset(self::$custom[$var]))
+ if ($settings_vars === []) {
+ foreach ($settings_defs as $var => $setting_def) {
+ if (isset(self::${$var}) || isset(self::$custom[$var])) {
$settings_vars[$var] = self::${$var} ?? self::$custom[$var];
+ }
}
$new_settings_vars = array_merge($settings_vars, $config_vars);
}
// During install/upgrade, don't set anything until we're ready for it.
- if (defined('SMF_INSTALLING') && empty($rebuild))
- {
- foreach ($settings_defs as $var => $setting_def)
- {
- if (!in_array($var, array_keys($new_settings_vars)) && !is_int($var))
+ if (defined('SMF_INSTALLING') && empty($rebuild)) {
+ foreach ($settings_defs as $var => $setting_def) {
+ if (!in_array($var, array_keys($new_settings_vars)) && !is_int($var)) {
unset($settings_defs[$var]);
+ }
}
}
@@ -1540,7 +1498,7 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
* PART 2: Build substitutions *
*******************************/
- $type_regex = array(
+ $type_regex = [
'string' =>
'(?:' .
// match the opening quotation mark...
@@ -1559,9 +1517,9 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
'boolean' => '(?i:TRUE|FALSE|(["\']?)[01]\b\\1)',
'NULL' => '(?i:NULL)',
// These use a PCRE subroutine to match nested arrays.
- 'array' => 'array\s*(\((?'.'>[^()]|(?1))*\))',
- 'object' => '\w+::__set_state\(array\s*(\((?'.'>[^()]|(?1))*\))\)',
- );
+ 'array' => 'array\s*(\((?' . '>[^()]|(?1))*\))',
+ 'object' => '\w+::__set_state\(array\s*(\((?' . '>[^()]|(?1))*\))\)',
+ ];
/*
* The substitutions take place in one of two ways:
@@ -1579,68 +1537,60 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
*/
$prefix = mt_rand() . '-';
$neg_index = -1;
- $substitutions = array(
- $neg_index-- => array(
+ $substitutions = [
+ $neg_index-- => [
'search_pattern' => '~^\s*<\?(php\b)?\n?~',
'placeholder' => '',
'replace_pattern' => '~^~',
'replacement' => '<' . "?php\n",
- ),
- $neg_index-- => array(
+ ],
+ $neg_index-- => [
'search_pattern' => '~\S\K\s*(\?' . '>)?\s*$~',
'placeholder' => "\n" . md5($prefix . '?' . '>'),
'replacement' => "\n\n?" . '>',
- ),
+ ],
// Remove the code that redirects to the installer.
- $neg_index-- => array(
- 'search_pattern' => '~^if\s*\(file_exists\(dirname\(__FILE__\)\s*\.\s*\'/install\.php\'\)\)\s*(?:({(?'.'>[^{}]|(?1))*})\h*|header(\((?' . '>[^()]|(?2))*\));\n)~m',
+ $neg_index-- => [
+ 'search_pattern' => '~^if\s*\(file_exists\(dirname\(__FILE__\)\s*\.\s*\'/install\.php\'\)\)\s*(?:({(?' . '>[^{}]|(?1))*})\h*|header(\((?' . '>[^()]|(?2))*\));\n)~m',
'placeholder' => '',
- ),
- );
+ ],
+ ];
- if (defined('SMF_INSTALLING'))
- {
- $substitutions[$neg_index--] = array(
+ if (defined('SMF_INSTALLING')) {
+ $substitutions[$neg_index--] = [
'search_pattern' => '~/\*.*?SMF\s+1\.\d.*?\*/~s',
'placeholder' => '',
- );
+ ];
}
- foreach ($settings_defs as $var => $setting_def)
- {
+ foreach ($settings_defs as $var => $setting_def) {
$placeholder = md5($prefix . $var);
$replacement = '';
- if (!empty($setting_def['text']))
- {
+ if (!empty($setting_def['text'])) {
// Special handling for the license block: always at the beginning.
- if (strpos($setting_def['text'], "* @package SMF\n") !== false)
- {
+ if (strpos($setting_def['text'], "* @package SMF\n") !== false) {
$substitutions[$var]['search_pattern'] = $setting_def['search_pattern'];
$substitutions[$var]['placeholder'] = '';
$substitutions[-1]['replacement'] .= $setting_def['text'] . "\n";
}
// Special handling for the Error-Catching block: always at the end.
- elseif (strpos($setting_def['text'], 'Error-Catching') !== false)
- {
+ elseif (strpos($setting_def['text'], 'Error-Catching') !== false) {
$errcatch_var = $var;
$substitutions[$var]['search_pattern'] = $setting_def['search_pattern'];
$substitutions[$var]['placeholder'] = '';
$substitutions[-2]['replacement'] = "\n" . $setting_def['text'] . $substitutions[-2]['replacement'];
}
// The text is the whole thing (code blocks, etc.)
- elseif (is_int($var))
- {
+ elseif (is_int($var)) {
// Remember the path correcting code for later.
- if (strpos($setting_def['text'], '# Make sure the paths are correct') !== false)
+ if (strpos($setting_def['text'], '# Make sure the paths are correct') !== false) {
$pathcode_var = $var;
+ }
- if (!empty($setting_def['search_pattern']))
- {
+ if (!empty($setting_def['search_pattern'])) {
$substitutions[$var]['search_pattern'] = $setting_def['search_pattern'];
- }
- else
- {
+ } else {
$substitutions[$var]['search_pattern'] = '~' . preg_quote($setting_def['text'], '~') . '~';
}
@@ -1649,67 +1599,52 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
$replacement .= $setting_def['text'] . "\n";
}
// We only include comments when rebuilding.
- elseif (!empty($rebuild))
- {
+ elseif (!empty($rebuild)) {
$replacement .= $setting_def['text'] . "\n";
}
}
- if (is_string($var))
- {
+ if (is_string($var)) {
// Ensure the value is good.
- if (in_array($var, array_keys($new_settings_vars)))
- {
+ if (in_array($var, array_keys($new_settings_vars))) {
// Objects without a __set_state method need a fallback.
- if (is_object($new_settings_vars[$var]) && !method_exists($new_settings_vars[$var], '__set_state'))
- {
- if (method_exists($new_settings_vars[$var], '__toString'))
- {
+ if (is_object($new_settings_vars[$var]) && !method_exists($new_settings_vars[$var], '__set_state')) {
+ if (method_exists($new_settings_vars[$var], '__toString')) {
$new_settings_vars[$var] = (string) $new_settings_vars[$var];
- }
- else
- {
+ } else {
$new_settings_vars[$var] = (array) $new_settings_vars[$var];
}
}
// Normalize the type if necessary.
- if (isset($setting_def['type']))
- {
+ if (isset($setting_def['type'])) {
$expected_types = (array) $setting_def['type'];
$var_type = gettype($new_settings_vars[$var]);
// Variable is not of an expected type.
- if (!in_array($var_type, $expected_types))
- {
+ if (!in_array($var_type, $expected_types)) {
// Passed in an unexpected array.
- if ($var_type == 'array')
- {
+ if ($var_type == 'array') {
$temp = reset($new_settings_vars[$var]);
// Use the first element if there's only one and it is a scalar.
- if (count($new_settings_vars[$var]) === 1 && is_scalar($temp))
- {
+ if (count($new_settings_vars[$var]) === 1 && is_scalar($temp)) {
$new_settings_vars[$var] = $temp;
}
// Or keep the old value, if that is good.
- elseif (isset($settings_vars[$var]) && in_array(gettype($settings_vars[$var]), $expected_types))
- {
+ elseif (isset($settings_vars[$var]) && in_array(gettype($settings_vars[$var]), $expected_types)) {
$new_settings_vars[$var] = $settings_vars[$var];
}
// Fall back to the default
- else
- {
+ else {
$new_settings_vars[$var] = $setting_def['default'];
}
}
// Cast it to whatever type was expected.
// Note: the order of the types in this loop matters.
- foreach (array('boolean', 'integer', 'double', 'string', 'array') as $to_type)
- {
- if (in_array($to_type, $expected_types))
- {
+ foreach (['boolean', 'integer', 'double', 'string', 'array'] as $to_type) {
+ if (in_array($to_type, $expected_types)) {
settype($new_settings_vars[$var], $to_type);
break;
}
@@ -1718,57 +1653,46 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
}
}
// Abort if a required one is undefined (unless we're installing).
- elseif (!empty($setting_def['required']) && !defined('SMF_INSTALLING'))
- {
+ elseif (!empty($setting_def['required']) && !defined('SMF_INSTALLING')) {
return false;
}
// Create the search pattern.
- if (!empty($setting_def['search_pattern']))
- {
+ if (!empty($setting_def['search_pattern'])) {
$substitutions[$var]['search_pattern'] = $setting_def['search_pattern'];
- }
- else
- {
- $var_pattern = array();
+ } else {
+ $var_pattern = [];
- if (isset($setting_def['type']))
- {
- foreach ((array) $setting_def['type'] as $type)
+ if (isset($setting_def['type'])) {
+ foreach ((array) $setting_def['type'] as $type) {
$var_pattern[] = $type_regex[$type];
+ }
}
- if (in_array($var, array_keys($config_vars)))
- {
+ if (in_array($var, array_keys($config_vars))) {
$var_pattern[] = @$type_regex[gettype($config_vars[$var])];
- if (is_string($config_vars[$var]) && strpos($config_vars[$var], dirname($settingsFile)) === 0)
- {
+ if (is_string($config_vars[$var]) && strpos($config_vars[$var], dirname($settingsFile)) === 0) {
$var_pattern[] = '(?:__DIR__|dirname\(__FILE__\)) . \'' . (preg_quote(str_replace(dirname($settingsFile), '', $config_vars[$var]), '~')) . '\'';
}
}
- if (in_array($var, array_keys($settings_vars)))
- {
+ if (in_array($var, array_keys($settings_vars))) {
$var_pattern[] = @$type_regex[gettype($settings_vars[$var])];
- if (is_string($settings_vars[$var]) && strpos($settings_vars[$var], dirname($settingsFile)) === 0)
- {
+ if (is_string($settings_vars[$var]) && strpos($settings_vars[$var], dirname($settingsFile)) === 0) {
$var_pattern[] = '(?:__DIR__|dirname\(__FILE__\)) . \'' . (preg_quote(str_replace(dirname($settingsFile), '', $settings_vars[$var]), '~')) . '\'';
}
}
- if (!empty($setting_def['raw_default']) && $setting_def['default'] !== '')
- {
+ if (!empty($setting_def['raw_default']) && $setting_def['default'] !== '') {
$var_pattern[] = preg_replace('/\s+/', '\s+', preg_quote($setting_def['default'], '~'));
- if (strpos($setting_def['default'], 'dirname(__FILE__)') !== false)
- {
+ if (strpos($setting_def['default'], 'dirname(__FILE__)') !== false) {
$var_pattern[] = preg_replace('/\s+/', '\s+', preg_quote(str_replace('dirname(__FILE__)', '__DIR__', $setting_def['default']), '~'));
}
- if (strpos($setting_def['default'], '__DIR__') !== false)
- {
+ if (strpos($setting_def['default'], '__DIR__') !== false) {
$var_pattern[] = preg_replace('/\s+/', '\s+', preg_quote(str_replace('__DIR__', 'dirname(__FILE__)', $setting_def['default']), '~'));
}
}
@@ -1781,25 +1705,18 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
}
// Next create the placeholder or replace_pattern.
- if (!empty($setting_def['replace_pattern']))
- {
+ if (!empty($setting_def['replace_pattern'])) {
$substitutions[$var]['replace_pattern'] = $setting_def['replace_pattern'];
- }
- else
- {
+ } else {
$substitutions[$var]['placeholder'] = $placeholder;
}
// Now create the replacement.
// A setting to delete.
- if (!empty($setting_def['auto_delete']) && empty($new_settings_vars[$var]))
- {
- if ($setting_def['auto_delete'] === 2 && empty($rebuild) && in_array($var, array_keys($new_settings_vars)))
- {
- $replacement .= '$' . $var . ' = ' . ($new_settings_vars[$var] === $setting_def['default'] && !empty($setting_def['raw_default']) ? sprintf($new_settings_vars[$var]) : self::varExport($new_settings_vars[$var], true)) . ";";
- }
- else
- {
+ if (!empty($setting_def['auto_delete']) && empty($new_settings_vars[$var])) {
+ if ($setting_def['auto_delete'] === 2 && empty($rebuild) && in_array($var, array_keys($new_settings_vars))) {
+ $replacement .= '$' . $var . ' = ' . ($new_settings_vars[$var] === $setting_def['default'] && !empty($setting_def['raw_default']) ? sprintf($new_settings_vars[$var]) : self::varExport($new_settings_vars[$var], true)) . ';';
+ } else {
$replacement = '';
$substitutions[$var]['placeholder'] = '';
@@ -1808,18 +1725,15 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
}
}
// Add this setting's value.
- elseif (in_array($var, array_keys($new_settings_vars)))
- {
- $replacement .= '$' . $var . ' = ' . ($new_settings_vars[$var] === $setting_def['default'] && !empty($setting_def['raw_default']) ? sprintf($new_settings_vars[$var]) : self::varExport($new_settings_vars[$var], true)) . ";";
+ elseif (in_array($var, array_keys($new_settings_vars))) {
+ $replacement .= '$' . $var . ' = ' . ($new_settings_vars[$var] === $setting_def['default'] && !empty($setting_def['raw_default']) ? sprintf($new_settings_vars[$var]) : self::varExport($new_settings_vars[$var], true)) . ';';
}
// Fall back to the default value.
- elseif (isset($setting_def['default']))
- {
+ elseif (isset($setting_def['default'])) {
$replacement .= '$' . $var . ' = ' . (!empty($setting_def['raw_default']) ? sprintf($setting_def['default']) : self::varExport($setting_def['default'], true)) . ';';
}
// This shouldn't happen, but we've got nothing.
- else
- {
+ else {
$replacement .= '$' . $var . ' = null;';
}
}
@@ -1831,15 +1745,16 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
}
// Any leftovers to deal with?
- foreach ($new_settings_vars as $var => $val)
- {
- $var_pattern = array();
+ foreach ($new_settings_vars as $var => $val) {
+ $var_pattern = [];
- if (in_array($var, array_keys($config_vars)))
+ if (in_array($var, array_keys($config_vars))) {
$var_pattern[] = $type_regex[gettype($config_vars[$var])];
+ }
- if (in_array($var, array_keys($settings_vars)))
+ if (in_array($var, array_keys($settings_vars))) {
$var_pattern[] = $type_regex[gettype($settings_vars[$var])];
+ }
$var_pattern = array_unique($var_pattern);
@@ -1849,20 +1764,17 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
$substitutions[$var]['search_pattern'] = '~(?<=^|\s)\h*\$' . preg_quote($var, '~') . '\s*=\s*' . $var_pattern . ';~' . (!empty($utf8) ? 'u' : '');
$substitutions[$var]['placeholder'] = $placeholder;
- $substitutions[$var]['replacement'] = '$' . $var . ' = ' . self::varExport($val, true) . ";";
+ $substitutions[$var]['replacement'] = '$' . $var . ' = ' . self::varExport($val, true) . ';';
}
// During an upgrade, some of the path variables may not have been declared yet.
- if (defined('SMF_INSTALLING') && empty($rebuild))
- {
+ if (defined('SMF_INSTALLING') && empty($rebuild)) {
preg_match_all('~^\h*\$(\w+)\s*=\s*~m', $substitutions[$pathcode_var]['replacement'], $matches);
$missing_pathvars = array_diff($matches[1], array_keys($substitutions));
- if (!empty($missing_pathvars))
- {
- foreach ($missing_pathvars as $var)
- {
+ if (!empty($missing_pathvars)) {
+ foreach ($missing_pathvars as $var) {
$substitutions[$pathcode_var]['replacement'] = preg_replace('~\nif[^\n]+\$' . $var . '[^\n]+\n\h*\$' . $var . ' = [^\n]+~', '', $substitutions[$pathcode_var]['replacement']);
}
}
@@ -1871,24 +1783,21 @@ public static function updateSettingsFile(array $config_vars, bool|null $keep_qu
// It's important to do the numbered ones before the named ones, or messes happen.
uksort(
$substitutions,
- function($a, $b) {
- if (is_int($a) && is_int($b))
- {
+ function ($a, $b) {
+ if (is_int($a) && is_int($b)) {
return $a > $b ? 1 : ($a < $b ? -1 : 0);
}
- elseif (is_int($a))
- {
+
+ if (is_int($a)) {
return -1;
}
- elseif (is_int($b))
- {
+
+ if (is_int($b)) {
return 1;
}
- else
- {
- return strcasecmp($b, $a);
- }
- }
+
+ return strcasecmp($b, $a);
+ },
);
/******************************
@@ -1898,26 +1807,21 @@ function($a, $b) {
/* 3.a: Get the content of Settings.php and make sure it is good. */
// Retrieve the contents of Settings.php and normalize the line endings.
- $settingsText = trim(strtr(file_get_contents($settingsFile), array("\r\n" => "\n", "\r" => "\n")));
+ $settingsText = trim(strtr(file_get_contents($settingsFile), ["\r\n" => "\n", "\r" => "\n"]));
// If Settings.php is empty or corrupt for some reason, see if we can recover.
- if ($settingsText == '' || substr($settingsText, 0, 5) !== '<' . '?php')
- {
+ if ($settingsText == '' || substr($settingsText, 0, 5) !== '<' . '?php') {
// Try restoring from the backup.
- if (file_exists($backupFile))
- {
- $settingsText = strtr(file_get_contents($backupFile), array("\r\n" => "\n", "\r" => "\n"));
+ if (file_exists($backupFile)) {
+ $settingsText = strtr(file_get_contents($backupFile), ["\r\n" => "\n", "\r" => "\n"]);
}
// Backup is bad too? Our only option is to create one from scratch.
- if ($settingsText == '' || substr($settingsText, 0, 5) !== '<' . '?php' || substr($settingsText, -2) !== '?' . '>')
- {
+ if ($settingsText == '' || substr($settingsText, 0, 5) !== '<' . '?php' || substr($settingsText, -2) !== '?' . '>') {
$settingsText = '<' . "?php\n";
- foreach ($settings_defs as $var => $setting_def)
- {
- if (is_string($var) && !empty($setting_def['text']) && strpos($substitutions[$var]['replacement'], $setting_def['text']) === false)
- {
+ foreach ($settings_defs as $var => $setting_def) {
+ if (is_string($var) && !empty($setting_def['text']) && strpos($substitutions[$var]['replacement'], $setting_def['text']) === false) {
$substitutions[$var]['replacement'] = $setting_def['text'] . "\n" . $substitutions[$var]['replacement'];
}
@@ -1930,17 +1834,12 @@ function($a, $b) {
}
// Settings.php is unlikely to contain any heredocs, but just in case...
- if (preg_match_all('/<<<([\'"]?)(\w+)\1\R(.*?)\R\h*\2;$/ms', $settingsText, $matches))
- {
- foreach ($matches[0] as $mkey => $heredoc)
- {
- if (!empty($matches[1][$mkey]) && $matches[1][$mkey] === '\'')
- {
+ if (preg_match_all('/<<<([\'"]?)(\w+)\1\R(.*?)\R\h*\2;$/ms', $settingsText, $matches)) {
+ foreach ($matches[0] as $mkey => $heredoc) {
+ if (!empty($matches[1][$mkey]) && $matches[1][$mkey] === '\'') {
$heredoc_replacements[$heredoc] = var_export($matches[3][$mkey], true) . ';';
- }
- else
- {
- $heredoc_replacements[$heredoc] = '"' . strtr(substr(var_export($matches[3][$mkey], true), 1, -1), array("\\'" => "'", '"' => '\"')) . '";';
+ } else {
+ $heredoc_replacements[$heredoc] = '"' . strtr(substr(var_export($matches[3][$mkey], true), 1, -1), ["\\'" => "'", '"' => '\\"']) . '";';
}
}
@@ -1951,58 +1850,53 @@ function($a, $b) {
$last_var = null;
$bare_settingsText = $settingsText;
- $force_before_pathcode = array();
- foreach ($substitutions as $var => $substitution)
- {
+ $force_before_pathcode = [];
+
+ foreach ($substitutions as $var => $substitution) {
$placeholders[$var] = $substitution['placeholder'];
- if (!empty($substitution['placeholder']))
- {
+ if (!empty($substitution['placeholder'])) {
$simple_replacements[$substitution['placeholder']] = $substitution['replacement'];
- }
- elseif (!empty($substitution['replace_pattern']))
- {
+ } elseif (!empty($substitution['replace_pattern'])) {
$replace_patterns[$var] = $substitution['replace_pattern'];
$replace_strings[$var] = $substitution['replacement'];
}
- if (strpos($substitutions[$pathcode_var]['replacement'], '$' . $var . ' = ') !== false)
+ if (strpos($substitutions[$pathcode_var]['replacement'], '$' . $var . ' = ') !== false) {
$force_before_pathcode[] = $var;
+ }
// Look before you leap.
preg_match_all($substitution['search_pattern'], $bare_settingsText, $matches);
- if ((is_string($var) || $var === $pathcode_var) && count($matches[0]) !== 1 && $substitution['replacement'] !== '')
- {
+ if ((is_string($var) || $var === $pathcode_var) && count($matches[0]) !== 1 && $substitution['replacement'] !== '') {
// More than one instance of the variable = not good.
- if (count($matches[0]) > 1)
- {
- if (is_string($var))
- {
+ if (count($matches[0]) > 1) {
+ if (is_string($var)) {
// Maybe we can try something more interesting?
$sp = substr($substitution['search_pattern'], 1);
- if (strpos($sp, '(?<=^|\s)') === 0)
+ if (strpos($sp, '(?<=^|\s)') === 0) {
$sp = substr($sp, 9);
+ }
- if (strpos($sp, '^') === 0 || strpos($sp, '(?<') === 0)
+ if (strpos($sp, '^') === 0 || strpos($sp, '(?<') === 0) {
return false;
+ }
// See if we can exclude `if` blocks, etc., to narrow down the matches.
// @todo Multiple layers of nested brackets might confuse this.
$sp = '~(?:^|//[^\n]+c\n|\*/|[;}]|' . implode('|', array_filter($placeholders)) . ')\s*' . (strpos($sp, '\K') === false ? '\K' : '') . $sp;
preg_match_all($sp, $settingsText, $matches);
- }
- else
+ } else {
$sp = $substitution['search_pattern'];
+ }
// Found at least some that are simple assignment statements.
- if (count($matches[0]) > 0)
- {
+ if (count($matches[0]) > 0) {
// Remove any duplicates.
- if (count($matches[0]) > 1)
- {
+ if (count($matches[0]) > 1) {
$settingsText = preg_replace($sp, '', $settingsText, count($matches[0]) - 1);
}
@@ -2011,8 +1905,7 @@ function($a, $b) {
}
// All instances are inside more complex code structures.
- else
- {
+ else {
// Only safe option at this point is to skip it.
unset($substitutions[$var], $new_settings_vars[$var], $settings_defs[$var], $simple_replacements[$substitution['placeholder']], $replace_patterns[$var], $replace_strings[$var]);
@@ -2020,25 +1913,21 @@ function($a, $b) {
}
}
// No matches found.
- elseif (count($matches[0]) === 0)
- {
+ elseif (count($matches[0]) === 0) {
$found = false;
$in_c = in_array($var, array_keys($config_vars));
$in_s = in_array($var, array_keys($settings_vars));
// Is it in there at all?
- if (!preg_match('~(^|\s)\$' . preg_quote($var, '~') . '\s*=\s*~', $bare_settingsText))
- {
+ if (!preg_match('~(^|\s)\$' . preg_quote($var, '~') . '\s*=\s*~', $bare_settingsText)) {
// It's defined by Settings.php, but not by code in the file.
// Probably done via an include or something. Skip it.
- if ($in_s)
- {
+ if ($in_s) {
unset($substitutions[$var], $settings_defs[$var]);
}
// Admin is explicitly trying to set this one, so we'll handle
// it as if it were a new custom setting being added.
- elseif ($in_c)
- {
+ elseif ($in_c) {
$new_settings_vars[$var] = $config_vars[$var];
}
@@ -2046,29 +1935,25 @@ function($a, $b) {
}
// It's in there somewhere, so check if the value changed type.
- foreach (array('scalar', 'object', 'array') as $type)
- {
+ foreach (['scalar', 'object', 'array'] as $type) {
// Try all the other scalar types first.
- if ($type == 'scalar')
- {
- $sp = '(?:' . (implode('|', array_diff_key($type_regex, array($in_c ? gettype($config_vars[$var]) : ($in_s ? gettype($settings_vars[$var]) : PHP_INT_MAX) => '', 'array' => '', 'object' => '')))) . ')';
+ if ($type == 'scalar') {
+ $sp = '(?:' . (implode('|', array_diff_key($type_regex, [$in_c ? gettype($config_vars[$var]) : ($in_s ? gettype($settings_vars[$var]) : PHP_INT_MAX) => '', 'array' => '', 'object' => '']))) . ')';
}
// Maybe it's an object? (Probably not, but we should check.)
- elseif ($type == 'object')
- {
- if (strpos($settingsText, '__set_state') === false)
+ elseif ($type == 'object') {
+ if (strpos($settingsText, '__set_state') === false) {
continue;
+ }
$sp = $type_regex['object'];
}
// Maybe it's an array?
- else
- {
+ else {
$sp = $type_regex['array'];
}
- if (preg_match('~(^|\s)\$' . preg_quote($var, '~') . '\s*=\s*' . $sp . '~', $bare_settingsText, $derp))
- {
+ if (preg_match('~(^|\s)\$' . preg_quote($var, '~') . '\s*=\s*' . $sp . '~', $bare_settingsText, $derp)) {
$settingsText = preg_replace('~(^|\s)\$' . preg_quote($var, '~') . '\s*=\s*' . $sp . '~', $substitution['placeholder'], $settingsText);
$found = true;
@@ -2078,8 +1963,7 @@ function($a, $b) {
}
// Something weird is going on. Better just leave it alone.
- if (!$found)
- {
+ if (!$found) {
// $var? What $var? Never heard of it.
unset($substitutions[$var], $new_settings_vars[$var], $settings_defs[$var], $simple_replacements[$substitution['placeholder']], $replace_patterns[$var], $replace_strings[$var]);
@@ -2088,30 +1972,27 @@ function($a, $b) {
}
}
// Good to go, so insert our placeholder.
- else
- {
+ else {
$settingsText = preg_replace($substitution['search_pattern'], $substitution['placeholder'], $settingsText);
}
// Once the code blocks are done, we want to compare to a version without comments.
- if (is_int($last_var) && is_string($var))
+ if (is_int($last_var) && is_string($var)) {
$bare_settingsText = self::stripPhpComments($settingsText);
+ }
$last_var = $var;
}
// Rebuilding requires more work.
- if (!empty($rebuild))
- {
+ if (!empty($rebuild)) {
// Strip out the leading and trailing placeholders to prevent duplication.
- $settingsText = str_replace(array($substitutions[-1]['placeholder'], $substitutions[-2]['placeholder']), '', $settingsText);
+ $settingsText = str_replace([$substitutions[-1]['placeholder'], $substitutions[-2]['placeholder']], '', $settingsText);
// Strip out all our standard comments.
- foreach ($settings_defs as $var => $setting_def)
- {
- if (isset($setting_def['text']))
- {
- $settingsText = strtr($settingsText, array($setting_def['text'] . "\n" => '', $setting_def['text'] => '',));
+ foreach ($settings_defs as $var => $setting_def) {
+ if (isset($setting_def['text'])) {
+ $settingsText = strtr($settingsText, [$setting_def['text'] . "\n" => '', $setting_def['text'] => '']);
}
}
@@ -2119,9 +2000,8 @@ function($a, $b) {
$bare_settingsText = self::stripPhpComments($settingsText);
// Fix up whitespace to make comparison easier.
- foreach ($placeholders as $placeholder)
- {
- $bare_settingsText = str_replace(array($placeholder . "\n\n", $placeholder), $placeholder . "\n", $bare_settingsText);
+ foreach ($placeholders as $placeholder) {
+ $bare_settingsText = str_replace([$placeholder . "\n\n", $placeholder], $placeholder . "\n", $bare_settingsText);
}
$bare_settingsText = preg_replace('/\h+$/m', '', rtrim($bare_settingsText));
@@ -2133,121 +2013,118 @@ function($a, $b) {
* each section, however, we'll reorganize the content to match the
* default layout as closely as we can.
*/
- $sections = array(array());
+ $sections = [[]];
$section_num = 0;
$trimmed_placeholders = array_filter(array_map('trim', $placeholders));
- $newsection_placeholders = array();
+ $newsection_placeholders = [];
$all_custom_content = '';
- foreach ($substitutions as $var => $substitution)
- {
- if (is_int($var) && ($var === -2 || $var > 0) && isset($trimmed_placeholders[$var]) && strpos($bare_settingsText, $trimmed_placeholders[$var]) !== false)
- {
+ foreach ($substitutions as $var => $substitution) {
+ if (is_int($var) && ($var === -2 || $var > 0) && isset($trimmed_placeholders[$var]) && strpos($bare_settingsText, $trimmed_placeholders[$var]) !== false) {
$newsection_placeholders[$var] = $trimmed_placeholders[$var];
}
}
- foreach (preg_split('~(?<=' . implode('|', $trimmed_placeholders) . ')|(?=' . implode('|', $trimmed_placeholders) . ')~', $bare_settingsText) as $part)
- {
+ foreach (preg_split('~(?<=' . implode('|', $trimmed_placeholders) . ')|(?=' . implode('|', $trimmed_placeholders) . ')~', $bare_settingsText) as $part) {
$part = trim($part);
- if (empty($part))
+ if (empty($part)) {
continue;
+ }
// Build a list of placeholders for this section.
- if (in_array($part, $trimmed_placeholders) && !in_array($part, $newsection_placeholders))
- {
+ if (in_array($part, $trimmed_placeholders) && !in_array($part, $newsection_placeholders)) {
$sections[$section_num][] = $part;
}
// Custom content and newsection_placeholders get their own sections.
- else
- {
- if (!empty($sections[$section_num]))
+ else {
+ if (!empty($sections[$section_num])) {
++$section_num;
+ }
$sections[$section_num][] = $part;
++$section_num;
- if (!in_array($part, $trimmed_placeholders))
+ if (!in_array($part, $trimmed_placeholders)) {
$all_custom_content .= "\n" . $part;
+ }
}
}
// And now, rebuild the content!
$new_settingsText = '';
- $done_defs = array();
+ $done_defs = [];
$sectionkeys = array_keys($sections);
- foreach ($sections as $sectionkey => $section)
- {
+ foreach ($sections as $sectionkey => $section) {
// Custom content needs to be preserved.
- if (count($section) === 1 && !in_array($section[0], $trimmed_placeholders))
- {
+ if (count($section) === 1 && !in_array($section[0], $trimmed_placeholders)) {
$prev_section_end = $sectionkey < 1 ? 0 : strpos($settingsText, end($sections[$sectionkey - 1])) + strlen(end($sections[$sectionkey - 1]));
$next_section_start = $sectionkey == end($sectionkeys) ? strlen($settingsText) : strpos($settingsText, $sections[$sectionkey + 1][0]);
$new_settingsText .= "\n" . substr($settingsText, $prev_section_end, $next_section_start - $prev_section_end) . "\n";
}
// Put the placeholders in this section into canonical order.
- else
- {
+ else {
$section_parts = array_flip($section);
$pathcode_reached = false;
- foreach ($settings_defs as $var => $setting_def)
- {
- if ($var === $pathcode_var)
+
+ foreach ($settings_defs as $var => $setting_def) {
+ if ($var === $pathcode_var) {
$pathcode_reached = true;
+ }
// Already did this setting, so move on to the next.
- if (in_array($var, $done_defs))
+ if (in_array($var, $done_defs)) {
continue;
+ }
// Stop when we hit a setting definition that will start a later section.
- if (isset($newsection_placeholders[$var]) && count($section) !== 1)
+ if (isset($newsection_placeholders[$var]) && count($section) !== 1) {
break;
+ }
// Stop when everything in this section is done, unless it's the last.
// This helps maintain the relative position of any custom content.
- if (empty($section_parts) && $sectionkey < (count($sections) - 1))
+ if (empty($section_parts) && $sectionkey < (count($sections) - 1)) {
break;
+ }
$p = trim($substitutions[$var]['placeholder']);
// Can't do anything with an empty placeholder.
- if ($p === '')
+ if ($p === '') {
continue;
+ }
// Does this need to be inserted before the path correction code?
- if (strpos($new_settingsText, trim($substitutions[$pathcode_var]['placeholder'])) !== false && in_array($var, $force_before_pathcode))
- {
- $new_settingsText = strtr($new_settingsText, array($substitutions[$pathcode_var]['placeholder'] => $p . "\n" . $substitutions[$pathcode_var]['placeholder']));
+ if (strpos($new_settingsText, trim($substitutions[$pathcode_var]['placeholder'])) !== false && in_array($var, $force_before_pathcode)) {
+ $new_settingsText = strtr($new_settingsText, [$substitutions[$pathcode_var]['placeholder'] => $p . "\n" . $substitutions[$pathcode_var]['placeholder']]);
$bare_settingsText .= "\n" . $substitutions[$var]['placeholder'];
$done_defs[] = $var;
unset($section_parts[trim($substitutions[$var]['placeholder'])]);
}
// If it's in this section, add it to the new text now.
- elseif (in_array($p, $section))
- {
+ elseif (in_array($p, $section)) {
$new_settingsText .= "\n" . $substitutions[$var]['placeholder'];
$done_defs[] = $var;
unset($section_parts[trim($substitutions[$var]['placeholder'])]);
}
// Perhaps it is safe to reposition it anyway.
- elseif (is_string($var) && strpos($new_settingsText, $p) === false && strpos($all_custom_content, '$' . $var) === false)
- {
+ elseif (is_string($var) && strpos($new_settingsText, $p) === false && strpos($all_custom_content, '$' . $var) === false) {
$new_settingsText .= "\n" . $substitutions[$var]['placeholder'];
$done_defs[] = $var;
unset($section_parts[trim($substitutions[$var]['placeholder'])]);
}
// If this setting is missing entirely, fix it.
- elseif (strpos($bare_settingsText, $p) === false)
- {
+ elseif (strpos($bare_settingsText, $p) === false) {
// Special case if the path code is missing. Put it near the end,
// and also anything else that is missing that normally follows it.
- if (!isset($newsection_placeholders[$pathcode_var]) && $pathcode_reached === true && $sectionkey < (count($sections) - 1))
+ if (!isset($newsection_placeholders[$pathcode_var]) && $pathcode_reached === true && $sectionkey < (count($sections) - 1)) {
break;
+ }
$new_settingsText .= "\n" . $substitutions[$var]['placeholder'];
$bare_settingsText .= "\n" . $substitutions[$var]['placeholder'];
@@ -2260,8 +2137,7 @@ function($a, $b) {
$settingsText = $new_settingsText;
// Restore the leading and trailing placeholders as necessary.
- foreach (array(-1, -2) as $var)
- {
+ foreach ([-1, -2] as $var) {
if (!empty($substitutions[$var]['placeholder']) && strpos($settingsText, $substitutions[$var]['placeholder']) === false);
{
$settingsText = ($var == -1 ? $substitutions[$var]['placeholder'] : '') . $settingsText . ($var == -2 ? $substitutions[$var]['placeholder'] : '');
@@ -2269,20 +2145,16 @@ function($a, $b) {
}
}
// Even if not rebuilding, there are a few variables that may need to be moved around.
- else
- {
+ else {
$pathcode_pos = strpos($settingsText, $substitutions[$pathcode_var]['placeholder']);
- if ($pathcode_pos !== false)
- {
- foreach ($force_before_pathcode as $var)
- {
- if (!empty($substitutions[$var]['placeholder']) && strpos($settingsText, $substitutions[$var]['placeholder']) > $pathcode_pos)
- {
- $settingsText = strtr($settingsText, array(
+ if ($pathcode_pos !== false) {
+ foreach ($force_before_pathcode as $var) {
+ if (!empty($substitutions[$var]['placeholder']) && strpos($settingsText, $substitutions[$var]['placeholder']) > $pathcode_pos) {
+ $settingsText = strtr($settingsText, [
$substitutions[$var]['placeholder'] => '',
$substitutions[$pathcode_var]['placeholder'] => $substitutions[$var]['placeholder'] . "\n" . $substitutions[$pathcode_var]['placeholder'],
- ));
+ ]);
}
}
}
@@ -2294,30 +2166,26 @@ function($a, $b) {
$settingsText = strtr($settingsText, $simple_replacements);
// Deal with any complicated ones.
- if (!empty($replace_patterns))
- {
+ if (!empty($replace_patterns)) {
$settingsText = preg_replace($replace_patterns, $replace_strings, $settingsText);
}
// Make absolutely sure that the path correction code is included.
- if (strpos($settingsText, $substitutions[$pathcode_var]['replacement']) === false)
- {
+ if (strpos($settingsText, $substitutions[$pathcode_var]['replacement']) === false) {
$settingsText = preg_replace('~(?=\n#+ Error.Catching #+)~', "\n" . $substitutions[$pathcode_var]['replacement'] . "\n", $settingsText);
}
// If we did not rebuild, do just enough to make sure the thing is viable.
- if (empty($rebuild))
- {
+ if (empty($rebuild)) {
// We need to refresh $bare_settingsText again, and remove the code blocks from it.
$bare_settingsText = $settingsText;
- foreach ($substitutions as $var => $substitution)
- {
- if (!is_int($var))
+ foreach ($substitutions as $var => $substitution) {
+ if (!is_int($var)) {
break;
+ }
- if (isset($substitution['replacement']))
- {
+ if (isset($substitution['replacement'])) {
$bare_settingsText = str_replace($substitution['replacement'], '', $bare_settingsText);
}
}
@@ -2327,41 +2195,37 @@ function($a, $b) {
// Now insert any defined settings that are missing.
$pathcode_reached = false;
- foreach ($settings_defs as $var => $setting_def)
- {
- if ($var === $pathcode_var)
+ foreach ($settings_defs as $var => $setting_def) {
+ if ($var === $pathcode_var) {
$pathcode_reached = true;
+ }
- if (is_int($var))
+ if (is_int($var)) {
continue;
+ }
// Do nothing if it is already in there.
- if (preg_match($substitutions[$var]['search_pattern'], $bare_settingsText))
+ if (preg_match($substitutions[$var]['search_pattern'], $bare_settingsText)) {
continue;
+ }
// Insert it either before or after the path correction code, whichever is appropriate.
- if (!$pathcode_reached || in_array($var, $force_before_pathcode))
- {
+ if (!$pathcode_reached || in_array($var, $force_before_pathcode)) {
$settingsText = preg_replace($substitutions[$pathcode_var]['search_pattern'], $substitutions[$var]['replacement'] . "\n\n$0", $settingsText);
- }
- else
- {
+ } else {
$settingsText = preg_replace($substitutions[$pathcode_var]['search_pattern'], "$0\n\n" . $substitutions[$var]['replacement'], $settingsText);
}
}
- }
- else
- {
+ } else {
// If the comments for some variables have changed since the last
// time we rebuilt, we could have orphan copies of the old comments
// still laying around.
$prev_var = null;
- foreach ($settings_defs as $var => $setting_def)
- {
- if (!isset($setting_def['text']))
- {
+ foreach ($settings_defs as $var => $setting_def) {
+ if (!isset($setting_def['text'])) {
$prev_var = $var;
+
continue;
}
@@ -2376,12 +2240,9 @@ function($a, $b) {
}
// If we have any brand new settings to add, do so.
- foreach ($new_settings_vars as $var => $val)
- {
- if (isset($substitutions[$var]) && !preg_match($substitutions[$var]['search_pattern'], $settingsText))
- {
- if (!isset($settings_defs[$var]) && strpos($settingsText, '# Custom Settings #') === false)
- {
+ foreach ($new_settings_vars as $var => $val) {
+ if (isset($substitutions[$var]) && !preg_match($substitutions[$var]['search_pattern'], $settingsText)) {
+ if (!isset($settings_defs[$var]) && strpos($settingsText, '# Custom Settings #') === false) {
$settingsText = preg_replace('~(?=\n#+ Error.Catching #+)~', "\n\n######### Custom Settings #########\n", $settingsText);
}
@@ -2404,8 +2265,7 @@ function($a, $b) {
unlink($temp_sfile);
// If the syntax is borked, try rebuilding to see if that fixes it.
- if ($result === false)
- {
+ if ($result === false) {
return empty($rebuild) ? self::updateSettingsFile($config_vars, $keep_quotes, true) : false;
}
@@ -2435,74 +2295,74 @@ function($a, $b) {
* @return array|bool An array of name/value pairs for all settings in the
* file, or false on error.
*/
- public static function getCurrentSettings(int|float $mtime = null, string $settingsFile = SMF_SETTINGS_FILE): array|bool
+ public static function getCurrentSettings(int|float|null $mtime = null, string $settingsFile = SMF_SETTINGS_FILE): array|bool
{
$mtime = is_null($mtime) ? (defined('TIME_START') ? TIME_START : $_SERVER['REQUEST_TIME']) : (int) $mtime;
- if (!is_file($settingsFile))
- {
- if ($settingsFile !== SMF_SETTINGS_FILE && is_file(SMF_SETTINGS_FILE))
- {
+ if (!is_file($settingsFile)) {
+ if ($settingsFile !== SMF_SETTINGS_FILE && is_file(SMF_SETTINGS_FILE)) {
$settingsFile = SMF_SETTINGS_FILE;
- }
- else
- {
- foreach (get_included_files() as $settingsFile)
- {
- if (basename($settingsFile) === basename(SMF_SETTINGS_FILE))
+ } else {
+ foreach (get_included_files() as $settingsFile) {
+ if (basename($settingsFile) === basename(SMF_SETTINGS_FILE)) {
break;
+ }
}
- if (basename($settingsFile) !== basename(SMF_SETTINGS_FILE))
+ if (basename($settingsFile) !== basename(SMF_SETTINGS_FILE)) {
return false;
+ }
}
}
// If the file has been changed since the last known good configuration, bail out.
clearstatcache();
- if (filemtime($settingsFile) > $mtime)
+ if (filemtime($settingsFile) > $mtime) {
return false;
+ }
// Strip out opening and closing PHP tags.
$settingsText = trim(file_get_contents($settingsFile));
- if (substr($settingsText, 0, 5) == '<' . '?php')
+ if (substr($settingsText, 0, 5) == '<' . '?php') {
$settingsText = substr($settingsText, 5);
+ }
- if (substr($settingsText, -2) == '?' . '>')
+ if (substr($settingsText, -2) == '?' . '>') {
$settingsText = substr($settingsText, 0, -2);
+ }
// Since we're using eval, we need to manually replace these with strings.
- $settingsText = strtr($settingsText, array(
+ $settingsText = strtr($settingsText, [
'__FILE__' => var_export($settingsFile, true),
'__DIR__' => var_export(dirname($settingsFile), true),
- ));
+ ]);
// Prevents warnings about constants that are already defined.
$settingsText = preg_replace_callback(
'~\bdefine\s*\(\s*(["\'])(\w+)\1~',
- function ($matches)
- {
+ function ($matches) {
return 'define(\'' . md5(mt_rand()) . '\'';
},
- $settingsText
+ $settingsText,
);
// Handle eval errors gracefully in all PHP versions.
- try
- {
- if ($settingsText !== '' && @eval($settingsText) === false)
+ try {
+ if ($settingsText !== '' && @eval($settingsText) === false) {
throw new ErrorException('eval error');
+ }
unset($mtime, $settingsFile, $settingsText);
$defined_vars = get_defined_vars();
+ } catch (Throwable $e) {
+ } catch (ErrorException $e) {
}
- catch (Throwable $e) {}
- catch (ErrorException $e) {}
- if (isset($e))
+ if (isset($e)) {
return false;
+ }
return $defined_vars;
}
@@ -2523,69 +2383,68 @@ function ($matches)
* overwriting the existing content of the file. Default false.
* @return bool Whether the write operation succeeded or not.
*/
- public static function safeFileWrite(string $file, string $data, string|null $backup_file = null, int|null $mtime = null, bool $append = false): bool
+ public static function safeFileWrite(string $file, string $data, ?string $backup_file = null, ?int $mtime = null, bool $append = false): bool
{
// Sanity checks.
- if (!file_exists($file) && !is_dir(dirname($file)))
+ if (!file_exists($file) && !is_dir(dirname($file))) {
return false;
+ }
- if (!is_int($mtime))
+ if (!is_int($mtime)) {
$mtime = defined('TIME_START') ? (int) TIME_START : $_SERVER['REQUEST_TIME'];
+ }
- if (!isset(self::$temp_dir))
+ if (!isset(self::$temp_dir)) {
self::getTempDir();
+ }
// Our temp files.
$temp_sfile = tempnam(self::$temp_dir . DIRECTORY_SEPARATOR, pathinfo($file, PATHINFO_FILENAME) . '.');
- if (!empty($backup_file))
- {
+ if (!empty($backup_file)) {
$temp_bfile = tempnam(self::$temp_dir, pathinfo($backup_file, PATHINFO_FILENAME) . '.');
}
// We need write permissions.
$failed = false;
- foreach (array($file, $backup_file) as $sf)
- {
- if (empty($sf))
+ foreach ([$file, $backup_file] as $sf) {
+ if (empty($sf)) {
continue;
+ }
- if (!file_exists($sf))
- {
+ if (!file_exists($sf)) {
touch($sf);
- }
- elseif (!is_file($sf))
- {
+ } elseif (!is_file($sf)) {
$failed = true;
}
- if (!$failed)
+ if (!$failed) {
$failed = !is_writable($sf);
+ }
}
// Now let's see if writing to a temp file succeeds.
- if (!$failed && file_put_contents($temp_sfile, $data, LOCK_EX) !== strlen($data))
+ if (!$failed && file_put_contents($temp_sfile, $data, LOCK_EX) !== strlen($data)) {
$failed = true;
+ }
// Tests passed, so it's time to do the job.
- if (!$failed)
- {
+ if (!$failed) {
// Back up the backup, just in case.
- if (!empty($backup_file) && file_exists($backup_file))
+ if (!empty($backup_file) && file_exists($backup_file)) {
$temp_bfile_saved = @copy($backup_file, $temp_bfile);
+ }
// Make sure no one changed the file while we weren't looking.
clearstatcache();
- if ((int) filemtime($file) <= $mtime)
- {
+ if ((int) filemtime($file) <= $mtime) {
// Attempt to open the file.
$sfhandle = @fopen($file, 'c');
// Let's do this thing!
- if ($sfhandle !== false)
- {
+ if ($sfhandle !== false) {
// Immediately get a lock.
flock($sfhandle, LOCK_EX);
@@ -2593,33 +2452,29 @@ public static function safeFileWrite(string $file, string $data, string|null $ba
$temp_sfile_saved = @copy($file, $temp_sfile);
// Now write our data to the file.
- if ($temp_sfile_saved)
- {
- if (empty($append))
- {
+ if ($temp_sfile_saved) {
+ if (empty($append)) {
ftruncate($sfhandle, 0);
rewind($sfhandle);
}
$failed = fwrite($sfhandle, $data) !== strlen($data);
- }
- else
- {
+ } else {
$failed = true;
}
// If writing failed, put everything back the way it was.
- if ($failed)
- {
- if (!empty($temp_sfile_saved))
+ if ($failed) {
+ if (!empty($temp_sfile_saved)) {
@rename($temp_sfile, $file);
+ }
- if (!empty($temp_bfile_saved))
+ if (!empty($temp_bfile_saved)) {
@rename($temp_bfile, $backup_file);
+ }
}
// It worked, so make our temp backup the new permanent backup.
- elseif (!empty($backup_file))
- {
+ elseif (!empty($backup_file)) {
@rename($temp_sfile, $backup_file);
}
@@ -2633,17 +2488,20 @@ public static function safeFileWrite(string $file, string $data, string|null $ba
// We're done with these.
@unlink($temp_sfile);
- if (!empty($temp_bfile))
+ if (!empty($temp_bfile)) {
@unlink($temp_bfile);
+ }
- if ($failed)
+ if ($failed) {
return false;
+ }
// Even though on normal installations the filemtime should invalidate
// any cached version, it seems that there are times it might not.
// So let's MAKE it dump the cache.
- if (function_exists('opcache_invalidate'))
+ if (function_exists('opcache_invalidate')) {
opcache_invalidate($file, true);
+ }
return true;
}
@@ -2663,38 +2521,35 @@ public static function varExport($var): string
* Even though technically we can now, we'll keep arrays on one line for
* the sake of backwards compatibility.
*/
- if (is_array($var))
- {
- $return = array();
+ if (is_array($var)) {
+ $return = [];
- foreach ($var as $key => $value)
+ foreach ($var as $key => $value) {
$return[] = var_export($key, true) . ' => ' . self::varExport($value);
+ }
return 'array(' . implode(', ', $return) . ')';
}
+
// For the same reason, replace literal returns and newlines with "\r" and "\n"
- elseif (is_string($var) && (strpos($var, "\n") !== false || strpos($var, "\r") !== false))
- {
+ if (is_string($var) && (strpos($var, "\n") !== false || strpos($var, "\r") !== false)) {
return strtr(
preg_replace_callback(
'/[\r\n]+/',
- function($m)
- {
- return '\' . "' . strtr($m[0], array("\r" => '\r', "\n" => '\n')) . '" . \'';
+ function ($m) {
+ return '\' . "' . strtr($m[0], ["\r" => '\r', "\n" => '\n']) . '" . \'';
},
- var_export($var, true)
+ var_export($var, true),
),
- array("'' . " => '', " . ''" => '')
+ ["'' . " => '', " . ''" => ''],
);
}
// We typically use lowercase true/false/null.
- elseif (in_array(gettype($var), array('boolean', 'NULL')))
- {
+ elseif (in_array(gettype($var), ['boolean', 'NULL'])) {
return strtolower(var_export($var, true));
}
// Nothing special.
- else
- {
+ else {
return var_export($var, true);
}
}
@@ -2708,24 +2563,18 @@ function($m)
public static function stripPhpComments(string $code_str): string
{
// This is the faster, better way.
- if (is_callable('token_get_all'))
- {
+ if (is_callable('token_get_all')) {
$tokens = token_get_all($code_str);
- $parts = array();
+ $parts = [];
- foreach ($tokens as $token)
- {
- if (is_string($token))
- {
+ foreach ($tokens as $token) {
+ if (is_string($token)) {
$parts[] = $token;
- }
- else
- {
+ } else {
list($id, $text) = $token;
- switch ($id)
- {
+ switch ($id) {
case T_COMMENT:
case T_DOC_COMMENT:
end($parts);
@@ -2737,14 +2586,10 @@ public static function stripPhpComments(string $code_str): string
// For 'C' style comments, also trim one preceding
// line break, if present.
- if (strpos($text, '/*') === 0)
- {
- if (substr($parts[$prev_part], -2) === "\r\n")
- {
+ if (strpos($text, '/*') === 0) {
+ if (substr($parts[$prev_part], -2) === "\r\n") {
$parts[$prev_part] = substr($parts[$prev_part], 0, -2);
- }
- elseif (in_array(substr($parts[$prev_part], -1), array("\r", "\n")))
- {
+ } elseif (in_array(substr($parts[$prev_part], -1), ["\r", "\n"])) {
$parts[$prev_part] = substr($parts[$prev_part], 0, -1);
}
}
@@ -2766,12 +2611,10 @@ public static function stripPhpComments(string $code_str): string
// If the tokenizer extension has been disabled, do the job manually.
// Leave any heredocs alone.
- if (preg_match_all('/<<<([\'"]?)(\w+)\1?\R(.*?)\R\h*\2;$/ms', $code_str, $matches))
- {
- $heredoc_replacements = array();
+ if (preg_match_all('/<<<([\'"]?)(\w+)\1?\R(.*?)\R\h*\2;$/ms', $code_str, $matches)) {
+ $heredoc_replacements = [];
- foreach ($matches[0] as $mkey => $heredoc)
- {
+ foreach ($matches[0] as $mkey => $heredoc) {
$heredoc_replacements[$heredoc] = var_export(md5($matches[3][$mkey]), true) . ';';
}
@@ -2783,8 +2626,8 @@ public static function stripPhpComments(string $code_str): string
$in_string = 0;
$in_comment = 0;
- foreach ($parts as $partkey => $part)
- {
+
+ foreach ($parts as $partkey => $part) {
$one_char = substr($part, 0, 1);
$two_char = substr($part, 0, 2);
$to_remove = 0;
@@ -2795,25 +2638,16 @@ public static function stripPhpComments(string $code_str): string
* 1: in a single quote string
* 2: in a double quote string
*/
- if ($one_char == "'")
- {
- if (!empty($in_comment))
- {
+ if ($one_char == "'") {
+ if (!empty($in_comment)) {
$in_string = 0;
- }
- elseif (in_array($in_string, array(0, 1)))
- {
+ } elseif (in_array($in_string, [0, 1])) {
$in_string = ($in_string ^ 1);
}
- }
- elseif ($one_char == '"')
- {
- if (!empty($in_comment))
- {
+ } elseif ($one_char == '"') {
+ if (!empty($in_comment)) {
$in_string = 0;
- }
- elseif (in_array($in_string, array(0, 2)))
- {
+ } elseif (in_array($in_string, [0, 2])) {
$in_string = ($in_string ^ 2);
}
}
@@ -2824,51 +2658,36 @@ public static function stripPhpComments(string $code_str): string
* 1: in a single line comment
* 2: in a multi-line comment
*/
- elseif ($one_char == '#' || $two_char == '//')
- {
+ elseif ($one_char == '#' || $two_char == '//') {
$in_comment = !empty($in_string) ? 0 : (empty($in_comment) ? 1 : $in_comment);
- if ($in_comment == 1)
- {
+ if ($in_comment == 1) {
$parts[$partkey - 1] = rtrim($parts[$partkey - 1], "\t ");
- if (substr($parts[$partkey - 1], -2) === "\r\n")
- {
+ if (substr($parts[$partkey - 1], -2) === "\r\n") {
$parts[$partkey - 1] = substr($parts[$partkey - 1], 0, -2);
- }
- elseif (in_array(substr($parts[$partkey - 1], -1), array("\r", "\n")))
- {
+ } elseif (in_array(substr($parts[$partkey - 1], -1), ["\r", "\n"])) {
$parts[$partkey - 1] = substr($parts[$partkey - 1], 0, -1);
}
}
- }
- elseif ($two_char === "\r\n" || $one_char === "\r" || $one_char === "\n")
- {
- if ($in_comment == 1)
+ } elseif ($two_char === "\r\n" || $one_char === "\r" || $one_char === "\n") {
+ if ($in_comment == 1) {
$in_comment = 0;
- }
- elseif ($two_char == '/*')
- {
+ }
+ } elseif ($two_char == '/*') {
$in_comment = !empty($in_string) ? 0 : (empty($in_comment) ? 2 : $in_comment);
- if ($in_comment == 2)
- {
+ if ($in_comment == 2) {
$parts[$partkey - 1] = rtrim($parts[$partkey - 1], "\t ");
- if (substr($parts[$partkey - 1], -2) === "\r\n")
- {
+ if (substr($parts[$partkey - 1], -2) === "\r\n") {
$parts[$partkey - 1] = substr($parts[$partkey - 1], 0, -2);
- }
- elseif (in_array(substr($parts[$partkey - 1], -1), array("\r", "\n")))
- {
+ } elseif (in_array(substr($parts[$partkey - 1], -1), ["\r", "\n"])) {
$parts[$partkey - 1] = substr($parts[$partkey - 1], 0, -1);
}
}
- }
- elseif ($two_char == '*/')
- {
- if ($in_comment == 2)
- {
+ } elseif ($two_char == '*/') {
+ if ($in_comment == 2) {
$in_comment = 0;
// Delete the comment closing.
@@ -2876,20 +2695,18 @@ public static function stripPhpComments(string $code_str): string
}
}
- if (empty($in_comment))
- {
+ if (empty($in_comment)) {
$parts[$partkey] = strlen($part) > $to_remove ? substr($part, $to_remove) : '';
- }
- else
- {
+ } else {
$parts[$partkey] = '';
}
}
$code_str = implode('', $parts);
- if (!empty($heredoc_replacements))
+ if (!empty($heredoc_replacements)) {
$code_str = strtr($code_str, array_flip($heredoc_replacements));
+ }
return $code_str;
}
@@ -2909,16 +2726,11 @@ public static function stripPhpComments(string $code_str): string
public static function updateDbLastError(int $time, bool $update = true): bool
{
// Write out the db_last_error file with the error timestamp
- if (!empty(self::$cachedir) && is_writable(self::$cachedir))
- {
+ if (!empty(self::$cachedir) && is_writable(self::$cachedir)) {
$errorfile = self::$cachedir . '/db_last_error.php';
- }
- elseif (file_exists(dirname(__DIR__) . '/cache'))
- {
+ } elseif (file_exists(dirname(__DIR__) . '/cache')) {
$errorfile = dirname(__DIR__) . '/cache/db_last_error.php';
- }
- else
- {
+ } else {
$errorfile = dirname(__DIR__) . '/db_last_error.php';
}
@@ -2927,8 +2739,9 @@ public static function updateDbLastError(int $time, bool $update = true): bool
@touch(SMF_SETTINGS_FILE);
// Unless requested, we should update self::$db_last_error as well.
- if ($update)
+ if ($update) {
self::$db_last_error = $time;
+ }
// We do a loose match here rather than strict (!==) as 0 is also false.
return $result != false;
@@ -2956,21 +2769,21 @@ public static function updateDbLastError(int $time, bool $update = true): bool
public static function getTempDir(): string
{
// Already did this.
- if (!empty(self::$temp_dir))
+ if (!empty(self::$temp_dir)) {
return self::$temp_dir;
+ }
// Temp Directory options order.
- $temp_dir_options = array(
+ $temp_dir_options = [
0 => 'sys_get_temp_dir',
1 => 'upload_tmp_dir',
2 => 'session.save_path',
3 => 'cachedir',
- );
+ ];
// Is self::$cachedir a valid option?
- if (empty(self::$cachedir) || !is_dir(self::$cachedir) || !is_writable(self::$cachedir))
- {
- $temp_dir_options = array_diff($temp_dir_options, array('cachedir'));
+ if (empty(self::$cachedir) || !is_dir(self::$cachedir) || !is_writable(self::$cachedir)) {
+ $temp_dir_options = array_diff($temp_dir_options, ['cachedir']);
}
// Determine if we should detect a restriction and what restrictions that may be.
@@ -2981,10 +2794,8 @@ public static function getTempDir(): string
$old_error_reporting = error_reporting(0);
// Search for a working temp directory.
- foreach ($temp_dir_options as $id_temp => $temp_option)
- {
- switch ($temp_option)
- {
+ foreach ($temp_dir_options as $id_temp => $temp_option) {
+ switch ($temp_option) {
case 'cachedir':
$possible_temp = rtrim(self::$cachedir, '\\/');
break;
@@ -3003,28 +2814,25 @@ public static function getTempDir(): string
}
// Check if we have a restriction preventing this from working.
- if ($restriction)
- {
- foreach ($restriction as $dir)
- {
- if (strpos($possible_temp, $dir) !== false && is_writable($possible_temp))
- {
+ if ($restriction) {
+ foreach ($restriction as $dir) {
+ if (strpos($possible_temp, $dir) !== false && is_writable($possible_temp)) {
self::$temp_dir = $possible_temp;
break;
}
}
}
// No restrictions, but need to check for writable status.
- elseif (is_writable($possible_temp))
- {
+ elseif (is_writable($possible_temp)) {
self::$temp_dir = $possible_temp;
break;
}
}
// Fall back to sys_get_temp_dir even though it won't work, so we have something.
- if (empty(self::$temp_dir))
+ if (empty(self::$temp_dir)) {
self::$temp_dir = sys_get_temp_dir();
+ }
// Put things back.
error_reporting($old_error_reporting);
@@ -3050,12 +2858,12 @@ public static function setMemoryLimit(string $needed, bool $in_use = false): boo
$memory_needed = self::memoryReturnBytes($needed);
// Should we account for how much is currently being used?
- if ($in_use)
+ if ($in_use) {
$memory_needed += memory_get_usage();
+ }
// If more is needed, request it.
- if ($memory_current < $memory_needed)
- {
+ if ($memory_current < $memory_needed) {
@ini_set('memory_limit', ceil($memory_needed / 1048576) . 'M');
$memory_current = self::memoryReturnBytes(ini_get('memory_limit'));
}
@@ -3070,12 +2878,13 @@ public static function setMemoryLimit(string $needed, bool $in_use = false): boo
* Helper function to convert memory string settings to bytes
*
* @param string $val The byte string, like '256M' or '1G'.
- * @return integer The string converted to a proper integer in bytes.
+ * @return int The string converted to a proper integer in bytes.
*/
public static function memoryReturnBytes(string $val): int
{
- if (is_integer($val))
+ if (is_integer($val)) {
return $val;
+ }
// Separate the number from the designator.
$val = trim($val);
@@ -3083,12 +2892,15 @@ public static function memoryReturnBytes(string $val): int
$last = strtolower(substr($val, -1));
// Convert to bytes.
- switch ($last)
- {
+ switch ($last) {
case 'g':
$num *= 1024;
+ // no break
+
case 'm':
$num *= 1024;
+ // no break
+
case 'k':
$num *= 1024;
}
@@ -3116,7 +2928,7 @@ public static function httpsOn(): bool
*/
public static function generateSeed(): void
{
- self::updateModSettings(array('rand_seed' => Utils::randomInt(0, 2**31 - 1)));
+ self::updateModSettings(['rand_seed' => Utils::randomInt(0, 2 ** 31 - 1)]);
}
/**
@@ -3128,35 +2940,31 @@ public static function generateSeed(): void
*/
public static function checkCron()
{
- if (!empty(self::$modSettings['cron_is_real_cron']) && time() - @intval(self::$modSettings['cron_last_checked']) > 84600)
- {
- $request = Db\DatabaseApi::$db->query('', '
- SELECT COUNT(*)
+ if (!empty(self::$modSettings['cron_is_real_cron']) && time() - @intval(self::$modSettings['cron_last_checked']) > 86400) {
+ $request = Db\DatabaseApi::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}scheduled_tasks
WHERE disabled = {int:not_disabled}
AND next_time < {int:yesterday}',
- array(
+ [
'not_disabled' => 0,
- 'yesterday' => time() - 84600,
- )
+ 'yesterday' => time() - 86400,
+ ],
);
list($overdue) = Db\DatabaseApi::$db->fetch_row($request);
Db\DatabaseApi::$db->free_result($request);
// If we have tasks more than a day overdue, cron isn't doing its job.
- if (!empty($overdue))
- {
+ if (!empty($overdue)) {
Lang::load('ManageScheduledTasks');
ErrorHandler::log(Lang::$txt['cron_not_working']);
- self::updateModSettings(array('cron_is_real_cron' => 0));
- }
- else
- {
- self::updateModSettings(array('cron_last_checked' => time()));
+ self::updateModSettings(['cron_is_real_cron' => 0]);
+ } else {
+ self::updateModSettings(['cron_last_checked' => time()]);
}
}
}
-
}
?>
\ No newline at end of file
diff --git a/Sources/Cookie.php b/Sources/Cookie.php
index c73936b22f..421da2d70f 100644
--- a/Sources/Cookie.php
+++ b/Sources/Cookie.php
@@ -25,15 +25,15 @@ class Cookie
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
- 'getCookie' => false,
+ private static $backcompat = [
+ 'func_names' => [
+ 'setLoginCookie' => 'setLoginCookie',
+ 'setTFACookie' => 'setTFACookie',
'urlParts' => 'url_parts',
'encrypt' => 'hash_salt',
- 'setDefaults' => false,
'setcookie' => 'smf_setcookie',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -41,7 +41,7 @@ class Cookie
/**
* @var string
- *
+ *
* The name of the cookie.
*/
public string $name;
@@ -57,7 +57,7 @@ class Cookie
/**
* @var int
- *
+ *
* The member this cookie is for.
*
* Only normally used for login and TFA cookies.
@@ -77,14 +77,14 @@ class Cookie
/**
* @var int
- *
+ *
* UNIX timestamp of the expiry date of the cookie.
*/
public int $expires;
/**
* @var string
- *
+ *
* The domain of the site where the cookie is used.
* This is normally the domain name of the forum's site.
*/
@@ -92,7 +92,7 @@ class Cookie
/**
* @var string
- *
+ *
* The path to the part of the site where the cookie is used.
* This is normally the URL path to the forum.
*/
@@ -145,7 +145,7 @@ class Cookie
/**
* Constructor.
- *
+ *
* @param string $name Name of the cookie.
* @param mixed $custom_data Data to include in the cookie.
* @param int $expires When the cookie expires.
@@ -162,25 +162,23 @@ class Cookie
* If not set, determined by Config::$modSettings['samesiteCookies'].
*/
public function __construct(
- string $name = null,
+ ?string $name = null,
mixed $custom_data = null,
?int $expires = null,
?string $domain = null,
?string $path = null,
?bool $secure = null,
?bool $httponly = null,
- ?string $samesite = null
- )
- {
+ ?string $samesite = null,
+ ) {
self::setDefaults();
$this->name = $name ?? Config::$cookiename;
- $this->custom_data = $custom_data ?? array();
+ $this->custom_data = $custom_data ?? [];
// Special case for the login and TFA cookies.
- if (in_array($this->name, array(Config::$cookiename, Config::$cookiename . '_tfa')))
- {
+ if (in_array($this->name, [Config::$cookiename, Config::$cookiename . '_tfa'])) {
$this->member = $this->custom_data[0] ?? User::$me->id;
$this->hash = $this->custom_data[1] ?? self::encrypt(User::$me->passwd, User::$me->password_salt);
@@ -188,27 +186,28 @@ public function __construct(
$domain = $domain ?? $this->custom_data[3] ?? null;
$path = $path ?? $this->custom_data[4] ?? null;
- for ($i = 0; $i <= 4; $i++)
+ for ($i = 0; $i <= 4; $i++) {
unset($this->custom_data[$i]);
+ }
}
$this->expires = $expires ?? time() + 60 * Config::$modSettings['cookieTime'];
$this->domain = $domain ?? self::$default_domain;
$this->path = $path ?? self::$default_path;
$this->secure = $secure ?? !empty(Config::$modSettings['secureCookies']);
- $this->httponly = $httponly ?? !empty(Config::$modSettings['httponlyCookies']);;
+ $this->httponly = $httponly ?? !empty(Config::$modSettings['httponlyCookies']);
$this->samesite = $samesite ?? !empty(Config::$modSettings['samesiteCookies']) ? Config::$modSettings['samesiteCookies'] : 'lax';
// Allow mods to add custom info to the cookie
- $data = $this->name !== Config::$cookiename ? array() : array(
+ $data = $this->name !== Config::$cookiename ? [] : [
$this->member,
$this->hash,
$this->expires,
$this->domain,
$this->path,
- );
+ ];
- IntegrationHook::call('integrate_cookie_data', array($data, &$this->custom_data));
+ IntegrationHook::call('integrate_cookie_data', [$data, &$this->custom_data]);
}
/**
@@ -216,41 +215,36 @@ public function __construct(
*/
public function set()
{
- if (in_array($this->name, array(Config::$cookiename, Config::$cookiename . '_tfa')))
- {
- $data = array(
+ if (in_array($this->name, [Config::$cookiename, Config::$cookiename . '_tfa'])) {
+ $data = [
$this->member,
$this->hash,
$this->expires,
$this->domain,
$this->path,
- );
+ ];
$data = array_merge($data, (array) $this->custom_data);
$value = Utils::jsonEncode($data, JSON_FORCE_OBJECT);
- }
- elseif (!is_scalar($this->custom_data))
- {
+ } elseif (!is_scalar($this->custom_data)) {
$value = Utils::jsonEncode($this->custom_data, JSON_FORCE_OBJECT);
- }
- else
- {
+ } else {
$value = $this->custom_data;
}
// MOD AUTHORS: This hook just informs you about the cookie. If you want
// to change the cookie data, use integrate_cookie_data instead.
- IntegrationHook::call('integrate_cookie', array($this->name, $value, $this->expires, $this->path, $this->domain, $this->secure, $this->httponly, $this->samesite));
+ IntegrationHook::call('integrate_cookie', [$this->name, $value, $this->expires, $this->path, $this->domain, $this->secure, $this->httponly, $this->samesite]);
- return setcookie($this->name, $value, array(
+ return setcookie($this->name, $value, [
'expires' => $this->expires,
'path' => $this->path,
'domain' => $this->domain,
'secure' => $this->secure,
'httponly' => $this->httponly,
'samesite' => $this->samesite,
- ));
+ ]);
}
/***********************
@@ -265,41 +259,37 @@ public function set()
* @return object|null An instance of this class for the cookie, or null
* if no cookie with that name was sent by the client.
*/
- public static function getCookie(string $name): object|null
+ public static function getCookie(string $name): ?object
{
- if (!isset($_COOKIE[$name]))
+ if (!isset($_COOKIE[$name])) {
return null;
+ }
// Special case for the login cookie.
- if ($name === Config::$cookiename)
- {
+ if ($name === Config::$cookiename) {
// First check for JSON-format cookie
- if (preg_match('~^{"0":\d+,"1":"[0-9a-f]*","2":\d+,"3":"[^"]+","4":"[^"]+"~', $_COOKIE[$name]))
- {
+ if (preg_match('~^{"0":\d+,"1":"[0-9a-f]*","2":\d+,"3":"[^"]+","4":"[^"]+"~', $_COOKIE[$name])) {
$data = Utils::jsonDecode($_COOKIE[$name], true);
}
// Legacy format (for recent upgrades from SMF 2.0.x)
- elseif (preg_match('~^a:[34]:\{i:0;i:\d+;i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d+;(i:3;i:\d;)?~', $_COOKIE[$name]))
- {
+ elseif (preg_match('~^a:[34]:\{i:0;i:\d+;i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d+;(i:3;i:\d;)?~', $_COOKIE[$name])) {
$data = Utils::safeUnserialize($_COOKIE[$name]);
- list(,,, $state) = $data;
+ list(, , , $state) = $data;
$cookie_state = (empty(Config::$modSettings['localCookies']) ? 0 : 1) | (empty(Config::$modSettings['globalCookies']) ? 0 : 2);
// Maybe we need to temporarily pretend to be using local cookies
- if ($cookie_state == 0 && $state == 1)
- {
+ if ($cookie_state == 0 && $state == 1) {
list($data[3], $data[4]) = self::urlParts(true, false);
- }
- else
- {
+ } else {
list($data[3], $data[4]) = self::urlParts($state & 1 > 0, $state & 2 > 0);
}
}
- if (!isset($data))
+ if (!isset($data)) {
return null;
+ }
$member = (int) ($data[0] ?? 0);
$hash = (string) ($data[1] ?? '');
@@ -307,15 +297,16 @@ public static function getCookie(string $name): object|null
$domain = $data[3] ?? null;
$path = $data[4] ?? null;
- return new self($name, array($member, $hash), $expires, $domain, $path);
+ return new self($name, [$member, $hash], $expires, $domain, $path);
}
+
// Special case for the TFA cookie.
- elseif ($name === Config::$cookiename . '_tfa')
- {
+ if ($name === Config::$cookiename . '_tfa') {
$data = Utils::jsonDecode($_COOKIE[$name], true);
- if (json_last_error() !== JSON_ERROR_NONE)
+ if (json_last_error() !== JSON_ERROR_NONE) {
return null;
+ }
$member = (int) ($data[0] ?? 0);
$hash = (string) ($data[1] ?? '');
@@ -323,18 +314,17 @@ public static function getCookie(string $name): object|null
$domain = (string) ($data[3] ?? '');
$path = (string) ($data[4] ?? '');
- return new self($name, array($member, $hash), $expires, $domain, $path);
+ return new self($name, [$member, $hash], $expires, $domain, $path);
}
- // Other cookies.
- else
- {
- $data = Utils::jsonDecode($_COOKIE[$name], true, false);
- if (json_last_error() !== JSON_ERROR_NONE)
- $data = $_COOKIE[$name];
+ // Other cookies.
+ $data = Utils::jsonDecode($_COOKIE[$name], true, false);
- return new self($name, $data);
+ if (json_last_error() !== JSON_ERROR_NONE) {
+ $data = $_COOKIE[$name];
}
+
+ return new self($name, $data);
}
/**
@@ -366,44 +356,41 @@ public static function setLoginCookie($cookie_length, $id, $password = '')
$old_cookie = self::getCookie(Config::$cookiename);
// Out with the old, in with the new!
- if (($old_cookie->domain ?? self::$default_domain) != self::$default_domain || ($old_cookie->path ?? self::$default_path) != self::$default_path)
- {
+ if (($old_cookie->domain ?? self::$default_domain) != self::$default_domain || ($old_cookie->path ?? self::$default_path) != self::$default_path) {
$old_domain = $old_cookie->domain;
$old_path = $old_cookie->path;
- $cookie = new self(Config::$cookiename, array(0, ''), 0, $old_domain, $old_path);
+ $cookie = new self(Config::$cookiename, [0, ''], 0, $old_domain, $old_path);
$cookie->set();
}
// Set the cookie, $_COOKIE, and session variable.
- $cookie = new self(Config::$cookiename, array($id, $password), $expires);
+ $cookie = new self(Config::$cookiename, [$id, $password], $expires);
$cookie->set();
// If subdomain-independent cookies are on, unset the subdomain-dependent cookie too.
- if (empty($id) && !empty(Config::$modSettings['globalCookies']))
- {
+ if (empty($id) && !empty(Config::$modSettings['globalCookies'])) {
$cookie->domain = '';
$cookie->set();
$cookie->domain = self::$default_domain;
}
// Any alias URLs? This is mainly for use with frames, etc.
- if (!empty(Config::$modSettings['forum_alias_urls']))
- {
+ if (!empty(Config::$modSettings['forum_alias_urls'])) {
$aliases = explode(',', Config::$modSettings['forum_alias_urls']);
$temp = Config::$boardurl;
- foreach ($aliases as $alias)
- {
+ foreach ($aliases as $alias) {
// Fake the Config::$boardurl so we can set a different cookie.
- $alias = strtr(trim($alias), array('http://' => '', 'https://' => ''));
+ $alias = strtr(trim($alias), ['http://' => '', 'https://' => '']);
Config::$boardurl = 'http://' . $alias;
list($domain, $path) = self::urlParts(!empty(Config::$modSettings['localCookies']), !empty(Config::$modSettings['globalCookies']));
- if ($domain == '')
+ if ($domain == '') {
$domain = strtok($alias, '/');
+ }
$alias_cookie = clone $cookie;
$alias_cookie->data[3] = $alias_cookie->domain = $domain;
@@ -415,22 +402,21 @@ public static function setLoginCookie($cookie_length, $id, $password = '')
}
$_COOKIE[Config::$cookiename] = Utils::jsonEncode(
- array(
+ [
$cookie->member,
$cookie->hash,
$cookie->expires,
$cookie->domain,
$cookie->path,
- ),
- JSON_FORCE_OBJECT
+ ],
+ JSON_FORCE_OBJECT,
);
// Make sure the user logs in with a new session ID.
- if (($_SESSION['login_' . Config::$cookiename] ?? null) !== $_COOKIE[Config::$cookiename])
- {
+ if (($_SESSION['login_' . Config::$cookiename] ?? null) !== $_COOKIE[Config::$cookiename]) {
// Backup and remove the old session.
$oldSessionData = $_SESSION;
- $_SESSION = array();
+ $_SESSION = [];
session_destroy();
// Recreate and restore the new session.
@@ -459,26 +445,25 @@ public static function setTFACookie($cookie_length, $id, $secret)
$expires = ($cookie_length >= 0 ? time() + $cookie_length : 1);
// Set the cookie, $_COOKIE, and session variable.
- $cookie = new self(Config::$cookiename . '_tfa', array($id, $secret), $expires);
+ $cookie = new self(Config::$cookiename . '_tfa', [$id, $secret], $expires);
$cookie->set();
// If subdomain-independent cookies are on, unset the subdomain-dependent cookie too.
- if (empty($id) && !empty(Config::$modSettings['globalCookies']))
- {
+ if (empty($id) && !empty(Config::$modSettings['globalCookies'])) {
$cookie->domain = '';
$cookie->set();
$cookie->domain = self::$default_domain;
}
$_COOKIE[Config::$cookiename . '_tfa'] = Utils::jsonEncode(
- array(
+ [
$cookie->member,
$cookie->hash,
$cookie->expires,
$cookie->domain,
$cookie->path,
- ),
- JSON_FORCE_OBJECT
+ ],
+ JSON_FORCE_OBJECT,
);
}
@@ -506,27 +491,23 @@ public static function urlParts($local, $global)
// Manually specified the global domain.
// @todo Why doesn't this check whether $global is true?
- if (!empty(Config::$modSettings['globalCookiesDomain']) && strpos(Config::$boardurl, Config::$modSettings['globalCookiesDomain']) !== false)
- {
+ if (!empty(Config::$modSettings['globalCookiesDomain']) && strpos(Config::$boardurl, Config::$modSettings['globalCookiesDomain']) !== false) {
$host = Config::$modSettings['globalCookiesDomain'];
}
// Globalize cookies across domains? (filter out IP-addresses)
- elseif ($global && preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $host) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $host, $parts) == 1)
- {
+ elseif ($global && preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $host) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $host, $parts) == 1) {
$host = '.' . $parts[1];
}
// We shouldn't use a host at all if both options are off.
- elseif (!$local && !$global)
- {
+ elseif (!$local && !$global) {
$host = '';
}
// The host also shouldn't be set if there aren't any dots in it.
- elseif (!isset($host) || strpos($host, '.') === false)
- {
+ elseif (!isset($host) || strpos($host, '.') === false) {
$host = '';
}
- return array($host, $path . '/');
+ return [$host, $path . '/'];
}
/**
@@ -552,8 +533,9 @@ public static function encrypt($password, $salt)
*/
public static function setDefaults(): void
{
- if (isset(self::$default_domain, self::$default_path))
+ if (isset(self::$default_domain, self::$default_path)) {
return;
+ }
list(self::$default_domain, self::$default_path) = self::urlParts(!empty(Config::$modSettings['localCookies']), !empty(Config::$modSettings['globalCookies']));
}
@@ -561,7 +543,7 @@ public static function setDefaults(): void
/**
* Backward compatibility wrapper for the set() method.
*/
- public static function setcookie(string $name, string $value = '', int $expires = 0, string $path = '', string $domain = '', bool $secure = null, bool $httponly = true, string $samesite = null): void
+ public static function setcookie(string $name, string $value = '', int $expires = 0, string $path = '', string $domain = '', ?bool $secure = null, bool $httponly = true, ?string $samesite = null): void
{
$data = Utils::jsonDecode($value);
@@ -572,7 +554,8 @@ public static function setcookie(string $name, string $value = '', int $expires
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Cookie::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Cookie::exportStatic')) {
Cookie::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Db/APIs/MySQL.php b/Sources/Db/APIs/MySQL.php
index ef5e5a961f..d3f7d473a0 100644
--- a/Sources/Db/APIs/MySQL.php
+++ b/Sources/Db/APIs/MySQL.php
@@ -14,13 +14,13 @@
namespace SMF\Db\APIs;
use SMF\Config;
+use SMF\Db\DatabaseApi;
+use SMF\Db\DatabaseApiInterface;
use SMF\ErrorHandler;
use SMF\IP;
use SMF\Lang;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi;
-use SMF\Db\DatabaseApiInterface;
/**
* Interacts with MySQL databases.
@@ -102,7 +102,7 @@ class MySQL extends DatabaseApi implements DatabaseApiInterface
*
* Available MySQL engines.
*/
- protected $engines = array();
+ protected $engines = [];
/**
* @var bool
@@ -118,21 +118,21 @@ class MySQL extends DatabaseApi implements DatabaseApiInterface
/**
* {@inheritDoc}
*/
- public function query($identifier, $db_string, $db_values = array(), $connection = null)
+ public function query($identifier, $db_string, $db_values = [], $connection = null)
{
// Comments that are allowed in a query are preg_removed.
- $allowed_comments_from = array(
+ $allowed_comments_from = [
'~\s+~s',
'~/\*!40001 SQL_NO_CACHE \*/~',
'~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
'~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
- );
- $allowed_comments_to = array(
+ ];
+ $allowed_comments_to = [
' ',
'',
'',
'',
- );
+ ];
// Decide which connection to use.
$connection = $connection ?? $this->connection;
@@ -140,54 +140,56 @@ public function query($identifier, $db_string, $db_values = array(), $connection
// One more query....
self::$count++;
- if (!$this->disableQueryCheck && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
+ if (!$this->disableQueryCheck && strpos($db_string, '\'') !== false && empty($db_values['security_override'])) {
$this->error_backtrace('No direct access...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
+ }
// Use "ORDER BY null" to prevent Mysql doing filesorts for Group By clauses without an Order By
- if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && preg_match('~^\s+SELECT~i', $db_string))
- {
+ if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && preg_match('~^\s+SELECT~i', $db_string)) {
// Add before LIMIT
- if ($pos = strpos($db_string, 'LIMIT '))
+ if ($pos = strpos($db_string, 'LIMIT ')) {
$db_string = substr($db_string, 0, $pos) . "\t\t\tORDER BY null\n" . substr($db_string, $pos, strlen($db_string));
- else
+ } else {
// Append it.
$db_string .= "\n\t\t\tORDER BY null";
+ }
}
- if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
- {
+ if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false)) {
$this->temp_values = $db_values;
$this->temp_connection = $connection;
// Inject the values passed to this function.
- $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', array($this, 'replacement__callback'), $db_string);
+ $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', [$this, 'replacement__callback'], $db_string);
unset($this->temp_values, $this->temp_connection);
}
// First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
- if (!$this->disableQueryCheck)
- {
+ if (!$this->disableQueryCheck) {
$clean = '';
$old_pos = 0;
$pos = -1;
// Remove the string escape for better runtime
$db_string_1 = str_replace('\\\'', '', $db_string);
- while (true)
- {
+
+ while (true) {
$pos = strpos($db_string_1, '\'', $pos + 1);
- if ($pos === false)
+
+ if ($pos === false) {
break;
+ }
$clean .= substr($db_string_1, $old_pos, $pos - $old_pos);
- while (true)
- {
+ while (true) {
$pos1 = strpos($db_string_1, '\'', $pos + 1);
$pos2 = strpos($db_string_1, '\\', $pos + 1);
- if ($pos1 === false)
+
+ if ($pos1 === false) {
break;
- elseif ($pos2 === false || $pos2 > $pos1)
- {
+ }
+
+ if ($pos2 === false || $pos2 > $pos1) {
$pos = $pos1;
break;
}
@@ -202,29 +204,30 @@ public function query($identifier, $db_string, $db_values = array(), $connection
$clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
// Comments? We don't use comments in our queries, we leave 'em outside!
- if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
+ if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false) {
$fail = true;
+ }
// Trying to change passwords, slow us down, or something?
- elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
+ elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0) {
$fail = true;
- elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
+ } elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) {
$fail = true;
+ }
- if (!empty($fail) && function_exists('log_error'))
+ if (!empty($fail) && function_exists('log_error')) {
$this->error_backtrace('No direct access...', 'No direct access...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__);
+ }
}
// Debugging.
- if ($this->show_debug)
- {
+ if ($this->show_debug) {
// Get the file and line number this function was called.
- list ($file, $line) = $this->error_backtrace('', '', 'return', __FILE__, __LINE__);
+ list($file, $line) = $this->error_backtrace('', '', 'return', __FILE__, __LINE__);
- if (!empty($_SESSION['debug_redirect']))
- {
+ if (!empty($_SESSION['debug_redirect'])) {
self::$cache = array_merge($_SESSION['debug_redirect'], self::$cache);
self::$count = count(self::$cache) + 1;
- $_SESSION['debug_redirect'] = array();
+ $_SESSION['debug_redirect'] = [];
}
// Don't overload it.
@@ -236,12 +239,14 @@ public function query($identifier, $db_string, $db_values = array(), $connection
$ret = @mysqli_query($connection, $db_string, self::$unbuffered ? MYSQLI_USE_RESULT : MYSQLI_STORE_RESULT);
- if ($ret === false && empty($db_values['db_error_skip']))
+ if ($ret === false && empty($db_values['db_error_skip'])) {
$ret = $this->error($db_string, $connection);
+ }
// Debugging.
- if ($this->show_debug)
+ if ($this->show_debug) {
self::$cache[self::$count]['t'] = microtime(true) - $st;
+ }
return $ret;
}
@@ -252,14 +257,13 @@ public function query($identifier, $db_string, $db_values = array(), $connection
public function quote($db_string, $db_values, $connection = null)
{
// Only bother if there's something to replace.
- if (strpos($db_string, '{') !== false)
- {
+ if (strpos($db_string, '{') !== false) {
// This is needed by the callback function.
$this->temp_values = $db_values;
$this->temp_connection = $connection ?? $this->connection;
// Do the quoting and escaping
- $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', array($this, 'replacement__callback'), $db_string);
+ $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', [$this, 'replacement__callback'], $db_string);
unset($this->temp_values, $this->temp_connection);
}
@@ -288,15 +292,17 @@ public function fetch_assoc($result)
*/
public function fetch_all($request)
{
- if (function_exists('mysqli_fetch_all'))
+ if (function_exists('mysqli_fetch_all')) {
$return = mysqli_fetch_all($request, MYSQLI_ASSOC);
- else
- {
- $return = array();
- while ($row = mysqli_fetch_assoc($request))
+ } else {
+ $return = [];
+
+ while ($row = mysqli_fetch_assoc($request)) {
$return[] = $row;
+ }
}
- return !empty($return) ? $return : array();
+
+ return !empty($return) ? $return : [];
}
/**
@@ -317,8 +323,9 @@ public function insert($method, $table, $columns, $data, $keys, $returnmode = 0,
$return_var = null;
// With nothing to insert, simply return.
- if (empty($table) || empty($data))
+ if (empty($table) || empty($data)) {
return;
+ }
// Force method to lower case
$method = strtolower($method);
@@ -328,27 +335,29 @@ public function insert($method, $table, $columns, $data, $keys, $returnmode = 0,
$with_returning = false;
- if (!empty($keys) && (count($keys) > 0) && $returnmode > 0)
- {
+ if (!empty($keys) && (count($keys) > 0) && $returnmode > 0) {
$with_returning = true;
- if ($returnmode == 2)
- $return_var = array();
+ if ($returnmode == 2) {
+ $return_var = [];
+ }
}
// Inserting data as a single row can be done as a single array.
- if (!is_array($data[array_rand($data)]))
- $data = array($data);
+ if (!is_array($data[array_rand($data)])) {
+ $data = [$data];
+ }
// Create the mold for a single row insert.
$insertData = '(';
- foreach ($columns as $columnName => $type)
- {
+
+ foreach ($columns as $columnName => $type) {
// Are we restricting the length?
- if (strpos($type, 'string-') !== false)
+ if (strpos($type, 'string-') !== false) {
$insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
- else
+ } else {
$insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
+ }
}
$insertData = substr($insertData, 0, -2) . ')';
@@ -356,38 +365,35 @@ public function insert($method, $table, $columns, $data, $keys, $returnmode = 0,
$indexed_columns = array_keys($columns);
// Here's where the variables are injected to the query.
- $insertRows = array();
- foreach ($data as $dataRow)
- {
+ $insertRows = [];
+
+ foreach ($data as $dataRow) {
$insertRows[] = $this->quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
}
// Determine the method of insertion.
- switch ($method)
- {
+ switch ($method) {
case 'replace':
$queryTitle = 'REPLACE';
// Sanity check for replace is key part of the columns array
- if (empty($keys))
- {
+ if (empty($keys)) {
$this->error_backtrace(
'When using the replace mode, the key column is a required entry.',
'Change the method of db insert to insert or add the pk field to the key array',
E_USER_ERROR,
__FILE__,
- __LINE__
+ __LINE__,
);
}
- if (count(array_intersect_key($columns, array_flip($keys))) !== count($keys))
- {
+ if (count(array_intersect_key($columns, array_flip($keys))) !== count($keys)) {
$this->error_backtrace(
'Primary Key field missing in insert call',
'Change the method of db insert to insert or add the pk field to the columns array',
E_USER_ERROR,
__FILE__,
- __LINE__
+ __LINE__,
);
}
@@ -402,79 +408,76 @@ public function insert($method, $table, $columns, $data, $keys, $returnmode = 0,
break;
}
- if (!$with_returning || $method != 'ignore')
- {
+ if (!$with_returning || $method != 'ignore') {
// Do the insert.
- $this->query('', '
- ' . $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`)
+ $this->query(
+ '',
+ $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`)
VALUES
' . implode(',
', $insertRows),
- array(
+ [
'security_override' => true,
'db_error_skip' => $table === $this->prefix . 'log_errors',
- ),
- $connection
+ ],
+ $connection,
);
}
// Special way for ignore method with returning
- else
- {
+ else {
$count = count($insertRows);
$ai = 0;
- for ($i = 0; $i < $count; $i++)
- {
+
+ for ($i = 0; $i < $count; $i++) {
$old_id = $this->insert_id($table);
- $this->query('', '
- ' . $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`)
+ $this->query(
+ '',
+ $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`)
VALUES
' . $insertRows[$i],
- array(
+ [
'security_override' => true,
'db_error_skip' => $table === $this->prefix . 'log_errors',
- ),
- $connection
+ ],
+ $connection,
);
$new_id = $this->insert_id($table);
// the inserted value was new
- if ($old_id != $new_id)
- {
+ if ($old_id != $new_id) {
$ai = $new_id;
}
// the inserted value already exists we need to find the pk
- else
- {
+ else {
$where_string = '';
$count2 = count($keys);
- for ($x = 0; $x < $count2; $x++)
- {
+ for ($x = 0; $x < $count2; $x++) {
$keyPos = array_search($keys[$x], array_keys($columns));
$where_string .= $keys[$x] . ' = ' . $data[$i][$keyPos];
- if (($x + 1) < $count2)
+ if (($x + 1) < $count2) {
$where_string .= ' AND ';
+ }
}
- $request = $this->query('', '
- SELECT `' . $keys[0] . '` FROM ' . $table . '
+ $request = $this->query(
+ '',
+ 'SELECT `' . $keys[0] . '` FROM ' . $table . '
WHERE ' . $where_string . ' LIMIT 1',
- array()
+ [],
);
- if ($request !== false && $this->num_rows($request) == 1)
- {
+ if ($request !== false && $this->num_rows($request) == 1) {
$row = $this->fetch_assoc($request);
$ai = $row[$keys[0]];
}
}
- switch ($returnmode)
- {
+ switch ($returnmode) {
case 2:
$return_var[] = $ai;
break;
@@ -486,22 +489,19 @@ public function insert($method, $table, $columns, $data, $keys, $returnmode = 0,
}
}
- if ($with_returning)
- {
- if ($returnmode == 1 && empty($return_var))
- {
+ if ($with_returning) {
+ if ($returnmode == 1 && empty($return_var)) {
$return_var = $this->insert_id($table, $keys[0]) + count($insertRows) - 1;
- }
- elseif ($returnmode == 2 && empty($return_var))
- {
- $return_var = array();
+ } elseif ($returnmode == 2 && empty($return_var)) {
+ $return_var = [];
$count = count($insertRows);
$start = $this->insert_id($table, $keys[0]);
- for ($i = 0; $i < $count; $i++)
+ for ($i = 0; $i < $count; $i++) {
$return_var[] = $start + $i;
+ }
}
return $return_var;
@@ -580,8 +580,9 @@ public function transaction($type = 'commit', $connection = null)
{
$type = strtoupper($type);
- if (in_array($type, array('BEGIN', 'ROLLBACK', 'COMMIT')))
+ if (in_array($type, ['BEGIN', 'ROLLBACK', 'COMMIT'])) {
return @mysqli_query($connection ?? $this->connection, $type);
+ }
return false;
}
@@ -591,11 +592,13 @@ public function transaction($type = 'commit', $connection = null)
*/
public function error($connection)
{
- if ($connection === null && $this->connection === null)
+ if ($connection === null && $this->connection === null) {
return '';
+ }
- if (!(($connection ?? $this->connection) instanceof mysqli))
+ if (!(($connection ?? $this->connection) instanceof mysqli)) {
return '';
+ }
return mysqli_error($connection ?? $this->connection);
}
@@ -613,16 +616,17 @@ public function select($database, $connection = null)
*/
public function escape_wildcard_string($string, $translate_human_wildcards = false)
{
- $replacements = array(
+ $replacements = [
'%' => '\%',
'_' => '\_',
'\\' => '\\\\',
- );
+ ];
- if ($translate_human_wildcards)
- $replacements += array(
+ if ($translate_human_wildcards) {
+ $replacements += [
'*' => '%',
- );
+ ];
+ }
return strtr($string, $replacements);
}
@@ -649,27 +653,29 @@ public function ping($connection = null)
public function error_insert($error_array)
{
// Without a database we can't do anything.
- if (empty($this->connection))
+ if (empty($this->connection)) {
return;
+ }
// String keys are easier to work with.
- if (!isset($error_array['ip']))
- $error_array = array_combine(array('id_member', 'log_time', 'ip', 'url', 'message', 'session', 'error_type', 'file', 'line', 'backtrace'), $error_array);
+ if (!isset($error_array['ip'])) {
+ $error_array = array_combine(['id_member', 'log_time', 'ip', 'url', 'message', 'session', 'error_type', 'file', 'line', 'backtrace'], $error_array);
+ }
- if (empty($this->error_data_prep))
- {
+ if (empty($this->error_data_prep)) {
$this->error_data_prep = mysqli_prepare(
$this->connection,
'INSERT INTO ' . $this->prefix . 'log_errors
(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
- VALUES( ?, ?, unhex(?), ?, ?, ?, ?, ?, ?, ?)'
+ VALUES( ?, ?, unhex(?), ?, ?, ?, ?, ?, ?, ?)',
);
}
- if (filter_var($error_array['ip'], FILTER_VALIDATE_IP) !== false)
+ if (filter_var($error_array['ip'], FILTER_VALIDATE_IP) !== false) {
$error_array['ip'] = bin2hex(inet_pton($error_array['ip']));
- else
+ } else {
$error_array['ip'] = null;
+ }
mysqli_stmt_bind_param(
$this->error_data_prep,
@@ -683,7 +689,7 @@ public function error_insert($error_array)
$error_array['error_type'],
$error_array['file'],
$error_array['line'],
- $error_array['backtrace']
+ $error_array['backtrace'],
);
mysqli_stmt_execute($this->error_data_prep);
@@ -698,8 +704,9 @@ public function custom_order($field, $array_values, $desc = false)
$count = count($array_values);
$then = ($desc ? ' THEN -' : ' THEN ');
- for ($i = 0; $i < $count; $i++)
+ for ($i = 0; $i < $count; $i++) {
$return .= 'WHEN ' . (int) $array_values[$i] . $then . $i . ' ';
+ }
$return .= 'END';
@@ -719,8 +726,9 @@ public function native_replace()
*/
public function cte_support()
{
- if (isset($this->supports_cte))
+ if (isset($this->supports_cte)) {
return $this->supports_cte;
+ }
$this->get_version();
@@ -759,47 +767,52 @@ public function backup_table($table, $backup_table)
$table = str_replace('{db_prefix}', $this->prefix, $table);
// First, get rid of the old table.
- $this->query('', '
- DROP TABLE IF EXISTS {raw:backup_table}',
- array(
+ $this->query(
+ '',
+ 'DROP TABLE IF EXISTS {raw:backup_table}',
+ [
'backup_table' => $backup_table,
- )
+ ],
);
// Can we do this the quick way?
- $result = $this->query('', '
- CREATE TABLE {raw:backup_table} LIKE {raw:table}',
- array(
+ $result = $this->query(
+ '',
+ 'CREATE TABLE {raw:backup_table} LIKE {raw:table}',
+ [
'backup_table' => $backup_table,
- 'table' => $table
- )
+ 'table' => $table,
+ ],
);
+
// If this failed, we go old school.
- if ($result)
- {
- $request = $this->query('', '
- INSERT INTO {raw:backup_table}
+ if ($result) {
+ $request = $this->query(
+ '',
+ 'INSERT INTO {raw:backup_table}
SELECT *
FROM {raw:table}',
- array(
+ [
'backup_table' => $backup_table,
- 'table' => $table
- )
+ 'table' => $table,
+ ],
);
// Old school or no school?
- if ($request)
+ if ($request) {
return $request;
+ }
}
// At this point, the quick method failed.
- $result = $this->query('', '
- SHOW CREATE TABLE {raw:table}',
- array(
+ $result = $this->query(
+ '',
+ 'SHOW CREATE TABLE {raw:table}',
+ [
'table' => $table,
- )
+ ],
);
- list (, $create) = $this->fetch_row($result);
+ list(, $create) = $this->fetch_row($result);
$this->free_result($result);
$create = preg_split('/[\n\r]/', $create);
@@ -810,71 +823,78 @@ public function backup_table($table, $backup_table)
$charset = '';
$collate = '';
- foreach ($create as $k => $l)
- {
+ foreach ($create as $k => $l) {
// Get the name of the auto_increment column.
- if (strpos($l, 'auto_increment'))
+ if (strpos($l, 'auto_increment')) {
$auto_inc = trim($l);
+ }
// For the engine type, see if we can work out what it is.
- if (strpos($l, 'ENGINE') !== false || strpos($l, 'TYPE') !== false)
- {
+ if (strpos($l, 'ENGINE') !== false || strpos($l, 'TYPE') !== false) {
// Extract the engine type.
preg_match('~(ENGINE|TYPE)=(\w+)(\sDEFAULT)?(\sCHARSET=(\w+))?(\sCOLLATE=(\w+))?~', $l, $match);
- if (!empty($match[1]))
+ if (!empty($match[1])) {
$engine = $match[1];
+ }
- if (!empty($match[2]))
+ if (!empty($match[2])) {
$engine = $match[2];
+ }
- if (!empty($match[5]))
+ if (!empty($match[5])) {
$charset = $match[5];
+ }
- if (!empty($match[7]))
+ if (!empty($match[7])) {
$collate = $match[7];
+ }
}
// Skip everything but keys...
- if (strpos($l, 'KEY') === false)
+ if (strpos($l, 'KEY') === false) {
unset($create[$k]);
+ }
}
- if (!empty($create))
+ if (!empty($create)) {
$create = '(
' . implode('
', $create) . ')';
- else
+ } else {
$create = '';
+ }
- $request = $this->query('', '
- CREATE TABLE {raw:backup_table} {raw:create}
+ $request = $this->query(
+ '',
+ 'CREATE TABLE {raw:backup_table} {raw:create}
ENGINE={raw:engine}' . (empty($charset) ? '' : ' CHARACTER SET {raw:charset}' . (empty($collate) ? '' : ' COLLATE {raw:collate}')) . '
SELECT *
FROM {raw:table}',
- array(
+ [
'backup_table' => $backup_table,
'table' => $table,
'create' => $create,
'engine' => $engine,
'charset' => empty($charset) ? '' : $charset,
'collate' => empty($collate) ? '' : $collate,
- )
+ ],
);
- if ($auto_inc != '')
- {
- if (preg_match('~\`(.+?)\`\s~', $auto_inc, $match) != 0 && substr($auto_inc, -1, 1) == ',')
+ if ($auto_inc != '') {
+ if (preg_match('~\`(.+?)\`\s~', $auto_inc, $match) != 0 && substr($auto_inc, -1, 1) == ',') {
$auto_inc = substr($auto_inc, 0, -1);
+ }
- $this->query('', '
- ALTER TABLE {raw:backup_table}
+ $this->query(
+ '',
+ 'ALTER TABLE {raw:backup_table}
CHANGE COLUMN {raw:column_detail} {raw:auto_inc}',
- array(
+ [
'backup_table' => $backup_table,
'column_detail' => $match[1],
'auto_inc' => $auto_inc,
- )
+ ],
);
}
@@ -889,31 +909,36 @@ public function optimize_table($table)
$table = str_replace('{db_prefix}', $this->prefix, $table);
// Get how much overhead there is.
- $request = $this->query('', '
- SHOW TABLE STATUS LIKE {string:table_name}',
- array(
- 'table_name' => str_replace('_', '\_', $table),
- )
+ $request = $this->query(
+ '',
+ 'SHOW TABLE STATUS LIKE {string:table_name}',
+ [
+ 'table_name' => str_replace('_', '\\_', $table),
+ ],
);
$row = $this->fetch_assoc($request);
$this->free_result($request);
- $data_before = isset($row['Data_free']) ? $row['Data_free'] : 0;
- $request = $this->query('', '
- OPTIMIZE TABLE `{raw:table}`',
- array(
+ $data_before = $row['Data_free'] ?? 0;
+ $request = $this->query(
+ '',
+ 'OPTIMIZE TABLE `{raw:table}`',
+ [
'table' => $table,
- )
+ ],
);
- if (!$request)
+
+ if (!$request) {
return -1;
+ }
// How much left?
- $request = $this->query('', '
- SHOW TABLE STATUS LIKE {string:table}',
- array(
- 'table' => str_replace('_', '\_', $table),
- )
+ $request = $this->query(
+ '',
+ 'SHOW TABLE STATUS LIKE {string:table}',
+ [
+ 'table' => str_replace('_', '\\_', $table),
+ ],
);
$row = $this->fetch_assoc($request);
$this->free_result($request);
@@ -940,27 +965,27 @@ public function table_sql($tableName)
$schema_create .= 'CREATE TABLE ' . '`' . $tableName . '` (' . $crlf;
// Find all the fields.
- $result = $this->query('', '
- SHOW FIELDS
+ $result = $this->query(
+ '',
+ 'SHOW FIELDS
FROM `{raw:table}`',
- array(
+ [
'table' => $tableName,
- )
+ ],
);
- while ($row = $this->fetch_assoc($result))
- {
+
+ while ($row = $this->fetch_assoc($result)) {
// Make the CREATE for this column.
$schema_create .= ' `' . $row['Field'] . '` ' . $row['Type'] . ($row['Null'] != 'YES' ? ' NOT NULL' : '');
// Add a default...?
- if (!empty($row['Default']) || $row['Null'] !== 'YES')
- {
+ if (!empty($row['Default']) || $row['Null'] !== 'YES') {
// Make a special case of auto-timestamp.
- if ($row['Default'] == 'CURRENT_TIMESTAMP')
+ if ($row['Default'] == 'CURRENT_TIMESTAMP') {
$schema_create .= ' /*!40102 NOT NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP */';
+ }
// Text shouldn't have a default.
- elseif ($row['Default'] !== null)
- {
+ elseif ($row['Default'] !== null) {
// If this field is numeric the default needs no escaping.
$type = strtolower($row['Type']);
$isNumericColumn = strpos($type, 'int') !== false || strpos($type, 'bool') !== false || strpos($type, 'bit') !== false || strpos($type, 'float') !== false || strpos($type, 'double') !== false || strpos($type, 'decimal') !== false;
@@ -978,34 +1003,36 @@ public function table_sql($tableName)
$schema_create = substr($schema_create, 0, -strlen($crlf) - 1);
// Find the keys.
- $result = $this->query('', '
- SHOW KEYS
+ $result = $this->query(
+ '',
+ 'SHOW KEYS
FROM `{raw:table}`',
- array(
+ [
'table' => $tableName,
- )
+ ],
);
- $indexes = array();
- while ($row = $this->fetch_assoc($result))
- {
+ $indexes = [];
+
+ while ($row = $this->fetch_assoc($result)) {
// IS this a primary key, unique index, or regular index?
$row['Key_name'] = $row['Key_name'] == 'PRIMARY' ? 'PRIMARY KEY' : (empty($row['Non_unique']) ? 'UNIQUE ' : ($row['Comment'] == 'FULLTEXT' || (isset($row['Index_type']) && $row['Index_type'] == 'FULLTEXT') ? 'FULLTEXT ' : 'KEY ')) . '`' . $row['Key_name'] . '`';
// Is this the first column in the index?
- if (empty($indexes[$row['Key_name']]))
- $indexes[$row['Key_name']] = array();
+ if (empty($indexes[$row['Key_name']])) {
+ $indexes[$row['Key_name']] = [];
+ }
// A sub part, like only indexing 15 characters of a varchar.
- if (!empty($row['Sub_part']))
+ if (!empty($row['Sub_part'])) {
$indexes[$row['Key_name']][$row['Seq_in_index']] = '`' . $row['Column_name'] . '`(' . $row['Sub_part'] . ')';
- else
+ } else {
$indexes[$row['Key_name']][$row['Seq_in_index']] = '`' . $row['Column_name'] . '`';
+ }
}
$this->free_result($result);
// Build the CREATEs for the keys.
- foreach ($indexes as $keyname => $columns)
- {
+ foreach ($indexes as $keyname => $columns) {
// Ensure the columns are in proper order.
ksort($columns);
@@ -1013,12 +1040,13 @@ public function table_sql($tableName)
}
// Now just get the comment and engine... (MyISAM, etc.)
- $result = $this->query('', '
- SHOW TABLE STATUS
+ $result = $this->query(
+ '',
+ 'SHOW TABLE STATUS
LIKE {string:table}',
- array(
- 'table' => strtr($tableName, array('_' => '\\_', '%' => '\\%')),
- )
+ [
+ 'table' => strtr($tableName, ['_' => '\\_', '%' => '\\%']),
+ ],
);
$row = $this->fetch_assoc($result);
$this->free_result($result);
@@ -1038,18 +1066,21 @@ public function list_tables($db = false, $filter = false)
$db = trim($db);
$filter = $filter == false ? '' : ' LIKE \'' . $filter . '\'';
- $request = $this->query('', '
- SHOW TABLES
+ $request = $this->query(
+ '',
+ 'SHOW TABLES
FROM `{raw:db}`
{raw:filter}',
- array(
- 'db' => $db[0] == '`' ? strtr($db, array('`' => '')) : $db,
+ [
+ 'db' => $db[0] == '`' ? strtr($db, ['`' => '']) : $db,
'filter' => $filter,
- )
+ ],
);
- $tables = array();
- while ($row = $this->fetch_row($request))
+ $tables = [];
+
+ while ($row = $this->fetch_row($request)) {
$tables[] = $row[0];
+ }
$this->free_result($request);
return $tables;
@@ -1060,15 +1091,17 @@ public function list_tables($db = false, $filter = false)
*/
public function get_version()
{
- if (!empty($this->version))
+ if (!empty($this->version)) {
return $this->version;
+ }
- $request = $this->query('', '
- SELECT VERSION()',
- array(
- )
+ $request = $this->query(
+ '',
+ 'SELECT VERSION()',
+ [
+ ],
);
- list ($this->version) = $this->fetch_row($request);
+ list($this->version) = $this->fetch_row($request);
$this->free_result($request);
return $this->version;
@@ -1079,26 +1112,26 @@ public function get_version()
*/
public function get_vendor()
{
- if (!empty($this->vendor))
+ if (!empty($this->vendor)) {
return $this->vendor;
+ }
$request = $this->query('', 'SELECT @@version_comment');
- list ($comment) = $this->fetch_row($request);
+ list($comment) = $this->fetch_row($request);
$this->free_result($request);
// Skip these if we don't have a comment.
- if (!empty($comment))
- {
- if (stripos($comment, 'percona') !== false)
+ if (!empty($comment)) {
+ if (stripos($comment, 'percona') !== false) {
$this->vendor = 'Percona';
- elseif (stripos($comment, 'mariadb') !== false)
+ } elseif (stripos($comment, 'mariadb') !== false) {
$this->vendor = 'MariaDB';
- else
+ } else {
$this->vendor = 'MySQL';
- }
- else
- {
+ }
+ } else {
Lang::load('Admin');
+
return Lang::$txt['unknown'];
}
@@ -1111,10 +1144,8 @@ public function get_vendor()
public function allow_persistent()
{
$value = ini_get('mysqli.allow_persistent');
- if (strtolower($value) == 'on' || strtolower($value) == 'true' || $value == '1')
- return true;
- else
- return false;
+
+ return (bool) (strtolower($value) == 'on' || strtolower($value) == 'true' || $value == '1');
}
/*****************************************
@@ -1124,7 +1155,7 @@ public function allow_persistent()
/**
* {@inheritDoc}
*/
- public function search_query($identifier, $db_string, $db_values = array(), $connection = null)
+ public function search_query($identifier, $db_string, $db_values = [], $connection = null)
{
return $this->query($identifier, $db_string, $db_values, $connection);
}
@@ -1134,7 +1165,7 @@ public function search_query($identifier, $db_string, $db_values = array(), $con
*/
public function search_support($search_type)
{
- $supported_types = array('fulltext');
+ $supported_types = ['fulltext'];
return in_array($search_type, $supported_types);
}
@@ -1144,23 +1175,25 @@ public function search_support($search_type)
*/
public function create_word_search($size)
{
- if ($size == 'small')
+ if ($size == 'small') {
$size = 'smallint(5)';
- elseif ($size == 'medium')
+ } elseif ($size == 'medium') {
$size = 'mediumint(8)';
- else
+ } else {
$size = 'int(10)';
+ }
- $this->query('', '
- CREATE TABLE {db_prefix}log_search_words (
+ $this->query(
+ '',
+ 'CREATE TABLE {db_prefix}log_search_words (
id_word {raw:size} unsigned NOT NULL default {string:string_zero},
id_msg int(10) unsigned NOT NULL default {string:string_zero},
PRIMARY KEY (id_word, id_msg)
) ENGINE=InnoDB',
- array(
+ [
'string_zero' => '0',
'size' => $size,
- )
+ ],
);
}
@@ -1169,7 +1202,6 @@ public function create_word_search($size)
*/
public function search_language()
{
- return null;
}
/*******************************************
@@ -1179,25 +1211,25 @@ public function search_language()
/**
* {@inheritDoc}
*/
- public function add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
+ public function add_column($table_name, $column_info, $parameters = [], $if_exists = 'update', $error = 'fatal')
{
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
$column_info = array_change_key_case($column_info);
// Log that we will want to uninstall this!
- self::$package_log[] = array('remove_column', $short_table_name, $column_info['name']);
+ self::$package_log[] = ['remove_column', $short_table_name, $column_info['name']];
// Does it exist - if so don't add it again!
$columns = $this->list_columns($table_name, false);
- foreach ($columns as $column)
- {
- if ($column == $column_info['name'])
- {
+
+ foreach ($columns as $column) {
+ if ($column == $column_info['name']) {
// If we're going to overwrite then use change column.
- if ($if_exists == 'update')
+ if ($if_exists == 'update') {
return $this->change_column($table_name, $column_info['name'], $column_info);
- else
- return false;
+ }
+
+ return false;
}
}
@@ -1205,12 +1237,13 @@ public function add_column($table_name, $column_info, $parameters = array(), $if
$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
// Now add the thing!
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
ADD ' . $this->create_query_column($column_info) . (empty($column_info['auto']) ? '' : ' primary key'),
- array(
+ [
'security_override' => true,
- )
+ ],
);
return true;
@@ -1219,32 +1252,32 @@ public function add_column($table_name, $column_info, $parameters = array(), $if
/**
* {@inheritDoc}
*/
- public function add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
+ public function add_index($table_name, $index_info, $parameters = [], $if_exists = 'update', $error = 'fatal')
{
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
// No columns = no index.
- if (empty($index_info['columns']))
+ if (empty($index_info['columns'])) {
return false;
+ }
// MySQL If its a text column, we need to add a size.
$cols = $this->list_columns($table_name, true);
- foreach ($index_info['columns'] as &$c)
- {
+
+ foreach ($index_info['columns'] as &$c) {
$c = trim($c);
$cols[$c]['size'] = isset($cols[$c]['size']) && is_numeric($cols[$c]['size']) ? $cols[$c]['size'] : null;
- list ($type, $size) = $this->calculate_type($cols[$c]['type'], $cols[$c]['size']);
+ list($type, $size) = $this->calculate_type($cols[$c]['type'], $cols[$c]['size']);
// If a size was already specified, we won't be able to match it anyways.
if (
!isset($cols[$c])
- || !in_array($cols[$c]['type'], array('text', 'mediumntext', 'largetext', 'varchar', 'char'))
+ || !in_array($cols[$c]['type'], ['text', 'mediumntext', 'largetext', 'varchar', 'char'])
|| (
isset($size)
&& $size <= 191
)
- )
- {
+ ) {
continue;
}
@@ -1254,52 +1287,51 @@ public function add_index($table_name, $index_info, $parameters = array(), $if_e
$columns = implode(',', $index_info['columns']);
// No name - make it up!
- if (empty($index_info['name']))
- {
+ if (empty($index_info['name'])) {
// No need for primary.
- if (isset($index_info['type']) && $index_info['type'] == 'primary')
+ if (isset($index_info['type']) && $index_info['type'] == 'primary') {
$index_info['name'] = '';
- else
+ } else {
$index_info['name'] = trim(implode('_', preg_replace('~(\(\d+\))~', '', $index_info['columns'])));
+ }
}
// Log that we are going to want to remove this!
- self::$package_log[] = array('remove_index', $short_table_name, $index_info['name']);
+ self::$package_log[] = ['remove_index', $short_table_name, $index_info['name']];
// Let's get all our indexes.
$indexes = $this->list_indexes($table_name, true);
+
// Do we already have it?
- foreach ($indexes as $index)
- {
- if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
- {
+ foreach ($indexes as $index) {
+ if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary')) {
// If we want to overwrite simply remove the current one then continue.
- if ($if_exists != 'update' || $index['type'] == 'primary')
+ if ($if_exists != 'update' || $index['type'] == 'primary') {
return false;
- else
- $this->remove_index($table_name, $index_info['name']);
+ }
+
+ $this->remove_index($table_name, $index_info['name']);
}
}
// If we're here we know we don't have the index - so just add it.
- if (!empty($index_info['type']) && $index_info['type'] == 'primary')
- {
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ if (!empty($index_info['type']) && $index_info['type'] == 'primary') {
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
ADD PRIMARY KEY (' . $columns . ')',
- array(
+ [
'security_override' => true,
- )
+ ],
);
- }
- else
- {
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ } else {
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
ADD ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : 'INDEX') . ' ' . $index_info['name'] . ' (' . $columns . ')',
- array(
+ [
'security_override' => true,
- )
+ ],
);
}
}
@@ -1312,42 +1344,36 @@ public function calculate_type($type_name, $type_size = null, $reverse = false)
// MySQL is actually the generic baseline.
$type_name = strtolower($type_name);
+
// Generic => Specific.
- if (!$reverse)
- {
- $types = array(
+ if (!$reverse) {
+ $types = [
'inet' => 'varbinary',
- );
- }
- else
- {
- $types = array(
+ ];
+ } else {
+ $types = [
'varbinary' => 'inet',
- );
+ ];
}
// Got it? Change it!
- if (isset($types[$type_name]))
- {
- if ($type_name == 'inet' && !$reverse)
- {
+ if (isset($types[$type_name])) {
+ if ($type_name == 'inet' && !$reverse) {
$type_size = 16;
$type_name = 'varbinary';
- }
- elseif ($type_name == 'varbinary' && $reverse && $type_size == 16)
- {
+ } elseif ($type_name == 'varbinary' && $reverse && $type_size == 16) {
$type_name = 'inet';
$type_size = null;
- }
- elseif ($type_name == 'varbinary')
+ } elseif ($type_name == 'varbinary') {
$type_name = 'varbinary';
- else
+ } else {
$type_name = $types[$type_name];
- }
- elseif ($type_name == 'boolean')
+ }
+ } elseif ($type_name == 'boolean') {
$type_size = null;
+ }
- return array($type_name, $type_size);
+ return [$type_name, $type_size];
}
/**
@@ -1361,94 +1387,116 @@ public function change_column($table_name, $old_column, $column_info)
// Check it does exist!
$columns = $this->list_columns($table_name, true);
$old_info = null;
- foreach ($columns as $column)
- {
- if ($column['name'] == $old_column)
+
+ foreach ($columns as $column) {
+ if ($column['name'] == $old_column) {
$old_info = $column;
+ }
}
// Nothing?
- if ($old_info == null)
+ if ($old_info == null) {
return false;
+ }
// backward compatibility
- if (isset($column_info['null']) && !isset($column_info['not_null']))
+ if (isset($column_info['null']) && !isset($column_info['not_null'])) {
$column_info['not_null'] = !$column_info['null'];
+ }
// Get the right bits.
- if (isset($column_info['drop_default']) && !empty($column_info['drop_default']))
+ if (isset($column_info['drop_default']) && !empty($column_info['drop_default'])) {
$column_info['drop_default'] = true;
- else
+ } else {
$column_info['drop_default'] = false;
- if (!isset($column_info['name']))
+ }
+
+ if (!isset($column_info['name'])) {
$column_info['name'] = $old_column;
- if (!array_key_exists('default', $column_info) && array_key_exists('default', $old_info) && empty($column_info['drop_default']))
+ }
+
+ if (!array_key_exists('default', $column_info) && array_key_exists('default', $old_info) && empty($column_info['drop_default'])) {
$column_info['default'] = $old_info['default'];
- if (!isset($column_info['not_null']))
+ }
+
+ if (!isset($column_info['not_null'])) {
$column_info['not_null'] = $old_info['not_null'];
- if (!isset($column_info['auto']))
+ }
+
+ if (!isset($column_info['auto'])) {
$column_info['auto'] = $old_info['auto'];
- if (!isset($column_info['type']))
+ }
+
+ if (!isset($column_info['type'])) {
$column_info['type'] = $old_info['type'];
- if (!isset($column_info['size']) || !is_numeric($column_info['size']))
+ }
+
+ if (!isset($column_info['size']) || !is_numeric($column_info['size'])) {
$column_info['size'] = $old_info['size'];
- if (!isset($column_info['unsigned']) || !in_array($column_info['type'], array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')))
+ }
+
+ if (!isset($column_info['unsigned']) || !in_array($column_info['type'], ['int', 'tinyint', 'smallint', 'mediumint', 'bigint'])) {
$column_info['unsigned'] = '';
+ }
// If truly unspecified, make that clear, otherwise, might be confused with NULL...
// (Unspecified = no default whatsoever = column is not nullable with a value of null...)
- if (($column_info['not_null'] === true) && !$column_info['drop_default'] && array_key_exists('default', $column_info) && is_null($column_info['default']))
+ if (($column_info['not_null'] === true) && !$column_info['drop_default'] && array_key_exists('default', $column_info) && is_null($column_info['default'])) {
unset($column_info['default']);
+ }
- list ($type, $size) = $this->calculate_type($column_info['type'], $column_info['size']);
+ list($type, $size) = $this->calculate_type($column_info['type'], $column_info['size']);
// Allow for unsigned integers (mysql only)
- $unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column_info['unsigned']) ? 'unsigned ' : '';
+ $unsigned = in_array($type, ['int', 'tinyint', 'smallint', 'mediumint', 'bigint']) && !empty($column_info['unsigned']) ? 'unsigned ' : '';
// If you need to drop the default, that needs it's own thing...
// Must be done first, in case the default type is inconsistent with the other changes.
- if ($column_info['drop_default'])
- {
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ if ($column_info['drop_default']) {
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
ALTER COLUMN `' . $old_column . '` DROP DEFAULT',
- array(
+ [
'security_override' => true,
- )
+ ],
);
}
// Set the default clause.
$default_clause = '';
- if (!$column_info['drop_default'] && array_key_exists('default', $column_info))
- {
- if (is_null($column_info['default']))
+
+ if (!$column_info['drop_default'] && array_key_exists('default', $column_info)) {
+ if (is_null($column_info['default'])) {
$default_clause = 'DEFAULT NULL';
- elseif (is_numeric($column_info['default']))
+ } elseif (is_numeric($column_info['default'])) {
$default_clause = 'DEFAULT ' . (strpos($column_info['default'], '.') ? floatval($column_info['default']) : intval($column_info['default']));
- elseif (is_string($column_info['default']))
+ } elseif (is_string($column_info['default'])) {
$default_clause = 'DEFAULT \'' . $this->escape_string($column_info['default']) . '\'';
+ }
}
- if ($size !== null)
+ if ($size !== null) {
$type = $type . '(' . $size . ')';
+ }
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
CHANGE COLUMN `' . $old_column . '` `' . $column_info['name'] . '` ' . $type . ' ' .
(!empty($unsigned) ? $unsigned : '') . (!empty($column_info['not_null']) ? 'NOT NULL' : '') . ' ' .
$default_clause . ' ' .
(empty($column_info['auto']) ? '' : 'auto_increment') . ' ',
- array(
+ [
'security_override' => true,
- )
+ ],
);
}
/**
* {@inheritDoc}
*/
- public function create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
+ public function create_table($table_name, $columns, $indexes = [], $parameters = [], $if_exists = 'ignore', $error = 'fatal')
{
$old_table_exists = false;
@@ -1462,64 +1510,66 @@ public function create_table($table_name, $columns, $indexes = array(), $paramet
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
// First - no way do we touch SMF tables.
- if (in_array(strtolower($short_table_name), $this->reservedTables))
+ if (in_array(strtolower($short_table_name), $this->reservedTables)) {
return false;
+ }
// Log that we'll want to remove this on uninstall.
- self::$package_log[] = array('remove_table', $short_table_name);
+ self::$package_log[] = ['remove_table', $short_table_name];
// Slightly easier on MySQL than the others...
$tables = $this->list_tables($database);
- if (in_array($full_table_name, $tables))
- {
+ if (in_array($full_table_name, $tables)) {
// This is a sad day... drop the table? If not, return false (error) by default.
- if ($if_exists == 'overwrite')
+ if ($if_exists == 'overwrite') {
$this->drop_table($table_name);
- elseif ($if_exists == 'update')
- {
+ } elseif ($if_exists == 'update') {
$this->transaction('begin');
$db_trans = true;
$this->drop_table($short_table_name . '_old');
- $this->query('', '
- RENAME TABLE ' . $short_table_name . ' TO ' . $short_table_name . '_old',
- array(
+ $this->query(
+ '',
+ 'RENAME TABLE ' . $short_table_name . ' TO ' . $short_table_name . '_old',
+ [
'security_override' => true,
- )
+ ],
);
$old_table_exists = true;
- }
- else
+ } else {
return $if_exists == 'ignore';
+ }
}
// Righty - let's do the damn thing!
$table_query = 'CREATE TABLE ' . $short_table_name . "\n" . '(';
- foreach ($columns as $column)
+
+ foreach ($columns as $column) {
$table_query .= "\n\t" . $this->create_query_column($column) . ',';
+ }
// Loop through the indexes next...
- foreach ($indexes as $index)
- {
+ foreach ($indexes as $index) {
// MySQL If its a text column, we need to add a size.
- foreach ($index['columns'] as &$c)
- {
+ foreach ($index['columns'] as &$c) {
$c = trim($c);
// If a size was already specified, we won't be able to match it anyways.
$key = array_search($c, array_column($columns, 'name'));
$columns[$key]['size'] = isset($columns[$key]['size']) && is_numeric($columns[$key]['size']) ? $columns[$key]['size'] : null;
- list ($type, $size) = $this->calculate_type($columns[$key]['type'], $columns[$key]['size']);
+ list($type, $size) = $this->calculate_type($columns[$key]['type'], $columns[$key]['size']);
+
if (
$key === false
|| !isset($columns[$key])
- || !in_array($columns[$key]['type'], array('text', 'mediumntext', 'largetext', 'varchar', 'char'))
+ || !in_array($columns[$key]['type'], ['text', 'mediumntext', 'largetext', 'varchar', 'char'])
|| (
isset($size)
&& $size <= 191
)
- )
+ ) {
continue;
+ }
$c .= '(191)';
}
@@ -1527,31 +1577,31 @@ public function create_table($table_name, $columns, $indexes = array(), $paramet
$idx_columns = implode(',', $index['columns']);
// Is it the primary?
- if (isset($index['type']) && $index['type'] == 'primary')
+ if (isset($index['type']) && $index['type'] == 'primary') {
$table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
- else
- {
- if (empty($index['name']))
+ } else {
+ if (empty($index['name'])) {
$index['name'] = trim(implode('_', preg_replace('~(\(\d+\))~', '', $index['columns'])));
+ }
$table_query .= "\n\t" . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : 'KEY') . ' ' . $index['name'] . ' (' . $idx_columns . '),';
}
}
// No trailing commas!
- if (substr($table_query, -1) == ',')
+ if (substr($table_query, -1) == ',') {
$table_query = substr($table_query, 0, -1);
+ }
// Which engine do we want here?
- if (empty($this->engines))
- {
+ if (empty($this->engines)) {
// Figure out which engines we have
- $get_engines = $this->query('', 'SHOW ENGINES', array());
+ $get_engines = $this->query('', 'SHOW ENGINES', []);
- while ($row = $this->fetch_assoc($get_engines))
- {
- if ($row['Support'] == 'YES' || $row['Support'] == 'DEFAULT')
+ while ($row = $this->fetch_assoc($get_engines)) {
+ if ($row['Support'] == 'YES' || $row['Support'] == 'DEFAULT') {
$this->engines[] = $row['Engine'];
+ }
}
$this->free_result($get_engines);
@@ -1559,52 +1609,55 @@ public function create_table($table_name, $columns, $indexes = array(), $paramet
// If we don't have this engine, or didn't specify one, default to InnoDB or MyISAM
// depending on which one is available
- if (!isset($parameters['engine']) || !in_array($parameters['engine'], $this->engines))
- {
+ if (!isset($parameters['engine']) || !in_array($parameters['engine'], $this->engines)) {
$parameters['engine'] = in_array('InnoDB', $this->engines) ? 'InnoDB' : 'MyISAM';
}
$table_query .= ') ENGINE=' . $parameters['engine'];
- if (!empty($this->character_set) && $this->character_set == 'utf8')
+
+ if (!empty($this->character_set) && $this->character_set == 'utf8') {
$table_query .= ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
+ }
// Create the table!
- $this->query('', $table_query,
- array(
+ $this->query(
+ '',
+ $table_query,
+ [
'security_override' => true,
- )
+ ],
);
// Fill the old data
- if ($old_table_exists)
- {
- $same_col = array();
+ if ($old_table_exists) {
+ $same_col = [];
- $request = $this->query('', '
- SELECT count(*), column_name
+ $request = $this->query(
+ '',
+ 'SELECT count(*), column_name
FROM information_schema.columns
WHERE table_name in ({string:table1},{string:table2}) AND table_schema = {string:schema}
GROUP BY column_name
HAVING count(*) > 1',
- array(
+ [
'table1' => $short_table_name,
'table2' => $short_table_name . '_old',
'schema' => $this->name,
- )
+ ],
);
- while ($row = $this->fetch_assoc($request))
- {
+ while ($row = $this->fetch_assoc($request)) {
$same_col[] = $row['column_name'];
}
- $this->query('', '
- INSERT INTO ' . $short_table_name . '('
+ $this->query(
+ '',
+ 'INSERT INTO ' . $short_table_name . '('
. implode(',', $same_col) .
')
SELECT ' . implode(',', $same_col) . '
FROM ' . $short_table_name . '_old',
- array()
+ [],
);
$this->drop_table($short_table_name . '_old');
@@ -1616,7 +1669,7 @@ public function create_table($table_name, $columns, $indexes = array(), $paramet
/**
* {@inheritDoc}
*/
- public function drop_table($table_name, $parameters = array(), $error = 'fatal')
+ public function drop_table($table_name, $parameters = [], $error = 'fatal')
{
// After stripping away the database name, this is what's left.
$real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $this->prefix, $match) === 1 ? $match[3] : $this->prefix;
@@ -1628,19 +1681,21 @@ public function drop_table($table_name, $parameters = array(), $error = 'fatal')
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
// God no - dropping one of these = bad.
- if (in_array(strtolower($short_table_name), $this->reservedTables))
+ if (in_array(strtolower($short_table_name), $this->reservedTables)) {
return false;
+ }
// Does it exist?
$tables = $this->list_tables($database);
- if (in_array($full_table_name, $tables))
- {
+
+ if (in_array($full_table_name, $tables)) {
$query = 'DROP TABLE ' . $short_table_name;
- $this->query('',
+ $this->query(
+ '',
$query,
- array(
+ [
'security_override' => true,
- )
+ ],
);
return true;
@@ -1660,14 +1715,15 @@ public function table_structure($table_name)
$database = !empty($match[2]) ? $match[2] : $this->name;
// Find the table engine and add that to the info as well
- $table_status = $this->query('', '
- SHOW TABLE STATUS
+ $table_status = $this->query(
+ '',
+ 'SHOW TABLE STATUS
IN {raw:db}
LIKE {string:table}',
- array(
+ [
'db' => $database,
- 'table' => $real_table_name
- )
+ 'table' => $real_table_name,
+ ],
);
// Only one row, so no need for a loop...
@@ -1675,72 +1731,68 @@ public function table_structure($table_name)
$this->free_result($table_status);
- return array(
+ return [
'name' => $parsed_table_name,
'columns' => $this->list_columns($table_name, true),
'indexes' => $this->list_indexes($table_name, true),
'engine' => $row['Engine'],
- );
+ ];
}
/**
* {@inheritDoc}
*/
- public function list_columns($table_name, $detail = false, $parameters = array())
+ public function list_columns($table_name, $detail = false, $parameters = [])
{
$parsed_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
$database = !empty($match[2]) ? $match[2] : $this->name;
- $result = $this->query('', '
- SELECT column_name "Field", COLUMN_TYPE "Type", is_nullable "Null", COLUMN_KEY "Key" , column_default "Default", extra "Extra"
+ $result = $this->query(
+ '',
+ 'SELECT column_name "Field", COLUMN_TYPE "Type", is_nullable "Null", COLUMN_KEY "Key" , column_default "Default", extra "Extra"
FROM information_schema.columns
WHERE table_name = {string:table_name}
AND table_schema = {string:db_name}
ORDER BY ordinal_position',
- array(
+ [
'table_name' => $real_table_name,
'db_name' => $this->name,
- )
+ ],
);
- $columns = array();
- while ($row = $this->fetch_assoc($result))
- {
- if (!$detail)
- {
+ $columns = [];
+
+ while ($row = $this->fetch_assoc($result)) {
+ if (!$detail) {
$columns[] = $row['Field'];
- }
- else
- {
+ } else {
// Is there an auto_increment?
$auto = strpos($row['Extra'], 'auto_increment') !== false ? true : false;
// Can we split out the size?
- if (preg_match('~(.+?)\s*\((\d+)\)(?:(?:\s*)?(unsigned))?~i', $row['Type'], $matches) === 1)
- {
+ if (preg_match('~(.+?)\s*\((\d+)\)(?:(?:\s*)?(unsigned))?~i', $row['Type'], $matches) === 1) {
$type = $matches[1];
$size = $matches[2];
- if (!empty($matches[3]) && $matches[3] == 'unsigned')
+
+ if (!empty($matches[3]) && $matches[3] == 'unsigned') {
$unsigned = true;
- }
- else
- {
+ }
+ } else {
$type = $row['Type'];
$size = null;
}
- $columns[$row['Field']] = array(
+ $columns[$row['Field']] = [
'name' => $row['Field'],
'not_null' => $row['Null'] != 'YES',
'null' => $row['Null'] == 'YES',
- 'default' => isset($row['Default']) ? $row['Default'] : null,
+ 'default' => $row['Default'] ?? null,
'type' => $type,
'size' => $size,
'auto' => $auto,
- );
+ ];
- if (isset($unsigned))
- {
+ if (isset($unsigned)) {
$columns[$row['Field']]['unsigned'] = $unsigned;
unset($unsigned);
}
@@ -1754,53 +1806,54 @@ public function list_columns($table_name, $detail = false, $parameters = array()
/**
* {@inheritDoc}
*/
- public function list_indexes($table_name, $detail = false, $parameters = array())
+ public function list_indexes($table_name, $detail = false, $parameters = [])
{
$parsed_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
$database = !empty($match[2]) ? $match[2] : $this->name;
- $result = $this->query('', '
- SHOW KEYS
+ $result = $this->query(
+ '',
+ 'SHOW KEYS
FROM {raw:table_name}
IN {raw:db}',
- array(
+ [
'db' => $database,
'table_name' => $real_table_name,
- )
+ ],
);
- $indexes = array();
- while ($row = $this->fetch_assoc($result))
- {
- if (!$detail)
+ $indexes = [];
+
+ while ($row = $this->fetch_assoc($result)) {
+ if (!$detail) {
$indexes[] = $row['Key_name'];
- else
- {
+ } else {
// What is the type?
- if ($row['Key_name'] == 'PRIMARY')
+ if ($row['Key_name'] == 'PRIMARY') {
$type = 'primary';
- elseif (empty($row['Non_unique']))
+ } elseif (empty($row['Non_unique'])) {
$type = 'unique';
- elseif (isset($row['Index_type']) && $row['Index_type'] == 'FULLTEXT')
+ } elseif (isset($row['Index_type']) && $row['Index_type'] == 'FULLTEXT') {
$type = 'fulltext';
- else
+ } else {
$type = 'index';
+ }
// This is the first column we've seen?
- if (empty($indexes[$row['Key_name']]))
- {
- $indexes[$row['Key_name']] = array(
+ if (empty($indexes[$row['Key_name']])) {
+ $indexes[$row['Key_name']] = [
'name' => $row['Key_name'],
'type' => $type,
- 'columns' => array(),
- );
+ 'columns' => [],
+ ];
}
// Is it a partial index?
- if (!empty($row['Sub_part']))
+ if (!empty($row['Sub_part'])) {
$indexes[$row['Key_name']]['columns'][] = $row['Column_name'] . '(' . $row['Sub_part'] . ')';
- else
+ } else {
$indexes[$row['Key_name']]['columns'][] = $row['Column_name'];
+ }
}
}
$this->free_result($result);
@@ -1811,26 +1864,27 @@ public function list_indexes($table_name, $detail = false, $parameters = array()
/**
* {@inheritDoc}
*/
- public function remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
+ public function remove_column($table_name, $column_name, $parameters = [], $error = 'fatal')
{
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
// Does it exist?
$columns = $this->list_columns($table_name, true);
- foreach ($columns as $column)
- if ($column['name'] == $column_name)
- {
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ foreach ($columns as $column) {
+ if ($column['name'] == $column_name) {
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
DROP COLUMN ' . $column_name,
- array(
+ [
'security_override' => true,
- )
+ ],
);
return true;
}
+ }
// If here we didn't have to work - joy!
return false;
@@ -1839,38 +1893,38 @@ public function remove_column($table_name, $column_name, $parameters = array(),
/**
* {@inheritDoc}
*/
- public function remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
+ public function remove_index($table_name, $index_name, $parameters = [], $error = 'fatal')
{
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
// Better exist!
$indexes = $this->list_indexes($table_name, true);
- foreach ($indexes as $index)
- {
+ foreach ($indexes as $index) {
// If the name is primary we want the primary key!
- if ($index['type'] == 'primary' && $index_name == 'primary')
- {
+ if ($index['type'] == 'primary' && $index_name == 'primary') {
// Dropping primary key?
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
DROP PRIMARY KEY',
- array(
+ [
'security_override' => true,
- )
+ ],
);
return true;
}
- if ($index['name'] == $index_name)
- {
+
+ if ($index['name'] == $index_name) {
// Drop the bugger...
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
DROP INDEX ' . $index_name,
- array(
+ [
'security_override' => true,
- )
+ ],
);
return true;
@@ -1892,7 +1946,7 @@ public function remove_index($table_name, $index_name, $parameters = array(), $e
*
* @param array $options An array of database options.
*/
- protected function __construct(array $options = array())
+ protected function __construct(array $options = [])
{
parent::__construct();
@@ -1900,49 +1954,56 @@ protected function __construct(array $options = array())
$non_fatal = !empty($options['non_fatal']);
// If we are in SSI try them first, but don't worry if it doesn't work, we have the normal username and password we can use.
- if (SMF == 'SSI' && !empty(Config::$ssi_db_user) && !empty(Config::$ssi_db_passwd))
- {
- if (empty($options))
- $options = array('non_fatal' => true, 'dont_select_db' => true);
+ if (SMF == 'SSI' && !empty(Config::$ssi_db_user) && !empty(Config::$ssi_db_passwd)) {
+ if (empty($options)) {
+ $options = ['non_fatal' => true, 'dont_select_db' => true];
+ }
$this->initiate(Config::$ssi_db_user, Config::$ssi_db_passwd, $options);
}
// Either we aren't in SSI mode, or it failed.
- if (empty($this->connection))
- {
- if (empty($options))
- $options = array('dont_select_db' => SMF == 'SSI');
+ if (empty($this->connection)) {
+ if (empty($options)) {
+ $options = ['dont_select_db' => SMF == 'SSI'];
+ }
$this->initiate(Config::$db_user, Config::$db_passwd, $options);
}
// Safe guard here, if there isn't a valid connection let's put a stop to it.
- if (empty($this->connection) && !$non_fatal)
+ if (empty($this->connection) && !$non_fatal) {
ErrorHandler::displayDbError();
+ }
// If in SSI mode, fix up the prefix so it doesn't require the database to be selected.
- if (SMF == 'SSI')
- {
+ if (SMF == 'SSI') {
$this->prefix = is_numeric(substr($this->prefix, 0, 1)) ? $this->name . '.' . $this->prefix : '`' . $this->name . '`.' . $this->prefix;
// Redo the reserved table name prefixes.
$this->prefixReservedTables();
}
- $this->get_version();
- $this->supports_pcre = version_compare($this->version, strpos($this->version, 'MariaDB') !== false ? '10.0.5' : '8.0.4', '>=');
+ // At this point, if we don't have a connection, nothing else can be done.
+ if (empty($this->connection)) {
+ return;
+ }
// For backward compatibility.
- if (!is_object(self::$db_connection))
+ if (!is_object(self::$db_connection)) {
self::$db_connection = $this->connection;
+ }
+
+ $this->get_version();
+ $this->supports_pcre = version_compare($this->version, strpos($this->version, 'MariaDB') !== false ? '10.0.5' : '8.0.4', '>=');
// Ensure database has UTF-8 as its default input charset.
- $this->query('', '
- SET NAMES {string:db_character_set}',
- array(
+ $this->query(
+ '',
+ 'SET NAMES {string:db_character_set}',
+ [
'db_character_set' => $this->character_set,
- )
+ ],
);
}
@@ -1955,21 +2016,21 @@ protected function __construct(array $options = array())
* @param string $passwd The database password
* @param array $options An array of database options
*/
- protected function initiate($user, $passwd, $options = array())
+ protected function initiate($user, $passwd, $options = [])
{
$server = ($this->persist ? 'p:' : '') . $this->server;
// We are not going to make it very far without these.
- if (!function_exists('mysqli_init') || !function_exists('mysqli_real_connect'))
+ if (!function_exists('mysqli_init') || !function_exists('mysqli_real_connect')) {
ErrorHandler::displayDbError();
+ }
// This was the default prior to PHP 8.1, and all our code assumes it.
mysqli_report(MYSQLI_REPORT_OFF);
$success = false;
- if (($this->connection = mysqli_init()))
- {
+ if (($this->connection = mysqli_init())) {
$success = @mysqli_real_connect(
$this->connection,
$server,
@@ -1978,27 +2039,27 @@ protected function initiate($user, $passwd, $options = array())
null,
$this->port,
null,
- MYSQLI_CLIENT_FOUND_ROWS
+ MYSQLI_CLIENT_FOUND_ROWS,
);
}
// Something's wrong, show an error if its fatal (which we assume it is)
- if ($success === false)
- {
- if (!empty($options['non_fatal']))
- {
+ if ($success === false) {
+ if (!empty($options['non_fatal'])) {
$this->connection = null;
+
return;
}
- else
- ErrorHandler::displayDbError();
+
+ ErrorHandler::displayDbError();
}
// Select the database, unless told not to
- if (empty($options['dont_select_db']) && !@mysqli_select_db($this->connection, $this->name) && empty($options['non_fatal']))
+ if (empty($options['dont_select_db']) && !@mysqli_select_db($this->connection, $this->name) && empty($options['non_fatal'])) {
ErrorHandler::displayDbError();
+ }
- $sql_mode = array(
+ $sql_mode = [
'ONLY_FULL_GROUP_BY',
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
@@ -2006,11 +2067,11 @@ protected function initiate($user, $passwd, $options = array())
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_ENGINE_SUBSTITUTION',
'PIPES_AS_CONCAT',
- );
+ ];
mysqli_query(
$this->connection,
- 'SET SESSION sql_mode = \'' . implode(',', $sql_mode) . '\''
+ 'SET SESSION sql_mode = \'' . implode(',', $sql_mode) . '\'',
);
}
@@ -2028,124 +2089,137 @@ protected function initiate($user, $passwd, $options = array())
*/
protected function replacement__callback($matches)
{
- if (!is_object($this->temp_connection))
+ if (!is_object($this->temp_connection)) {
ErrorHandler::displayDbError();
+ }
- if ($matches[1] === 'db_prefix')
+ if ($matches[1] === 'db_prefix') {
return $this->prefix;
+ }
- if (isset(User::$me->{$matches[1]}) && strpos($matches[1], 'query_') !== false)
+ if (isset(User::$me->{$matches[1]}) && strpos($matches[1], 'query_') !== false) {
return User::$me->{$matches[1]};
+ }
- if ($matches[1] === 'empty')
+ if ($matches[1] === 'empty') {
return '\'\'';
+ }
- if (!isset($matches[2]))
+ if (!isset($matches[2])) {
$this->error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
- if ($matches[1] === 'literal')
+ if ($matches[1] === 'literal') {
return '\'' . mysqli_real_escape_string($this->temp_connection, $matches[2]) . '\'';
+ }
- if (!isset($this->temp_values[$matches[2]]))
+ if (!isset($this->temp_values[$matches[2]])) {
$this->error_backtrace('The database value you\'re trying to insert does not exist: ' . Utils::htmlspecialchars($matches[2]), '', E_USER_ERROR, __FILE__, __LINE__);
+ }
$replacement = $this->temp_values[$matches[2]];
- switch ($matches[1])
- {
+ switch ($matches[1]) {
case 'int':
- if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
+ if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement) {
$this->error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
return (string) (int) $replacement;
- break;
case 'string':
case 'text':
return sprintf('\'%1$s\'', mysqli_real_escape_string($this->temp_connection, $replacement));
- break;
case 'array_int':
- if (is_array($replacement))
- {
- if (empty($replacement))
+ if (is_array($replacement)) {
+ if (empty($replacement)) {
$this->error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
- foreach ($replacement as $key => $value)
- {
- if (!is_numeric($value) || (string) $value !== (string) (int) $value)
+ foreach ($replacement as $key => $value) {
+ if (!is_numeric($value) || (string) $value !== (string) (int) $value) {
$this->error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
$replacement[$key] = (string) (int) $value;
}
return implode(', ', $replacement);
}
- else
- $this->error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
+ $this->error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
break;
case 'array_string':
- if (is_array($replacement))
- {
- if (empty($replacement))
+ if (is_array($replacement)) {
+ if (empty($replacement)) {
$this->error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
- foreach ($replacement as $key => $value)
+ foreach ($replacement as $key => $value) {
$replacement[$key] = sprintf('\'%1$s\'', mysqli_real_escape_string($this->temp_connection, $value));
+ }
return implode(', ', $replacement);
}
- else
- $this->error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
+ $this->error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
case 'date':
- if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
+ if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1) {
return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]);
- else
- $this->error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
+ $this->error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
case 'time':
- if (preg_match('~^([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $time_matches) === 1)
+ if (preg_match('~^([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $time_matches) === 1) {
return sprintf('\'%02d:%02d:%02d\'', $time_matches[1], $time_matches[2], $time_matches[3]);
- else
- $this->error_backtrace('Wrong value type sent to the database. Time expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
+ $this->error_backtrace('Wrong value type sent to the database. Time expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
case 'datetime':
- if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d) ([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $datetime_matches) === 1)
+ if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d) ([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $datetime_matches) === 1) {
return 'str_to_date(' .
sprintf('\'%04d-%02d-%02d %02d:%02d:%02d\'', $datetime_matches[1], $datetime_matches[2], $datetime_matches[3], $datetime_matches[4], $datetime_matches[5], $datetime_matches[6]) .
',\'%Y-%m-%d %h:%i:%s\')';
- else
- $this->error_backtrace('Wrong value type sent to the database. Datetime expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
+ $this->error_backtrace('Wrong value type sent to the database. Datetime expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
case 'float':
- if (!is_numeric($replacement))
+ if (!is_numeric($replacement)) {
$this->error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
return (string) (float) $replacement;
- break;
case 'identifier':
// Backticks inside identifiers are supported as of MySQL 4.1. We don't need them for SMF.
- return '`' . implode('`.`', array_filter(explode('.', strtr($replacement, array('`' => ''))), 'strlen')) . '`';
- break;
+ return '`' . implode('`.`', array_filter(explode('.', strtr($replacement, ['`' => ''])), 'strlen')) . '`';
case 'raw':
return $replacement;
- break;
case 'inet':
- if ($replacement == 'null' || $replacement == '')
+ if ($replacement == 'null' || $replacement == '') {
return 'null';
+ }
$ip = new IP($replacement);
- if (!$ip->isValid())
- {
+ if (!$ip->isValid()) {
$this->error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
}
@@ -2153,22 +2227,19 @@ protected function replacement__callback($matches)
return sprintf('unhex(\'%1$s\')', $ip->toHex());
case 'array_inet':
- if (is_array($replacement))
- {
- if (empty($replacement))
- {
+ if (is_array($replacement)) {
+ if (empty($replacement)) {
$this->error_backtrace('Database error, given array of IPv4 or IPv6 values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
}
- foreach ($replacement as $key => $value)
- {
- if ($value == 'null' || $value == '')
+ foreach ($replacement as $key => $value) {
+ if ($value == 'null' || $value == '') {
$replacement[$key] = 'null';
+ }
$ip = new IP($value);
- if (!$ip->isValid())
- {
+ if (!$ip->isValid()) {
$this->error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
}
@@ -2177,10 +2248,9 @@ protected function replacement__callback($matches)
return implode(', ', $replacement);
}
- else
- {
- $this->error_backtrace('Wrong value type sent to the database. Array of IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
- }
+
+ $this->error_backtrace('Wrong value type sent to the database. Array of IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
default:
@@ -2201,44 +2271,45 @@ protected function replacement__callback($matches)
*/
protected function error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
{
- if (empty($log_message))
+ if (empty($log_message)) {
$log_message = $error_message;
+ }
- foreach (debug_backtrace() as $step)
- {
+ foreach (debug_backtrace() as $step) {
// Found it?
- if (strpos($step['function'], 'query') === false && !in_array(substr($step['function'], 0, 7), array('smf_db_', 'preg_re', 'db_erro', 'call_us')) && strpos($step['function'], '__') !== 0 && (empty($step['class']) || $step['class'] != $this::class))
- {
+ if (strpos($step['function'], 'query') === false && !in_array(substr($step['function'], 0, 7), ['smf_db_', 'preg_re', 'db_erro', 'call_us']) && strpos($step['function'], '__') !== 0 && (empty($step['class']) || $step['class'] != $this::class)) {
$log_message .= ' Function: ' . $step['function'];
break;
}
- if (isset($step['line']))
- {
+ if (isset($step['line'])) {
$file = $step['file'];
$line = $step['line'];
}
}
// A special case - we want the file and line numbers for debugging.
- if ($error_type == 'return')
- return array($file, $line);
+ if ($error_type == 'return') {
+ return [$file, $line];
+ }
// Is always a critical error.
- if (function_exists('log_error'))
+ if (function_exists('log_error')) {
ErrorHandler::log($log_message, 'critical', $file, $line);
+ }
- if (function_exists('fatal_error'))
- {
+ if (function_exists('fatal_error')) {
ErrorHandler::fatal($error_message, false);
// Cannot continue...
exit;
}
- elseif ($error_type)
+
+ if ($error_type) {
trigger_error($error_message . ($line !== null ? '(' . basename($file) . '-' . $line . ')' : ''), $error_type);
- else
+ } else {
trigger_error($error_message . ($line !== null ? '(' . basename($file) . '-' . $line . ')' : ''));
+ }
}
/**
@@ -2252,33 +2323,39 @@ protected function create_query_column($column)
$column = array_change_key_case($column);
// Auto increment is easy here!
- if (!empty($column['auto']))
+ if (!empty($column['auto'])) {
$default = 'auto_increment';
+ }
// Make it null.
- elseif (array_key_exists('default', $column) && is_null($column['default']))
+ elseif (array_key_exists('default', $column) && is_null($column['default'])) {
$default = 'DEFAULT NULL';
+ }
// Numbers don't need quotes.
- elseif (isset($column['default']) && is_numeric($column['default']))
+ elseif (isset($column['default']) && is_numeric($column['default'])) {
$default = 'DEFAULT ' . (strpos($column['default'], '.') ? floatval($column['default']) : intval($column['default']));
+ }
// Non empty string.
- elseif (isset($column['default']))
+ elseif (isset($column['default'])) {
$default = 'DEFAULT \'' . $this->escape_string($column['default']) . '\'';
- else
+ } else {
$default = '';
+ }
// Backwards compatible with the nullable column.
- if (isset($column['null']) && !isset($column['not_null']))
+ if (isset($column['null']) && !isset($column['not_null'])) {
$column['not_null'] = !$column['null'];
+ }
// Sort out the size... and stuff...
$column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
- list ($type, $size) = $this->calculate_type($column['type'], $column['size']);
+ list($type, $size) = $this->calculate_type($column['type'], $column['size']);
// Allow unsigned integers (mysql only)
- $unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column['unsigned']) ? 'unsigned ' : '';
+ $unsigned = in_array($type, ['int', 'tinyint', 'smallint', 'mediumint', 'bigint']) && !empty($column['unsigned']) ? 'unsigned ' : '';
- if ($size !== null)
+ if ($size !== null) {
$type = $type . '(' . $size . ')';
+ }
// Now just put it together!
return '`' . $column['name'] . '` ' . $type . ' ' . (!empty($unsigned) ? $unsigned : '') . (!empty($column['not_null']) ? 'NOT NULL' : '') . ' ' . $default;
diff --git a/Sources/Db/APIs/PostgreSQL.php b/Sources/Db/APIs/PostgreSQL.php
index 0d6d0cd75b..c668f5d4fa 100644
--- a/Sources/Db/APIs/PostgreSQL.php
+++ b/Sources/Db/APIs/PostgreSQL.php
@@ -14,13 +14,13 @@
namespace SMF\Db\APIs;
use SMF\Config;
+use SMF\Db\DatabaseApi;
+use SMF\Db\DatabaseApiInterface;
use SMF\ErrorHandler;
use SMF\IP;
use SMF\Lang;
use SMF\User;
use SMF\Utils;
-use SMF\Db\DatabaseApi;
-use SMF\Db\DatabaseApiInterface;
/**
* Interacts with PostgreSQL databases.
@@ -138,104 +138,108 @@ class PostgreSQL extends DatabaseApi implements DatabaseApiInterface
/**
* {@inheritDoc}
*/
- public function query($identifier, $db_string, $db_values = array(), $connection = null)
+ public function query($identifier, $db_string, $db_values = [], $connection = null)
{
// Decide which connection to use.
$connection = $connection ?? $this->connection;
// Special queries that need processing.
- $replacements = array(
- 'profile_board_stats' => array(
+ $replacements = [
+ 'profile_board_stats' => [
'~COUNT\(\*\) \/ MAX\(b.num_posts\)~' => 'CAST(COUNT(*) AS DECIMAL) / CAST(b.num_posts AS DECIMAL)',
- ),
- );
+ ],
+ ];
// Special optimizer Hints
- $query_opt = array(
- 'load_board_info' => array(
+ $query_opt = [
+ 'load_board_info' => [
'join_collapse_limit' => 1,
- ),
- 'calendar_get_events' => array(
+ ],
+ 'calendar_get_events' => [
'enable_seqscan' => 'off',
- ),
- );
+ ],
+ ];
- if (isset($replacements[$identifier]))
+ if (isset($replacements[$identifier])) {
$db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
+ }
// Limits need to be a little different.
$db_string = preg_replace('~\sLIMIT\s(\d+|{int:.+}),\s*(\d+|{int:.+})\s*$~i', 'LIMIT $2 OFFSET $1', $db_string);
- if (trim($db_string) == '')
+ if (trim($db_string) == '') {
return false;
+ }
// Comments that are allowed in a query are preg_removed.
- $allowed_comments_from = array(
+ $allowed_comments_from = [
'~\s+~s',
'~/\*!40001 SQL_NO_CACHE \*/~',
'~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
'~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
- );
- $allowed_comments_to = array(
+ ];
+ $allowed_comments_to = [
' ',
'',
'',
'',
- );
+ ];
// One more query....
self::$count++;
$this->replace_result = 0;
- if (!$this->disableQueryCheck && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
+ if (!$this->disableQueryCheck && strpos($db_string, '\'') !== false && empty($db_values['security_override'])) {
$this->error_backtrace('No direct access...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
+ }
// Use "ORDER BY null" to prevent Mysql doing filesorts for Group By clauses without an Order By
- if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && preg_match('~^\s+SELECT~i', $db_string))
- {
+ if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && preg_match('~^\s+SELECT~i', $db_string)) {
// Add before LIMIT
- if ($pos = strpos($db_string, 'LIMIT '))
+ if ($pos = strpos($db_string, 'LIMIT ')) {
$db_string = substr($db_string, 0, $pos) . "\t\t\tORDER BY null\n" . substr($db_string, $pos, strlen($db_string));
- else
+ } else {
// Append it.
$db_string .= "\n\t\t\tORDER BY null";
+ }
}
- if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
- {
+ if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false)) {
$this->temp_values = $db_values;
$this->temp_connection = $connection;
// Inject the values passed to this function.
- $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', array($this, 'replacement__callback'), $db_string);
+ $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', [$this, 'replacement__callback'], $db_string);
unset($this->temp_values, $this->temp_connection);
}
// First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
- if (!$this->disableQueryCheck)
- {
+ if (!$this->disableQueryCheck) {
$clean = '';
$old_pos = 0;
$pos = -1;
// Remove the string escape for better runtime
$db_string_1 = str_replace('\'\'', '', $db_string);
- while (true)
- {
+
+ while (true) {
$pos = strpos($db_string_1, '\'', $pos + 1);
- if ($pos === false)
+
+ if ($pos === false) {
break;
+ }
$clean .= substr($db_string_1, $old_pos, $pos - $old_pos);
- while (true)
- {
+ while (true) {
$pos1 = strpos($db_string_1, '\'', $pos + 1);
$pos2 = strpos($db_string_1, '\\', $pos + 1);
- if ($pos1 === false)
+
+ if ($pos1 === false) {
break;
- elseif ($pos2 === false || $pos2 > $pos1)
- {
+ }
+
+ if ($pos2 === false || $pos2 > $pos1) {
$pos = $pos1;
break;
}
@@ -250,29 +254,31 @@ public function query($identifier, $db_string, $db_values = array(), $connection
$clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
// Comments? We don't use comments in our queries, we leave 'em outside!
- if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
+ if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false) {
$fail = true;
+ }
// Trying to change passwords, slow us down, or something?
- elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
+ elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0) {
$fail = true;
- elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
+ } elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) {
$fail = true;
+ }
- if (!empty($fail) && function_exists('log_error'))
+ if (!empty($fail) && function_exists('log_error')) {
$this->error_backtrace('No direct access...', 'No direct access...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__);
+ }
}
// Set optimize stuff
- if (isset($query_opt[$identifier]))
- {
+ if (isset($query_opt[$identifier])) {
$query_hints = $query_opt[$identifier];
$query_hints_set = '';
- if (isset($query_hints['join_collapse_limit']))
- {
+
+ if (isset($query_hints['join_collapse_limit'])) {
$query_hints_set .= 'SET LOCAL join_collapse_limit = ' . $query_hints['join_collapse_limit'] . ';';
}
- if (isset($query_hints['enable_seqscan']))
- {
+
+ if (isset($query_hints['enable_seqscan'])) {
$query_hints_set .= 'SET LOCAL enable_seqscan = ' . $query_hints['enable_seqscan'] . ';';
}
@@ -280,16 +286,14 @@ public function query($identifier, $db_string, $db_values = array(), $connection
}
// Debugging.
- if ($this->show_debug)
- {
+ if ($this->show_debug) {
// Get the file and line number this function was called.
- list ($file, $line) = $this->error_backtrace('', '', 'return', __FILE__, __LINE__);
+ list($file, $line) = $this->error_backtrace('', '', 'return', __FILE__, __LINE__);
- if (!empty($_SESSION['debug_redirect']))
- {
+ if (!empty($_SESSION['debug_redirect'])) {
self::$cache = array_merge($_SESSION['debug_redirect'], self::$cache);
self::$count = count(self::$cache) + 1;
- $_SESSION['debug_redirect'] = array();
+ $_SESSION['debug_redirect'] = [];
}
// Don't overload it.
@@ -301,12 +305,14 @@ public function query($identifier, $db_string, $db_values = array(), $connection
$this->last_result = @pg_query($connection, $db_string);
- if ($this->last_result === false && empty($db_values['db_error_skip']))
+ if ($this->last_result === false && empty($db_values['db_error_skip'])) {
$this->last_result = $this->error($db_string, $connection);
+ }
// Debugging.
- if ($this->show_debug)
+ if ($this->show_debug) {
self::$cache[self::$count]['t'] = microtime(true) - $st;
+ }
return $this->last_result;
}
@@ -317,14 +323,13 @@ public function query($identifier, $db_string, $db_values = array(), $connection
public function quote($db_string, $db_values, $connection = null)
{
// Only bother if there's something to replace.
- if (strpos($db_string, '{') !== false)
- {
+ if (strpos($db_string, '{') !== false) {
// This is needed by the callback function.
$this->temp_values = $db_values;
$this->temp_connection = $connection ?? $this->connection;
// Do the quoting and escaping
- $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', array($this, 'replacement__callback'), $db_string);
+ $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', [$this, 'replacement__callback'], $db_string);
unset($this->temp_values, $this->temp_connection);
}
@@ -354,7 +359,8 @@ public function fetch_assoc($result)
public function fetch_all($request)
{
$return = @pg_fetch_all($request);
- return !empty($return) ? $return : array();
+
+ return !empty($return) ? $return : [];
}
/**
@@ -375,84 +381,94 @@ public function insert($method, $table, $columns, $data, $keys, $returnmode = 0,
$replace = '';
// With nothing to insert, simply return.
- if (empty($table) || empty($data))
+ if (empty($table) || empty($data)) {
return;
+ }
// Force method to lower case
$method = strtolower($method);
- if (!is_array($data[array_rand($data)]))
- $data = array($data);
+ if (!is_array($data[array_rand($data)])) {
+ $data = [$data];
+ }
// Replace the prefix holder with the actual prefix.
$table = str_replace('{db_prefix}', $this->prefix, $table);
// Sanity check for replace is key part of the columns array
- if ($method == 'replace')
- {
- if (empty($keys))
- $this->error_backtrace('When using the replace mode, the key column is a required entry.',
- 'Change the method of db insert to insert or add the pk field to the key array', E_USER_ERROR, __FILE__, __LINE__);
- if (count(array_intersect_key($columns, array_flip($keys))) !== count($keys))
- $this->error_backtrace('Primary Key field missing in insert call',
- 'Change the method of db insert to insert or add the pk field to the columns array', E_USER_ERROR, __FILE__, __LINE__);
+ if ($method == 'replace') {
+ if (empty($keys)) {
+ $this->error_backtrace(
+ 'When using the replace mode, the key column is a required entry.',
+ 'Change the method of db insert to insert or add the pk field to the key array',
+ E_USER_ERROR,
+ __FILE__,
+ __LINE__,
+ );
+ }
+
+ if (count(array_intersect_key($columns, array_flip($keys))) !== count($keys)) {
+ $this->error_backtrace(
+ 'Primary Key field missing in insert call',
+ 'Change the method of db insert to insert or add the pk field to the columns array',
+ E_USER_ERROR,
+ __FILE__,
+ __LINE__,
+ );
+ }
}
// PostgreSQL doesn't support replace: we implement a MySQL-compatible behavior instead
- if ($method == 'replace' || $method == 'ignore')
- {
+ if ($method == 'replace' || $method == 'ignore') {
$key_str = '';
$col_str = '';
$count = 0;
$count_pk = 0;
- foreach ($columns as $columnName => $type)
- {
+ foreach ($columns as $columnName => $type) {
// Check pk field.
- if (in_array($columnName, $keys))
- {
+ if (in_array($columnName, $keys)) {
$key_str .= ($count_pk > 0 ? ',' : '');
$key_str .= $columnName;
$count_pk++;
}
// Normal field.
- elseif ($method == 'replace')
- {
+ elseif ($method == 'replace') {
$col_str .= ($count > 0 ? ',' : '');
$col_str .= $columnName . ' = EXCLUDED.' . $columnName;
$count++;
}
}
- if ($method == 'replace')
+ if ($method == 'replace') {
$replace = ' ON CONFLICT (' . $key_str . ') DO UPDATE SET ' . $col_str;
- else
+ } else {
$replace = ' ON CONFLICT (' . $key_str . ') DO NOTHING';
+ }
}
$returning = '';
$with_returning = false;
// Let's build the returning string. (MySQL allows this only in normal mode)
- if (!empty($keys) && (count($keys) > 0) && $returnmode > 0)
- {
+ if (!empty($keys) && (count($keys) > 0) && $returnmode > 0) {
// We only take the first key.
$returning = ' RETURNING ' . $keys[0];
$with_returning = true;
}
- if (!empty($data))
- {
+ if (!empty($data)) {
// Create the mold for a single row insert.
$insertData = '(';
- foreach ($columns as $columnName => $type)
- {
+
+ foreach ($columns as $columnName => $type) {
// Are we restricting the length?
- if (strpos($type, 'string-') !== false)
+ if (strpos($type, 'string-') !== false) {
$insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
- else
+ } else {
$insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
+ }
}
$insertData = substr($insertData, 0, -2) . ')';
@@ -460,34 +476,34 @@ public function insert($method, $table, $columns, $data, $keys, $returnmode = 0,
$indexed_columns = array_keys($columns);
// Here's where the variables are injected to the query.
- $insertRows = array();
- foreach ($data as $dataRow)
+ $insertRows = [];
+
+ foreach ($data as $dataRow) {
$insertRows[] = $this->quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
+ }
// Do the insert.
- $request = $this->query('', '
- INSERT INTO ' . $table . '("' . implode('", "', $indexed_columns) . '")
+ $request = $this->query(
+ '',
+ 'INSERT INTO ' . $table . '("' . implode('", "', $indexed_columns) . '")
VALUES
' . implode(',
', $insertRows) . $replace . $returning,
- array(
+ [
'security_override' => true,
'db_error_skip' => $method == 'ignore' || $table === $this->prefix . 'log_errors',
- ),
- $connection
+ ],
+ $connection,
);
- if ($with_returning && $request !== false)
- {
- if ($returnmode === 2)
- $return_var = array();
-
- while (($row = $this->fetch_row($request)) && $with_returning)
- {
- if (is_numeric($row[0])) // try to emulate mysql limitation
- {
- switch ($returnmode)
- {
+ if ($with_returning && $request !== false) {
+ if ($returnmode === 2) {
+ $return_var = [];
+ }
+
+ while (($row = $this->fetch_row($request)) && $with_returning) {
+ if (is_numeric($row[0])) { // try to emulate mysql limitation
+ switch ($returnmode) {
case 2:
$return_var[] = $row[0];
break;
@@ -496,9 +512,7 @@ public function insert($method, $table, $columns, $data, $keys, $returnmode = 0,
$return_var = $row[0];
break;
}
- }
- else
- {
+ } else {
$with_returning = false;
Lang::load('Errors');
trigger_error(Lang::$txt['postgres_id_not_int'], E_USER_ERROR);
@@ -507,8 +521,9 @@ public function insert($method, $table, $columns, $data, $keys, $returnmode = 0,
}
}
- if ($with_returning && !empty($return_var))
+ if ($with_returning && !empty($return_var)) {
return $return_var;
+ }
}
/**
@@ -519,13 +534,16 @@ public function insert_id($table, $field = null, $connection = null)
$table = str_replace('{db_prefix}', $this->prefix, $table);
// Try get the last ID for the auto increment field.
- $request = $this->query('', '
- SELECT CURRVAL(\'' . $table . '_seq\') AS insertID',
- array()
+ $request = $this->query(
+ '',
+ 'SELECT CURRVAL(\'' . $table . '_seq\') AS insertID',
+ [],
);
- if (!$request)
+
+ if (!$request) {
return false;
- list ($lastID) = $this->fetch_row($request);
+ }
+ list($lastID) = $this->fetch_row($request);
$this->free_result($request);
return $lastID;
@@ -586,12 +604,11 @@ public function server_info($connection = null)
*/
public function affected_rows($connection = null)
{
- if ($this->replace_result)
- {
+ if ($this->replace_result) {
return $this->replace_result;
}
- elseif ($connection === null && !$this->last_result)
- {
+
+ if ($connection === null && !$this->last_result) {
return 0;
}
@@ -605,8 +622,7 @@ public function transaction($type = 'commit', $connection = null)
{
$type = strtoupper($type);
- if (in_array($type, array('BEGIN', 'ROLLBACK', 'COMMIT')))
- {
+ if (in_array($type, ['BEGIN', 'ROLLBACK', 'COMMIT'])) {
$this->inTransaction = $type === 'BEGIN';
return @pg_query($connection ?? $this->connection, $type);
@@ -620,11 +636,13 @@ public function transaction($type = 'commit', $connection = null)
*/
public function error($connection)
{
- if ($connection === null && $this->connection === null)
+ if ($connection === null && $this->connection === null) {
return '';
+ }
- if (!(($connection ?? $this->connection) instanceof \PgSql\Connection))
+ if (!(($connection ?? $this->connection) instanceof \PgSql\Connection)) {
return '';
+ }
return pg_last_error($connection ?? $this->connection);
}
@@ -642,16 +660,17 @@ public function select($database, $connection = null)
*/
public function escape_wildcard_string($string, $translate_human_wildcards = false)
{
- $replacements = array(
+ $replacements = [
'%' => '\%',
'_' => '\_',
'\\' => '\\\\',
- );
+ ];
- if ($translate_human_wildcards)
- $replacements += array(
+ if ($translate_human_wildcards) {
+ $replacements += [
'*' => '%',
- );
+ ];
+ }
return strtr($string, $replacements);
}
@@ -678,39 +697,46 @@ public function ping($connection = null)
public function error_insert($error_array)
{
// Without a database we can't do anything.
- if (empty($this->connection))
+ if (empty($this->connection)) {
return;
+ }
// String keys are easier to work with.
- if (!isset($error_array['ip']))
- $error_array = array_combine(array('id_member', 'log_time', 'ip', 'url', 'message', 'session', 'error_type', 'file', 'line', 'backtrace'), $error_array);
+ if (!isset($error_array['ip'])) {
+ $error_array = array_combine(['id_member', 'log_time', 'ip', 'url', 'message', 'session', 'error_type', 'file', 'line', 'backtrace'], $error_array);
+ }
- if (filter_var($error_array['ip'], FILTER_VALIDATE_IP) === false)
+ if (filter_var($error_array['ip'], FILTER_VALIDATE_IP) === false) {
$error_array['ip'] = null;
+ }
// If we are in a transaction, abort.
- if (!empty($inTransaction))
+ if (!empty($inTransaction)) {
$this->transaction('rollback');
+ }
// Without pooling.
- if (empty($this->persist))
- {
- if (empty($this->error_data_prep))
- $this->error_data_prep = pg_prepare($this->connection, 'smf_log_errors',
+ if (empty($this->persist)) {
+ if (empty($this->error_data_prep)) {
+ $this->error_data_prep = pg_prepare(
+ $this->connection,
+ 'smf_log_errors',
'INSERT INTO ' . $this->prefix . 'log_errors
(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
- VALUES( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)'
+ VALUES( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)',
);
+ }
pg_execute($this->connection, 'smf_log_errors', $error_array);
}
// With pooling.
- else
- {
- $this->error_data_prep = pg_prepare($this->connection, '',
+ else {
+ $this->error_data_prep = pg_prepare(
+ $this->connection,
+ '',
'INSERT INTO ' . $this->prefix . 'log_errors
(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
- VALUES( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)'
+ VALUES( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)',
);
pg_execute($this->connection, '', $error_array);
@@ -726,8 +752,9 @@ public function custom_order($field, $array_values, $desc = false)
$count = count($array_values);
$then = ($desc ? ' THEN -' : ' THEN ');
- for ($i = 0; $i < $count; $i++)
+ for ($i = 0; $i < $count; $i++) {
$return .= 'WHEN ' . (int) $array_values[$i] . $then . $i . ' ';
+ }
$return .= 'END';
@@ -755,8 +782,9 @@ public function cte_support()
*/
public function connect_error()
{
- if (empty($this->connect_error))
+ if (empty($this->connect_error)) {
$this->connect_error = '';
+ }
return $this->connect_error;
}
@@ -766,8 +794,9 @@ public function connect_error()
*/
public function connect_errno()
{
- if (empty($this->connect_errno))
+ if (empty($this->connect_errno)) {
$this->connect_errno = '';
+ }
return $this->connect_errno;
}
@@ -786,38 +815,40 @@ public function backup_table($table, $backup_table)
// Do we need to drop it first?
$tables = $this->list_tables(false, $backup_table);
- if (!empty($tables))
- {
- $this->query('', '
- DROP TABLE {raw:backup_table}',
- array(
+ if (!empty($tables)) {
+ $this->query(
+ '',
+ 'DROP TABLE {raw:backup_table}',
+ [
'backup_table' => $backup_table,
- )
+ ],
);
}
/**
* @todo Should we create backups of sequences as well?
*/
- $this->query('', '
- CREATE TABLE {raw:backup_table}
+ $this->query(
+ '',
+ 'CREATE TABLE {raw:backup_table}
(
LIKE {raw:table}
INCLUDING DEFAULTS
)',
- array(
+ [
'backup_table' => $backup_table,
'table' => $table,
- )
+ ],
);
- $this->query('', '
- INSERT INTO {raw:backup_table}
+ $this->query(
+ '',
+ 'INSERT INTO {raw:backup_table}
SELECT * FROM {raw:table}',
- array(
+ [
'backup_table' => $backup_table,
'table' => $table,
- )
+ ],
);
}
@@ -828,18 +859,19 @@ public function optimize_table($table)
{
$table = str_replace('{db_prefix}', $this->prefix, $table);
- $pg_tables = array('pg_catalog', 'information_schema');
+ $pg_tables = ['pg_catalog', 'information_schema'];
- $request = $this->query('', '
- SELECT pg_relation_size(C.oid) AS "size"
+ $request = $this->query(
+ '',
+ 'SELECT pg_relation_size(C.oid) AS "size"
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname NOT IN ({array_string:pg_tables})
AND relname = {string:table}',
- array(
+ [
'table' => $table,
'pg_tables' => $pg_tables,
- )
+ ],
);
$row = $this->fetch_assoc($request);
@@ -847,35 +879,39 @@ public function optimize_table($table)
$old_size = $row['size'];
- $request = $this->query('', '
- VACUUM FULL ANALYZE {raw:table}',
- array(
+ $request = $this->query(
+ '',
+ 'VACUUM FULL ANALYZE {raw:table}',
+ [
'table' => $table,
- )
+ ],
);
- if (!$request)
+ if (!$request) {
return -1;
+ }
- $request = $this->query('', '
- SELECT pg_relation_size(C.oid) AS "size"
+ $request = $this->query(
+ '',
+ 'SELECT pg_relation_size(C.oid) AS "size"
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname NOT IN ({array_string:pg_tables})
AND relname = {string:table}',
- array(
+ [
'table' => $table,
'pg_tables' => $pg_tables,
- )
+ ],
);
$row = $this->fetch_assoc($request);
$this->free_result($request);
- if (isset($row['size']))
+ if (isset($row['size'])) {
return ($old_size - $row['size']) / 1024;
- else
- return 0;
+ }
+
+ return 0;
}
/**
@@ -897,46 +933,48 @@ public function table_sql($tableName)
$seq_create = '';
// Find all the fields.
- $result = $this->query('', '
- SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
+ $result = $this->query(
+ '',
+ 'SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = {string:table}
ORDER BY ordinal_position',
- array(
+ [
'table' => $tableName,
- )
+ ],
);
- while ($row = $this->fetch_assoc($result))
- {
- if ($row['data_type'] == 'character varying')
+
+ while ($row = $this->fetch_assoc($result)) {
+ if ($row['data_type'] == 'character varying') {
$row['data_type'] = 'varchar';
- elseif ($row['data_type'] == 'character')
+ } elseif ($row['data_type'] == 'character') {
$row['data_type'] = 'char';
+ }
- if ($row['character_maximum_length'])
+ if ($row['character_maximum_length']) {
$row['data_type'] .= '(' . $row['character_maximum_length'] . ')';
+ }
// Make the CREATE for this column.
$schema_create .= ' "' . $row['column_name'] . '" ' . $row['data_type'] . ($row['is_nullable'] != 'YES' ? ' NOT NULL' : '');
// Add a default...?
- if (trim($row['column_default']) != '')
- {
+ if (trim($row['column_default']) != '') {
$schema_create .= ' default ' . $row['column_default'] . '';
// Auto increment?
- if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0)
- {
+ if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0) {
// Get to find the next variable first!
- $count_req = $this->query('', '
- SELECT MAX("{raw:column}")
+ $count_req = $this->query(
+ '',
+ 'SELECT MAX("{raw:column}")
FROM {raw:table}',
- array(
+ [
'column' => $row['column_name'],
'table' => $tableName,
- )
+ ],
);
- list ($max_ind) = $this->fetch_row($count_req);
+ list($max_ind) = $this->fetch_row($count_req);
$this->free_result($count_req);
// Get the right bloody start!
$seq_create .= 'CREATE SEQUENCE ' . $matches[1] . ' START WITH ' . ($max_ind + 1) . ';' . $crlf . $crlf;
@@ -950,35 +988,37 @@ public function table_sql($tableName)
// Take off the last comma.
$schema_create = substr($schema_create, 0, -strlen($crlf) - 1);
- $result = $this->query('', '
- SELECT pg_get_indexdef(i.indexrelid) AS inddef
+ $result = $this->query(
+ '',
+ 'SELECT pg_get_indexdef(i.indexrelid) AS inddef
FROM pg_class AS c
INNER JOIN pg_index AS i ON (i.indrelid = c.oid)
INNER JOIN pg_class AS c2 ON (c2.oid = i.indexrelid)
WHERE c.relname = {string:table} AND i.indisprimary is {raw:pk}',
- array(
+ [
'table' => $tableName,
'pk' => 'false',
- )
+ ],
);
- while ($row = $this->fetch_assoc($result))
- {
+
+ while ($row = $this->fetch_assoc($result)) {
$index_create .= $crlf . $row['inddef'] . ';';
}
$this->free_result($result);
- $result = $this->query('', '
- SELECT pg_get_constraintdef(c.oid) as pkdef
+ $result = $this->query(
+ '',
+ 'SELECT pg_get_constraintdef(c.oid) as pkdef
FROM pg_constraint as c
WHERE c.conrelid::regclass::text = {string:table} AND
c.contype = {string:constraintType}',
- array(
+ [
'table' => $tableName,
'constraintType' => 'p',
- )
+ ],
);
- while ($row = $this->fetch_assoc($result))
- {
+
+ while ($row = $this->fetch_assoc($result)) {
$index_create .= $crlf . 'ALTER TABLE ' . $tableName . ' ADD ' . $row['pkdef'] . ';';
}
$this->free_result($result);
@@ -994,21 +1034,22 @@ public function table_sql($tableName)
*/
public function list_tables($db = false, $filter = false)
{
- $tables = array();
+ $tables = [];
- $request = $this->query('', '
- SELECT tablename
+ $request = $this->query(
+ '',
+ 'SELECT tablename
FROM pg_tables
WHERE schemaname = {string:schema_public}' . ($filter == false ? '' : '
AND tablename LIKE {string:filter}') . '
ORDER BY tablename',
- array(
+ [
'schema_public' => 'public',
'filter' => $filter,
- )
+ ],
);
- while ($row = $this->fetch_row($request))
- {
+
+ while ($row = $this->fetch_row($request)) {
$tables[] = $row[0];
}
$this->free_result($request);
@@ -1040,10 +1081,8 @@ public function get_vendor()
public function allow_persistent()
{
$value = ini_get('pgsql.allow_persistent');
- if (strtolower($value) == 'on' || strtolower($value) == 'true' || $value == '1')
- return true;
- else
- return false;
+
+ return (bool) (strtolower($value) == 'on' || strtolower($value) == 'true' || $value == '1');
}
/*****************************************
@@ -1053,68 +1092,67 @@ public function allow_persistent()
/**
* {@inheritDoc}
*/
- public function search_query($identifier, $db_string, $db_values = array(), $connection = null)
+ public function search_query($identifier, $db_string, $db_values = [], $connection = null)
{
- $replacements = array(
- 'create_tmp_log_search_topics' => array(
+ $replacements = [
+ 'create_tmp_log_search_topics' => [
'~ENGINE=MEMORY~i' => '',
- ),
- 'create_tmp_log_search_messages' => array(
+ ],
+ 'create_tmp_log_search_messages' => [
'~ENGINE=MEMORY~i' => '',
- ),
- 'insert_into_log_messages_fulltext' => array(
+ ],
+ 'insert_into_log_messages_fulltext' => [
'/NOT\sLIKE/' => 'NOT ILIKE',
'/\bLIKE\b/' => 'ILIKE',
'/NOT RLIKE/' => '!~*',
'/RLIKE/' => '~*',
- ),
- 'insert_log_search_results_subject' => array(
+ ],
+ 'insert_log_search_results_subject' => [
'/NOT\sLIKE/' => 'NOT ILIKE',
'/\bLIKE\b/' => 'ILIKE',
'/NOT RLIKE/' => '!~*',
'/RLIKE/' => '~*',
- ),
- 'insert_log_search_topics' => array(
+ ],
+ 'insert_log_search_topics' => [
'/NOT\sLIKE/' => 'NOT ILIKE',
'/\bLIKE\b/' => 'ILIKE',
'/NOT RLIKE/' => '!~*',
'/RLIKE/' => '~*',
- ),
- 'insert_log_search_results_no_index' => array(
+ ],
+ 'insert_log_search_results_no_index' => [
'/NOT\sLIKE/' => 'NOT ILIKE',
'/\bLIKE\b/' => 'ILIKE',
'/NOT RLIKE/' => '!~*',
'/RLIKE/' => '~*',
- ),
- );
+ ],
+ ];
- if (isset($replacements[$identifier]))
- {
+ if (isset($replacements[$identifier])) {
$db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
}
- if (preg_match('~^\s*INSERT\s+IGNORE\b~i', $db_string) != 0)
- {
+ if (preg_match('~^\s*INSERT\s+IGNORE\b~i', $db_string) != 0) {
$db_string = preg_replace('~^\s*INSERT\s+IGNORE\b~i', 'INSERT', $db_string);
- if ($this->support_ignore)
- {
+ if ($this->support_ignore) {
// pg style "INSERT INTO.... ON CONFLICT DO NOTHING"
$db_string = $db_string . ' ON CONFLICT DO NOTHING';
- }
- else
- {
+ } else {
// Don't error on multi-insert.
$db_values['db_error_skip'] = true;
}
}
// Fix double quotes.
- if ($identifier == 'insert_into_log_messages_fulltext')
+ if ($identifier == 'insert_into_log_messages_fulltext') {
$db_string = str_replace('"', "'", $db_string);
+ }
- $return = $this->query('', $db_string,
- $db_values, $this->connection
+ $return = $this->query(
+ '',
+ $db_string,
+ $db_values,
+ $this->connection,
);
return $return;
@@ -1125,7 +1163,7 @@ public function search_query($identifier, $db_string, $db_values = array(), $con
*/
public function search_support($search_type)
{
- $supported_types = array('custom', 'fulltext');
+ $supported_types = ['custom', 'fulltext'];
return in_array($search_type, $supported_types);
}
@@ -1137,16 +1175,17 @@ public function create_word_search($size)
{
$size = 'int';
- $this->query('', '
- CREATE TABLE {db_prefix}log_search_words (
+ $this->query(
+ '',
+ 'CREATE TABLE {db_prefix}log_search_words (
id_word {raw:size} NOT NULL default {string:string_zero},
id_msg int NOT NULL default {string:string_zero},
PRIMARY KEY (id_word, id_msg)
)',
- array(
+ [
'size' => $size,
'string_zero' => '0',
- )
+ ],
);
}
@@ -1155,34 +1194,36 @@ public function create_word_search($size)
*/
public function search_language()
{
- if (!empty(Config::$modSettings['search_language']))
+ if (!empty(Config::$modSettings['search_language'])) {
$this->language_ftx = Config::$modSettings['search_language'];
+ }
- if (empty($this->language_ftx))
- {
- $request = $this->query('', '
- SELECT cfgname FROM pg_ts_config WHERE oid = current_setting({string:default_language})::regconfig',
- array(
- 'default_language' => 'default_text_search_config'
- )
+ if (empty($this->language_ftx)) {
+ $request = $this->query(
+ '',
+ 'SELECT cfgname FROM pg_ts_config WHERE oid = current_setting({string:default_language})::regconfig',
+ [
+ 'default_language' => 'default_text_search_config',
+ ],
);
- if ($request !== false && $this->num_rows($request) == 1)
- {
+ if ($request !== false && $this->num_rows($request) == 1) {
$row = $this->fetch_assoc($request);
$this->language_ftx = $row['cfgname'];
- $this->insert('replace',
+ $this->insert(
+ 'replace',
'{db_prefix}settings',
- array('variable' => 'string', 'value' => 'string'),
- array('search_language', $this->language_ftx),
- array('variable')
+ ['variable' => 'string', 'value' => 'string'],
+ ['search_language', $this->language_ftx],
+ ['variable'],
);
}
}
- if (empty($this->language_ftx))
+ if (empty($this->language_ftx)) {
$this->language_ftx = 'english';
+ }
return $this->language_ftx;
}
@@ -1194,25 +1235,25 @@ public function search_language()
/**
* {@inheritDoc}
*/
- public function add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
+ public function add_column($table_name, $column_info, $parameters = [], $if_exists = 'update', $error = 'fatal')
{
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
$column_info = array_change_key_case($column_info);
// Log that we will want to uninstall this!
- self::$package_log[] = array('remove_column', $short_table_name, $column_info['name']);
+ self::$package_log[] = ['remove_column', $short_table_name, $column_info['name']];
// Does it exist - if so don't add it again!
$columns = $this->list_columns($table_name, false);
- foreach ($columns as $column)
- {
- if ($column == $column_info['name'])
- {
+
+ foreach ($columns as $column) {
+ if ($column == $column_info['name']) {
// If we're going to overwrite then use change column.
- if ($if_exists == 'update')
+ if ($if_exists == 'update') {
return $this->change_column($table_name, $column_info['name'], $column_info);
- else
- return false;
+ }
+
+ return false;
}
}
@@ -1221,93 +1262,97 @@ public function add_column($table_name, $column_info, $parameters = array(), $if
list($type, $size) = $this->calculate_type($column_info['type'], $column_info['size']);
- if ($size !== null)
+ if ($size !== null) {
$type = $type . '(' . $size . ')';
+ }
// Now add the thing!
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
ADD COLUMN ' . $column_info['name'] . ' ' . $type,
- array(
+ [
'security_override' => true,
- )
+ ],
);
-
// If there's more attributes they need to be done via a change on PostgreSQL.
unset($column_info['type'], $column_info['size']);
- if (count($column_info) != 1)
+ if (count($column_info) != 1) {
return $this->change_column($table_name, $column_info['name'], $column_info);
- else
- return true;
+ }
+
+ return true;
}
/**
* {@inheritDoc}
*/
- public function add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
+ public function add_index($table_name, $index_info, $parameters = [], $if_exists = 'update', $error = 'fatal')
{
$parsed_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
// No columns = no index.
- if (empty($index_info['columns']))
+ if (empty($index_info['columns'])) {
return false;
+ }
// MySQL you can do a "column_name (length)", postgresql does not allow this. Strip it.
$cols = $this->list_columns($table_name, true);
- foreach ($index_info['columns'] as &$c)
+
+ foreach ($index_info['columns'] as &$c) {
$c = preg_replace('~\s+(\(\d+\))~', '', $c);
+ }
$columns = implode(',', $index_info['columns']);
// No name - make it up!
- if (empty($index_info['name']))
- {
+ if (empty($index_info['name'])) {
// No need for primary.
- if (isset($index_info['type']) && $index_info['type'] == 'primary')
+ if (isset($index_info['type']) && $index_info['type'] == 'primary') {
$index_info['name'] = '';
- else
+ } else {
$index_info['name'] = trim(implode('_', preg_replace('~(\(\d+\))~', '', $index_info['columns'])));
+ }
}
// Log that we are going to want to remove this!
- self::$package_log[] = array('remove_index', $parsed_table_name, $index_info['name']);
+ self::$package_log[] = ['remove_index', $parsed_table_name, $index_info['name']];
// Let's get all our indexes.
$indexes = $this->list_indexes($table_name, true);
+
// Do we already have it?
- foreach ($indexes as $index)
- {
- if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
- {
+ foreach ($indexes as $index) {
+ if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary')) {
// If we want to overwrite simply remove the current one then continue.
- if ($if_exists != 'update' || $index['type'] == 'primary')
+ if ($if_exists != 'update' || $index['type'] == 'primary') {
return false;
- else
- $this->remove_index($table_name, $index_info['name']);
+ }
+
+ $this->remove_index($table_name, $index_info['name']);
}
}
// If we're here we know we don't have the index - so just add it.
- if (!empty($index_info['type']) && $index_info['type'] == 'primary')
- {
- $this->query('', '
- ALTER TABLE ' . $real_table_name . '
+ if (!empty($index_info['type']) && $index_info['type'] == 'primary') {
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $real_table_name . '
ADD PRIMARY KEY (' . $columns . ')',
- array(
+ [
'security_override' => true,
- )
+ ],
);
- }
- else
- {
- $this->query('', '
- CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $real_table_name . '_' . $index_info['name'] . ' ON ' . $real_table_name . ' (' . $columns . ')',
- array(
+ } else {
+ $this->query(
+ '',
+ 'CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $real_table_name . '_' . $index_info['name'] . ' ON ' . $real_table_name . ' (' . $columns . ')',
+ [
'security_override' => true,
- )
+ ],
);
}
}
@@ -1319,10 +1364,10 @@ public function calculate_type($type_name, $type_size = null, $reverse = false)
{
// Let's be sure it's lowercase MySQL likes both, others no.
$type_name = strtolower($type_name);
+
// Generic => Specific.
- if (!$reverse)
- {
- $types = array(
+ if (!$reverse) {
+ $types = [
'varchar' => 'character varying',
'char' => 'character',
'mediumint' => 'int',
@@ -1334,11 +1379,9 @@ public function calculate_type($type_name, $type_size = null, $reverse = false)
'time' => 'time without time zone',
'datetime' => 'timestamp without time zone',
'timestamp' => 'timestamp without time zone',
- );
- }
- else
- {
- $types = array(
+ ];
+ } else {
+ $types = [
'character varying' => 'varchar',
'character' => 'char',
'integer' => 'int',
@@ -1346,22 +1389,23 @@ public function calculate_type($type_name, $type_size = null, $reverse = false)
'time without time zone' => 'time',
'timestamp without time zone' => 'datetime',
'numeric' => 'decimal',
- );
+ ];
}
// Got it? Change it!
- if (isset($types[$type_name]))
- {
- if ($type_name == 'tinytext')
+ if (isset($types[$type_name])) {
+ if ($type_name == 'tinytext') {
$type_size = 255;
+ }
$type_name = $types[$type_name];
}
// Only char fields got size
- if (strpos($type_name, 'char') === false)
+ if (strpos($type_name, 'char') === false) {
$type_size = null;
+ }
- return array($type_name, $type_size);
+ return [$type_name, $type_size];
}
/**
@@ -1375,146 +1419,175 @@ public function change_column($table_name, $old_column, $column_info)
// Check it does exist!
$columns = $this->list_columns($table_name, true);
$old_info = null;
- foreach ($columns as $column)
- {
- if ($column['name'] == $old_column)
+
+ foreach ($columns as $column) {
+ if ($column['name'] == $old_column) {
$old_info = $column;
+ }
}
// Nothing?
- if ($old_info == null)
+ if ($old_info == null) {
return false;
+ }
// backward compatibility
- if (isset($column_info['null']) && !isset($column_info['not_null']))
+ if (isset($column_info['null']) && !isset($column_info['not_null'])) {
$column_info['not_null'] = !$column_info['null'];
+ }
// Get the right bits.
- if (isset($column_info['drop_default']) && !empty($column_info['drop_default']))
+ if (isset($column_info['drop_default']) && !empty($column_info['drop_default'])) {
$column_info['drop_default'] = true;
- else
+ } else {
$column_info['drop_default'] = false;
- if (!isset($column_info['name']))
+ }
+
+ if (!isset($column_info['name'])) {
$column_info['name'] = $old_column;
- if (!array_key_exists('default', $column_info) && array_key_exists('default', $old_info) && empty($column_info['drop_default']))
+ }
+
+ if (!array_key_exists('default', $column_info) && array_key_exists('default', $old_info) && empty($column_info['drop_default'])) {
$column_info['default'] = $old_info['default'];
- if (!isset($column_info['not_null']))
+ }
+
+ if (!isset($column_info['not_null'])) {
$column_info['not_null'] = $old_info['not_null'];
- if (!isset($column_info['auto']))
+ }
+
+ if (!isset($column_info['auto'])) {
$column_info['auto'] = $old_info['auto'];
- if (!isset($column_info['type']))
+ }
+
+ if (!isset($column_info['type'])) {
$column_info['type'] = $old_info['type'];
- if (!isset($column_info['size']) || !is_numeric($column_info['size']))
+ }
+
+ if (!isset($column_info['size']) || !is_numeric($column_info['size'])) {
$column_info['size'] = $old_info['size'];
- if (!isset($column_info['unsigned']) || !in_array($column_info['type'], array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')))
+ }
+
+ if (!isset($column_info['unsigned']) || !in_array($column_info['type'], ['int', 'tinyint', 'smallint', 'mediumint', 'bigint'])) {
$column_info['unsigned'] = '';
+ }
// If truly unspecified, make that clear, otherwise, might be confused with NULL...
// (Unspecified = no default whatsoever = column is not nullable with a value of null...)
- if (($column_info['not_null'] === true) && !$column_info['drop_default'] && array_key_exists('default', $column_info) && is_null($column_info['default']))
+ if (($column_info['not_null'] === true) && !$column_info['drop_default'] && array_key_exists('default', $column_info) && is_null($column_info['default'])) {
unset($column_info['default']);
+ }
// If you need to drop the default, that needs it's own thing...
// Must be done first, in case the default type is inconsistent with the other changes.
- if ($column_info['drop_default'])
- {
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ if ($column_info['drop_default']) {
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
ALTER COLUMN ' . $old_column . ' DROP DEFAULT',
- array(
+ [
'security_override' => true,
- )
+ ],
);
}
+
// Now we check each bit individually and ALTER as required.
- if (isset($column_info['name']) && $column_info['name'] != $old_column)
- {
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ if (isset($column_info['name']) && $column_info['name'] != $old_column) {
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
RENAME COLUMN ' . $old_column . ' TO ' . $column_info['name'],
- array(
+ [
'security_override' => true,
- )
+ ],
);
}
// What about a change in type?
- if (isset($column_info['type']) && ($column_info['type'] != $old_info['type'] || (isset($column_info['size']) && $column_info['size'] != $old_info['size'])))
- {
+ if (isset($column_info['type']) && ($column_info['type'] != $old_info['type'] || (isset($column_info['size']) && $column_info['size'] != $old_info['size']))) {
$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
- list ($type, $size) = $this->calculate_type($column_info['type'], $column_info['size']);
- if ($size !== null)
+ list($type, $size) = $this->calculate_type($column_info['type'], $column_info['size']);
+
+ if ($size !== null) {
$type = $type . '(' . $size . ')';
+ }
// The alter is a pain.
$this->transaction('begin');
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
ADD COLUMN ' . $column_info['name'] . '_tempxx ' . $type,
- array(
+ [
'security_override' => true,
- )
+ ],
);
- $this->query('', '
- UPDATE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'UPDATE ' . $short_table_name . '
SET ' . $column_info['name'] . '_tempxx = CAST(' . $column_info['name'] . ' AS ' . $type . ')',
- array(
+ [
'security_override' => true,
- )
+ ],
);
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
DROP COLUMN ' . $column_info['name'],
- array(
+ [
'security_override' => true,
- )
+ ],
);
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
RENAME COLUMN ' . $column_info['name'] . '_tempxx TO ' . $column_info['name'],
- array(
+ [
'security_override' => true,
- )
+ ],
);
$this->transaction('commit');
}
// Different default?
// Just go ahead & honor the setting. Type changes above introduce defaults that we might need to override here...
- if (!$column_info['drop_default'] && array_key_exists('default', $column_info))
- {
+ if (!$column_info['drop_default'] && array_key_exists('default', $column_info)) {
// Fix the default.
$default = '';
- if (is_null($column_info['default']))
+
+ if (is_null($column_info['default'])) {
$default = 'NULL';
- elseif (isset($column_info['default']) && is_numeric($column_info['default']))
+ } elseif (isset($column_info['default']) && is_numeric($column_info['default'])) {
$default = strpos($column_info['default'], '.') ? floatval($column_info['default']) : intval($column_info['default']);
- else
+ } else {
$default = '\'' . $this->escape_string($column_info['default']) . '\'';
+ }
$action = 'SET DEFAULT ' . $default;
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
ALTER COLUMN ' . $column_info['name'] . ' ' . $action,
- array(
+ [
'security_override' => true,
- )
+ ],
);
}
// Is it null - or otherwise?
// Just go ahead & honor the setting. Type changes above introduce defaults that we might need to override here...
- if ($column_info['not_null'])
+ if ($column_info['not_null']) {
$action = 'SET NOT NULL';
- else
+ } else {
$action = 'DROP NOT NULL';
+ }
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
ALTER COLUMN ' . $column_info['name'] . ' ' . $action,
- array(
+ [
'security_override' => true,
- )
+ ],
);
return true;
@@ -1523,7 +1596,7 @@ public function change_column($table_name, $old_column, $column_info)
/**
* {@inheritDoc}
*/
- public function create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
+ public function create_table($table_name, $columns, $indexes = [], $parameters = [], $if_exists = 'ignore', $error = 'fatal')
{
$db_trans = false;
$old_table_exists = false;
@@ -1537,166 +1610,180 @@ public function create_table($table_name, $columns, $indexes = array(), $paramet
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
// First - no way do we touch SMF tables.
- if (in_array(strtolower($short_table_name), $this->reservedTables))
+ if (in_array(strtolower($short_table_name), $this->reservedTables)) {
return false;
+ }
// Log that we'll want to remove this on uninstall.
- self::$package_log[] = array('remove_table', $short_table_name);
+ self::$package_log[] = ['remove_table', $short_table_name];
// This... my friends... is a function in a half - let's start by checking if the table exists!
$tables = $this->list_tables($database);
- if (in_array($full_table_name, $tables))
- {
+ if (in_array($full_table_name, $tables)) {
// This is a sad day... drop the table? If not, return false (error) by default.
- if ($if_exists == 'overwrite')
+ if ($if_exists == 'overwrite') {
$this->drop_table($table_name);
- elseif ($if_exists == 'update')
- {
+ } elseif ($if_exists == 'update') {
$this->drop_table($table_name . '_old');
$this->transaction('begin');
$db_trans = true;
- $this->query('', '
- ALTER TABLE ' . $short_table_name . ' RENAME TO ' . $short_table_name . '_old',
- array(
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . ' RENAME TO ' . $short_table_name . '_old',
+ [
'security_override' => true,
- )
+ ],
);
$old_table_exists = true;
- }
- else
+ } else {
return $if_exists == 'ignore';
+ }
}
// If we've got this far - good news - no table exists. We can build our own!
- if (!$db_trans)
+ if (!$db_trans) {
$this->transaction('begin');
+ }
$table_query = 'CREATE TABLE ' . $short_table_name . "\n" . '(';
- foreach ($columns as $column)
- {
+
+ foreach ($columns as $column) {
$column = array_change_key_case($column);
// If we have an auto increment do it!
- if (!empty($column['auto']))
- {
- if (!$old_table_exists)
- $this->query('', '
- DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
- array(
+ if (!empty($column['auto'])) {
+ if (!$old_table_exists) {
+ $this->query(
+ '',
+ 'DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
+ [
'security_override' => true,
- )
+ ],
);
+ }
- if (!$old_table_exists)
- $this->query('', '
- CREATE SEQUENCE ' . $short_table_name . '_seq',
- array(
+ if (!$old_table_exists) {
+ $this->query(
+ '',
+ 'CREATE SEQUENCE ' . $short_table_name . '_seq',
+ [
'security_override' => true,
- )
+ ],
);
+ }
$default = 'default nextval(\'' . $short_table_name . '_seq\')';
- }
- elseif (isset($column['default']) && $column['default'] !== null)
+ } elseif (isset($column['default']) && $column['default'] !== null) {
$default = 'default \'' . $this->escape_string($column['default']) . '\'';
- else
+ } else {
$default = '';
+ }
// Sort out the size...
$column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
- list ($type, $size) = $this->calculate_type($column['type'], $column['size']);
- if ($size !== null)
+ list($type, $size) = $this->calculate_type($column['type'], $column['size']);
+
+ if ($size !== null) {
$type = $type . '(' . $size . ')';
+ }
// backward compatibility
- if (isset($column['null']) && !isset($column['not_null']))
+ if (isset($column['null']) && !isset($column['not_null'])) {
$column['not_null'] = !$column['null'];
+ }
// Now just put it together!
$table_query .= "\n\t\"" . $column['name'] . '" ' . $type . ' ' . (!empty($column['not_null']) ? 'NOT NULL' : '') . ' ' . $default . ',';
}
// Loop through the indexes next...
- $index_queries = array();
- foreach ($indexes as $index)
- {
+ $index_queries = [];
+
+ foreach ($indexes as $index) {
// MySQL you can do a "column_name (length)", postgresql does not allow this. Strip it.
- foreach ($index['columns'] as &$c)
+ foreach ($index['columns'] as &$c) {
$c = preg_replace('~\s+(\(\d+\))~', '', $c);
+ }
$idx_columns = implode(',', $index['columns']);
// Is it the primary?
- if (isset($index['type']) && $index['type'] == 'primary')
+ if (isset($index['type']) && $index['type'] == 'primary') {
$table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
- else
- {
- if (empty($index['name']))
+ } else {
+ if (empty($index['name'])) {
$index['name'] = trim(implode('_', preg_replace('~(\(\d+\))~', '', $index['columns'])));
+ }
$index_queries[] = 'CREATE ' . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $short_table_name . '_' . $index['name'] . ' ON ' . $short_table_name . ' (' . $idx_columns . ')';
}
}
// No trailing commas!
- if (substr($table_query, -1) == ',')
+ if (substr($table_query, -1) == ',') {
$table_query = substr($table_query, 0, -1);
+ }
$table_query .= ')';
// Create the table!
- $this->query('', $table_query,
- array(
+ $this->query(
+ '',
+ $table_query,
+ [
'security_override' => true,
- )
+ ],
);
// Fill the old data
- if ($old_table_exists)
- {
- $same_col = array();
+ if ($old_table_exists) {
+ $same_col = [];
- $request = $this->query('', '
- SELECT count(*), column_name
+ $request = $this->query(
+ '',
+ 'SELECT count(*), column_name
FROM information_schema.columns
WHERE table_name in ({string:table1},{string:table2}) AND table_schema = {string:schema}
GROUP BY column_name
HAVING count(*) > 1',
- array(
+ [
'table1' => $short_table_name,
'table2' => $short_table_name . '_old',
'schema' => 'public',
- )
+ ],
);
- while ($row = $this->fetch_assoc($request))
- {
+ while ($row = $this->fetch_assoc($request)) {
$same_col[] = $row['column_name'];
}
- $this->query('', '
- INSERT INTO ' . $short_table_name . '('
+ $this->query(
+ '',
+ 'INSERT INTO ' . $short_table_name . '('
. implode(',', $same_col) .
')
SELECT ' . implode(',', $same_col) . '
FROM ' . $short_table_name . '_old',
- array()
+ [],
);
}
-
// And the indexes...
- foreach ($index_queries as $query)
- $this->query('', $query,
- array(
+ foreach ($index_queries as $query) {
+ $this->query(
+ '',
+ $query,
+ [
'security_override' => true,
- )
+ ],
);
+ }
// Go, go power rangers!
$this->transaction('commit');
- if ($old_table_exists)
+ if ($old_table_exists) {
$this->drop_table($table_name . '_old');
+ }
return true;
}
@@ -1704,7 +1791,7 @@ public function create_table($table_name, $columns, $indexes = array(), $paramet
/**
* {@inheritDoc}
*/
- public function drop_table($table_name, $parameters = array(), $error = 'fatal')
+ public function drop_table($table_name, $parameters = [], $error = 'fatal')
{
// After stripping away the database name, this is what's left.
$real_prefix = preg_match('~^("?)(.+?)\\1\\.(.*?)$~', $this->prefix, $match) === 1 ? $match[3] : $this->prefix;
@@ -1715,13 +1802,14 @@ public function drop_table($table_name, $parameters = array(), $error = 'fatal')
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
// God no - dropping one of these = bad.
- if (in_array(strtolower($table_name), $this->reservedTables))
+ if (in_array(strtolower($table_name), $this->reservedTables)) {
return false;
+ }
// Does it exist?
$tables = $this->list_tables($database);
- if (in_array($full_table_name, $tables))
- {
+
+ if (in_array($full_table_name, $tables)) {
// We can then drop the table.
$this->transaction('begin');
@@ -1732,17 +1820,19 @@ public function drop_table($table_name, $parameters = array(), $error = 'fatal')
$sequence_query = 'DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq';
// drop them
- $this->query('',
+ $this->query(
+ '',
$table_query,
- array(
+ [
'security_override' => true,
- )
+ ],
);
- $this->query('',
+ $this->query(
+ '',
$sequence_query,
- array(
+ [
'security_override' => true,
- )
+ ],
);
$this->transaction('commit');
@@ -1762,60 +1852,57 @@ public function table_structure($table_name)
$parsed_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
- return array(
+ return [
'name' => $real_table_name,
'columns' => $this->list_columns($table_name, true),
'indexes' => $this->list_indexes($table_name, true),
- );
+ ];
}
/**
* {@inheritDoc}
*/
- public function list_columns($table_name, $detail = false, $parameters = array())
+ public function list_columns($table_name, $detail = false, $parameters = [])
{
$parsed_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
$database = !empty($match[2]) ? $match[2] : $this->name;
- $result = $this->query('', '
- SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
+ $result = $this->query(
+ '',
+ 'SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_schema = {string:schema_public}
AND table_name = {string:table_name}
ORDER BY ordinal_position',
- array(
+ [
'schema_public' => 'public',
'table_name' => $real_table_name,
- )
+ ],
);
- $columns = array();
- while ($row = $this->fetch_assoc($result))
- {
- if (!$detail)
- {
+ $columns = [];
+
+ while ($row = $this->fetch_assoc($result)) {
+ if (!$detail) {
$columns[] = $row['column_name'];
- }
- else
- {
+ } else {
$auto = false;
$default = null;
+
// What is the default?
- if ($row['column_default'] !== null)
- {
- if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0)
+ if ($row['column_default'] !== null) {
+ if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0) {
$auto = true;
- elseif (substr($row['column_default'], 0, 4) != 'NULL' && trim($row['column_default']) != '')
- {
+ } elseif (substr($row['column_default'], 0, 4) != 'NULL' && trim($row['column_default']) != '') {
$pos = strpos($row['column_default'], '::');
$default = trim($pos === false ? $row['column_default'] : substr($row['column_default'], 0, $pos), '\'');
}
}
// Make the type generic.
- list ($type, $size) = $this->calculate_type($row['data_type'], $row['character_maximum_length'], true);
+ list($type, $size) = $this->calculate_type($row['data_type'], $row['character_maximum_length'], true);
- $columns[$row['column_name']] = array(
+ $columns[$row['column_name']] = [
'name' => $row['column_name'],
'not_null' => $row['is_nullable'] != 'YES',
'null' => $row['is_nullable'] == 'YES',
@@ -1823,7 +1910,7 @@ public function list_columns($table_name, $detail = false, $parameters = array()
'type' => $type,
'size' => $size,
'auto' => $auto,
- );
+ ];
}
}
$this->free_result($result);
@@ -1834,14 +1921,15 @@ public function list_columns($table_name, $detail = false, $parameters = array()
/**
* {@inheritDoc}
*/
- public function list_indexes($table_name, $detail = false, $parameters = array())
+ public function list_indexes($table_name, $detail = false, $parameters = [])
{
$parsed_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
$database = !empty($match[2]) ? $match[2] : $this->name;
- $result = $this->query('', '
- SELECT CASE WHEN i.indisprimary THEN 1 ELSE 0 END AS is_primary,
+ $result = $this->query(
+ '',
+ 'SELECT CASE WHEN i.indisprimary THEN 1 ELSE 0 END AS is_primary,
CASE WHEN i.indisunique THEN 1 ELSE 0 END AS is_unique,
c2.relname AS name,
pg_get_indexdef(i.indexrelid) AS inddef
@@ -1849,40 +1937,43 @@ public function list_indexes($table_name, $detail = false, $parameters = array()
WHERE c.relname = {string:table_name}
AND c.oid = i.indrelid
AND i.indexrelid = c2.oid',
- array(
+ [
'table_name' => $real_table_name,
- )
+ ],
);
- $indexes = array();
- while ($row = $this->fetch_assoc($result))
- {
+ $indexes = [];
+
+ while ($row = $this->fetch_assoc($result)) {
// Try get the columns that make it up.
- if (preg_match('~\(([^\)]+?)\)~i', $row['inddef'], $matches) == 0)
+ if (preg_match('~\(([^\)]+?)\)~i', $row['inddef'], $matches) == 0) {
continue;
+ }
$columns = explode(',', $matches[1]);
- if (empty($columns))
+ if (empty($columns)) {
continue;
+ }
- foreach ($columns as $k => $v)
+ foreach ($columns as $k => $v) {
$columns[$k] = trim($v);
+ }
// Fix up the name to be consistent cross databases
- if (substr($row['name'], -5) == '_pkey' && $row['is_primary'] == 1)
+ if (substr($row['name'], -5) == '_pkey' && $row['is_primary'] == 1) {
$row['name'] = 'PRIMARY';
- else
+ } else {
$row['name'] = str_replace($real_table_name . '_', '', $row['name']);
+ }
- if (!$detail)
+ if (!$detail) {
$indexes[] = $row['name'];
- else
- {
- $indexes[$row['name']] = array(
+ } else {
+ $indexes[$row['name']] = [
'name' => $row['name'],
'type' => $row['is_primary'] ? 'primary' : ($row['is_unique'] ? 'unique' : 'index'),
'columns' => $columns,
- );
+ ];
}
}
$this->free_result($result);
@@ -1893,35 +1984,38 @@ public function list_indexes($table_name, $detail = false, $parameters = array()
/**
* {@inheritDoc}
*/
- public function remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
+ public function remove_column($table_name, $column_name, $parameters = [], $error = 'fatal')
{
$short_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
// Does it exist?
$columns = $this->list_columns($table_name, true);
- foreach ($columns as $column)
- if (strtolower($column['name']) == strtolower($column_name))
- {
+ foreach ($columns as $column) {
+ if (strtolower($column['name']) == strtolower($column_name)) {
// If there is an auto we need remove it!
- if ($column['auto'])
- $this->query('', '
- DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
- array(
+ if ($column['auto']) {
+ $this->query(
+ '',
+ 'DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
+ [
'security_override' => true,
- )
+ ],
);
+ }
- $this->query('', '
- ALTER TABLE ' . $short_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $short_table_name . '
DROP COLUMN ' . $column_name,
- array(
+ [
'security_override' => true,
- )
+ ],
);
return true;
}
+ }
// If here we didn't have to work - joy!
return false;
@@ -1930,7 +2024,7 @@ public function remove_column($table_name, $column_name, $parameters = array(),
/**
* {@inheritDoc}
*/
- public function remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
+ public function remove_index($table_name, $index_name, $parameters = [], $error = 'fatal')
{
$parsed_table_name = str_replace('{db_prefix}', $this->prefix, $table_name);
$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
@@ -1939,33 +2033,34 @@ public function remove_index($table_name, $index_name, $parameters = array(), $e
$indexes = $this->list_indexes($table_name, true);
// Do not add the table name to the index if it is arleady there.
- if ($index_name != 'primary' && strpos($index_name, $real_table_name) !== false)
+ if ($index_name != 'primary' && strpos($index_name, $real_table_name) !== false) {
$index_name = str_replace($real_table_name . '_', '', $index_name);
+ }
- foreach ($indexes as $index)
- {
+ foreach ($indexes as $index) {
// If the name is primary we want the primary key!
- if ($index['type'] == 'primary' && $index_name == 'primary')
- {
+ if ($index['type'] == 'primary' && $index_name == 'primary') {
// Dropping primary key?
- $this->query('', '
- ALTER TABLE ' . $real_table_name . '
+ $this->query(
+ '',
+ 'ALTER TABLE ' . $real_table_name . '
DROP CONSTRAINT ' . $index['name'],
- array(
+ [
'security_override' => true,
- )
+ ],
);
return true;
}
- if ($index['name'] == $index_name)
- {
+
+ if ($index['name'] == $index_name) {
// Drop the bugger...
- $this->query('', '
- DROP INDEX ' . $real_table_name . '_' . $index_name,
- array(
+ $this->query(
+ '',
+ 'DROP INDEX ' . $real_table_name . '_' . $index_name,
+ [
'security_override' => true,
- )
+ ],
);
return true;
@@ -1987,7 +2082,7 @@ public function remove_index($table_name, $index_name, $parameters = array(), $e
*
* @param array $options An array of database options.
*/
- protected function __construct(array $options = array())
+ protected function __construct(array $options = [])
{
parent::__construct();
@@ -1995,37 +2090,45 @@ protected function __construct(array $options = array())
$non_fatal = !empty($options['non_fatal']);
// If we are in SSI try them first, but don't worry if it doesn't work, we have the normal username and password we can use.
- if (SMF == 'SSI' && !empty(Config::$ssi_db_user) && !empty(Config::$ssi_db_passwd))
- {
- if (empty($options))
- $options = array('non_fatal' => true, 'dont_select_db' => true);
+ if (SMF == 'SSI' && !empty(Config::$ssi_db_user) && !empty(Config::$ssi_db_passwd)) {
+ if (empty($options)) {
+ $options = ['non_fatal' => true, 'dont_select_db' => true];
+ }
$this->initiate(Config::$ssi_db_user, Config::$ssi_db_passwd, $options);
}
// Either we aren't in SSI mode, or it failed.
- if (empty($this->connection))
- {
- if (empty($options))
- $options = array('dont_select_db' => SMF == 'SSI');
+ if (empty($this->connection)) {
+ if (empty($options)) {
+ $options = ['dont_select_db' => SMF == 'SSI'];
+ }
$this->initiate(Config::$db_user, Config::$db_passwd, $options);
}
// Safe guard here, if there isn't a valid connection let's put a stop to it.
- if (empty($this->connection) && !$non_fatal)
+ if (empty($this->connection) && !$non_fatal) {
ErrorHandler::displayDbError();
+ }
+
+ // At this point, if we don't have a connection, nothing else can be done.
+ if (empty($this->connection)) {
+ return;
+ }
// For backward compatibility.
- if (!is_object(self::$db_connection))
+ if (!is_object(self::$db_connection)) {
self::$db_connection = $this->connection;
+ }
// Ensure database has UTF-8 as its default input charset.
- $this->query('', '
- SET NAMES {string:db_character_set}',
- array(
+ $this->query(
+ '',
+ 'SET NAMES {string:db_character_set}',
+ [
'db_character_set' => $this->character_set,
- )
+ ],
);
}
@@ -2038,33 +2141,32 @@ protected function __construct(array $options = array())
* @param string $passwd The database password
* @param array $options An array of database options
*/
- protected function initiate($user, $passwd, $options = array())
+ protected function initiate($user, $passwd, $options = [])
{
// We are not going to make it very far without this.
- if (!function_exists('pg_pconnect'))
+ if (!function_exists('pg_pconnect')) {
ErrorHandler::displayDbError();
+ }
// We need to escape ' and \
- $passwd = str_replace(array('\\','\''), array('\\\\','\\\''), $passwd);
+ $passwd = str_replace(['\\', '\''], ['\\\\', '\\\''], $passwd);
// Since pg_connect doesn't feed error info to pg_last_error, we have to catch issues with a try/catch.
set_error_handler(
- function($errno, $errstr)
- {
+ function ($errno, $errstr) {
throw new ErrorException($errstr, $errno);
- }
+ },
);
- try
- {
+
+ try {
$connection_string = (empty($this->server) ? '' : 'host=' . $this->server . ' ') . 'dbname=' . $this->name . ' user=\'' . $user . '\' password=\'' . $passwd . '\'' . (empty($options['port']) ? '' : ' port=\'' . $options['port'] . '\'');
- if (!empty($options['persist']))
+ if (!empty($options['persist'])) {
$this->connection = @pg_pconnect($connection_string);
- else
+ } else {
$this->connection = @pg_connect($connection_string);
- }
- catch (Exception $e)
- {
+ }
+ } catch (Exception $e) {
// Make error info available to calling processes
$this->connect_error = $e->getMessage();
$this->connect_errno = $e->getCode();
@@ -2073,8 +2175,9 @@ function($errno, $errstr)
restore_error_handler();
// Something's wrong, show an error if its fatal (which we assume it is)
- if (empty($this->connection) && empty($options['non_fatal']))
+ if (empty($this->connection) && empty($options['non_fatal'])) {
ErrorHandler::displayDbError();
+ }
}
/**
@@ -2091,145 +2194,155 @@ function($errno, $errstr)
*/
protected function replacement__callback($matches)
{
- if (!is_object($this->temp_connection))
+ if (!is_object($this->temp_connection)) {
ErrorHandler::displayDbError();
+ }
- if ($matches[1] === 'db_prefix')
+ if ($matches[1] === 'db_prefix') {
return $this->prefix;
+ }
- if (isset(User::$me->{$matches[1]}) && strpos($matches[1], 'query_') !== false)
+ if (isset(User::$me->{$matches[1]}) && strpos($matches[1], 'query_') !== false) {
return User::$me->{$matches[1]};
+ }
- if ($matches[1] === 'empty')
+ if ($matches[1] === 'empty') {
return '\'\'';
+ }
- if (!isset($matches[2]))
+ if (!isset($matches[2])) {
$this->error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
- if ($matches[1] === 'literal')
+ if ($matches[1] === 'literal') {
return '\'' . pg_escape_string($this->connection, $matches[2]) . '\'';
+ }
- if (!isset($this->temp_values[$matches[2]]))
+ if (!isset($this->temp_values[$matches[2]])) {
$this->error_backtrace('The database value you\'re trying to insert does not exist: ' . Utils::htmlspecialchars($matches[2]), '', E_USER_ERROR, __FILE__, __LINE__);
+ }
$replacement = $this->temp_values[$matches[2]];
- switch ($matches[1])
- {
+ switch ($matches[1]) {
case 'int':
- if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
+ if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement) {
$this->error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
return (string) (int) $replacement;
- break;
case 'string':
case 'text':
return sprintf('\'%1$s\'', pg_escape_string($this->connection, $replacement));
- break;
case 'array_int':
- if (is_array($replacement))
- {
- if (empty($replacement))
+ if (is_array($replacement)) {
+ if (empty($replacement)) {
$this->error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
- foreach ($replacement as $key => $value)
- {
- if (!is_numeric($value) || (string) $value !== (string) (int) $value)
+ foreach ($replacement as $key => $value) {
+ if (!is_numeric($value) || (string) $value !== (string) (int) $value) {
$this->error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
$replacement[$key] = (string) (int) $value;
}
return implode(', ', $replacement);
}
- else
- $this->error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
+ $this->error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
break;
case 'array_string':
- if (is_array($replacement))
- {
- if (empty($replacement))
+ if (is_array($replacement)) {
+ if (empty($replacement)) {
$this->error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
- foreach ($replacement as $key => $value)
+ foreach ($replacement as $key => $value) {
$replacement[$key] = sprintf('\'%1$s\'', pg_escape_string($this->connection, $value));
+ }
return implode(', ', $replacement);
}
- else
- $this->error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
+ $this->error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
case 'date':
- if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
+ if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1) {
return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]) . '::date';
- else
- $this->error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
+ $this->error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
case 'time':
- if (preg_match('~^([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $time_matches) === 1)
+ if (preg_match('~^([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $time_matches) === 1) {
return sprintf('\'%02d:%02d:%02d\'', $time_matches[1], $time_matches[2], $time_matches[3]) . '::time';
- else
- $this->error_backtrace('Wrong value type sent to the database. Time expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
+ $this->error_backtrace('Wrong value type sent to the database. Time expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
case 'datetime':
- if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d) ([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $datetime_matches) === 1)
+ if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d) ([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $datetime_matches) === 1) {
return 'to_timestamp(' .
sprintf('\'%04d-%02d-%02d %02d:%02d:%02d\'', $datetime_matches[1], $datetime_matches[2], $datetime_matches[3], $datetime_matches[4], $datetime_matches[5], $datetime_matches[6]) .
',\'YYYY-MM-DD HH24:MI:SS\')';
- else
- $this->error_backtrace('Wrong value type sent to the database. Datetime expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
+ $this->error_backtrace('Wrong value type sent to the database. Datetime expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
case 'float':
- if (!is_numeric($replacement))
+ if (!is_numeric($replacement)) {
$this->error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+ }
+
return (string) (float) $replacement;
- break;
case 'identifier':
- return '"' . implode('"."', array_filter(explode('.', strtr($replacement, array('`' => ''))), 'strlen')) . '"';
- break;
+ return '"' . implode('"."', array_filter(explode('.', strtr($replacement, ['`' => ''])), 'strlen')) . '"';
case 'raw':
return $replacement;
- break;
case 'inet':
- if ($replacement == 'null' || $replacement == '')
+ if ($replacement == 'null' || $replacement == '') {
return 'null';
+ }
$ip = new IP($replacement);
- if (!$ip->isValid())
- {
+ if (!$ip->isValid()) {
$this->error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
}
return sprintf('\'%1$s\'::inet', pg_escape_string($this->connection, $ip));
case 'array_inet':
- if (is_array($replacement))
- {
- if (empty($replacement))
- {
+ if (is_array($replacement)) {
+ if (empty($replacement)) {
$this->error_backtrace('Database error, given array of IPv4 or IPv6 values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
}
- foreach ($replacement as $key => $value)
- {
- if ($value == 'null' || $value == '')
+ foreach ($replacement as $key => $value) {
+ if ($value == 'null' || $value == '') {
$replacement[$key] = 'null';
+ }
$ip = new IP($value);
- if (!$ip->isValid())
- {
+ if (!$ip->isValid()) {
$this->error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected.(' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
}
@@ -2238,8 +2351,9 @@ protected function replacement__callback($matches)
return implode(', ', $replacement);
}
- else
- $this->error_backtrace('Wrong value type sent to the database. Array of IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
+ $this->error_backtrace('Wrong value type sent to the database. Array of IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
+
break;
default:
@@ -2260,44 +2374,45 @@ protected function replacement__callback($matches)
*/
protected function error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
{
- if (empty($log_message))
+ if (empty($log_message)) {
$log_message = $error_message;
+ }
- foreach (debug_backtrace() as $step)
- {
+ foreach (debug_backtrace() as $step) {
// Found it?
- if (strpos($step['function'], 'query') === false && !in_array(substr($step['function'], 0, 7), array('smf_db_', 'preg_re', 'db_erro', 'call_us')) && strpos($step['function'], '__') !== 0 && (empty($step['class']) || $step['class'] != $this::class))
- {
+ if (strpos($step['function'], 'query') === false && !in_array(substr($step['function'], 0, 7), ['smf_db_', 'preg_re', 'db_erro', 'call_us']) && strpos($step['function'], '__') !== 0 && (empty($step['class']) || $step['class'] != $this::class)) {
$log_message .= ' Function: ' . $step['function'];
break;
}
- if (isset($step['line']))
- {
+ if (isset($step['line'])) {
$file = $step['file'];
$line = $step['line'];
}
}
// A special case - we want the file and line numbers for debugging.
- if ($error_type == 'return')
- return array($file, $line);
+ if ($error_type == 'return') {
+ return [$file, $line];
+ }
// Is always a critical error.
- if (function_exists('log_error'))
+ if (function_exists('log_error')) {
ErrorHandler::log($log_message, 'critical', $file, $line);
+ }
- if (function_exists('fatal_error'))
- {
+ if (function_exists('fatal_error')) {
ErrorHandler::fatal($error_message, $error_type);
// Cannot continue...
exit;
}
- elseif ($error_type)
+
+ if ($error_type) {
trigger_error($error_message . ($line !== null ? '(' . basename($file) . '-' . $line . ')' : ''), $error_type);
- else
+ } else {
trigger_error($error_message . ($line !== null ? '(' . basename($file) . '-' . $line . ')' : ''));
+ }
}
}
diff --git a/Sources/Db/APIs/index.php b/Sources/Db/APIs/index.php
index 69278ce68e..976d292448 100644
--- a/Sources/Db/APIs/index.php
+++ b/Sources/Db/APIs/index.php
@@ -1,8 +1,8 @@
array(
+ private static $backcompat = [
+ 'func_names' => [
'load' => 'loadDatabase',
'extend' => 'db_extend',
- ),
- 'prop_names' => array(
+ ],
+ 'prop_names' => [
'count' => 'db_count',
'cache' => 'db_cache',
'package_log' => 'db_package_log',
'db_connection' => 'db_connection',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -190,7 +190,7 @@ abstract class DatabaseApi
*
* For backward compatibilty, also referenced as global $db_cache.
*/
- public static array $cache = array();
+ public static array $cache = [];
/**
* @var array
@@ -199,7 +199,7 @@ abstract class DatabaseApi
*
* For backward compatibilty, also referenced as global $db_package_log.
*/
- public static array $package_log = array();
+ public static array $package_log = [];
/**
* @var object
@@ -231,7 +231,7 @@ abstract class DatabaseApi
*
* SMF tables that can't be auto-removed - in case a mod writer cocks it up!
*/
- protected array $reservedTables = array(
+ protected array $reservedTables = [
'admin_info_files',
'approval_queue',
'attachments',
@@ -305,7 +305,7 @@ abstract class DatabaseApi
'user_alerts_prefs',
'user_drafts',
'user_likes',
- );
+ ];
/***********************
* Public static methods
@@ -319,14 +319,34 @@ abstract class DatabaseApi
* @param array $options An array of database options.
* @return object An instance of a child class of this class.
*/
- final public static function load(array $options = array())
+ final public static function load(array $options = [])
{
- if (isset(self::$db))
+ if (isset(self::$db)) {
return self::$db;
+ }
// Figure out what type of database we are using.
- switch (!empty(Config::$db_type) ? strtolower(Config::$db_type) : 'mysql')
- {
+ $class = self::getClass(!empty(Config::$db_type) ? strtolower(Config::$db_type) : 'mysql');
+
+ if (!class_exists(__NAMESPACE__ . '\\APIs\\' . $class)) {
+ ErrorHandler::displayDbError();
+ }
+
+ $class = __NAMESPACE__ . '\\APIs\\' . $class;
+ self::$db = new $class($options);
+
+ // Double check that we found what we expected.
+ if (!(self::$db instanceof DatabaseApi)) {
+ unset(self::$db);
+ ErrorHandler::displayDbError();
+ }
+
+ return self::$db;
+ }
+
+ public static function getClass($db_type)
+ {
+ switch (strtolower($db_type)) {
// PostgreSQL is known by many names.
case 'postgresql':
case 'postgres':
@@ -347,26 +367,14 @@ final public static function load(array $options = array())
$class = ucwords(Config::$db_type);
// If the necessary class doesn't exist, fall back to MySQL.
- if (!class_exists(__NAMESPACE__ . '\\APIs\\' . $class))
+ if (!class_exists(__NAMESPACE__ . '\\APIs\\' . $class)) {
$class = MYSQL_TITLE;
+ }
break;
}
- if (!class_exists(__NAMESPACE__ . '\\APIs\\' . $class))
- ErrorHandler::displayDbError();
-
- $class = __NAMESPACE__ . '\\APIs\\' . $class;
- self::$db = new $class($options);
-
- // Double check that we found what we expected.
- if (!(self::$db instanceof DatabaseApi))
- {
- unset($self::$db);
- ErrorHandler::displayDbError();
- }
-
- return self::$db;
+ return $class;
}
/**
@@ -385,32 +393,41 @@ public static function extend()
*/
protected function __construct()
{
- if (!isset($this->server))
+ if (!isset($this->server)) {
$this->server = (string) Config::$db_server;
+ }
- if (!isset($this->name))
+ if (!isset($this->name)) {
$this->name = (string) Config::$db_name;
+ }
- if (!isset($this->prefix))
+ if (!isset($this->prefix)) {
$this->prefix = (string) Config::$db_prefix;
+ }
- if (!isset($this->port))
+ if (!isset($this->port)) {
$this->port = !empty(Config::$db_port) ? (int) Config::$db_port : 0;
+ }
- if (!isset($this->persist))
+ if (!isset($this->persist)) {
$this->persist = !empty(Config::$db_persist);
+ }
- if (!isset($this->mb4))
+ if (!isset($this->mb4)) {
$this->mb4 = !empty(Config::$db_mb4);
+ }
- if (!isset($this->character_set))
+ if (!isset($this->character_set)) {
$this->character_set = (string) Config::$db_character_set;
+ }
- if (!isset($this->show_debug))
+ if (!isset($this->show_debug)) {
$this->show_debug = !empty(Config::$db_show_debug);
+ }
- if (!isset($this->disableQueryCheck))
+ if (!isset($this->disableQueryCheck)) {
$this->disableQueryCheck = !empty(Config::$modSettings['disableQueryCheck']);
+ }
$this->prefixReservedTables();
@@ -428,8 +445,9 @@ protected function prefixReservedTables()
$this->reservedTables = $class_vars['reservedTables'];
// Prepend the prefix.
- foreach ($this->reservedTables as $k => $table_name)
+ foreach ($this->reservedTables as $k => $table_name) {
$this->reservedTables[$k] = strtolower($this->prefix . $table_name);
+ }
}
/**
@@ -439,21 +457,22 @@ protected function prefixReservedTables()
protected function mapToSmcFunc()
{
// Only do this once.
- if (isset(Utils::$smcFunc['db_fetch_assoc']))
+ if (isset(Utils::$smcFunc['db_fetch_assoc'])) {
return;
+ }
// Scalar values to export.
- Utils::$smcFunc += array(
+ Utils::$smcFunc += [
'db_title' => &$this->title,
'db_sybase' => &$this->sybase,
'db_case_sensitive' => &$this->case_sensitive,
'db_mb4' => &$this->mb4,
'db_support_ignore' => &$this->support_ignore,
'db_supports_pcre' => &$this->supports_pcre,
- );
+ ];
// Methods to export.
- $methods = array(
+ $methods = [
// Basic
'db_affected_rows' => 'affected_rows',
'db_connect_errno' => 'connect_errno',
@@ -510,13 +529,11 @@ protected function mapToSmcFunc()
'db_search_language' => 'search_language',
'db_search_query' => 'query',
'db_search_support' => 'search_support',
- );
+ ];
// Wrap each method in a closure that calls it.
- foreach ($methods as $key => $method)
- {
- Utils::$smcFunc[$key] = function(...$args) use ($method)
- {
+ foreach ($methods as $key => $method) {
+ Utils::$smcFunc[$key] = function (...$args) use ($method) {
return $this->$method(...$args);
};
}
@@ -524,7 +541,8 @@ protected function mapToSmcFunc()
}
// Export public static functions to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\DatabaseApi::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\DatabaseApi::exportStatic')) {
DatabaseApi::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/Db/DatabaseApiInterface.php b/Sources/Db/DatabaseApiInterface.php
index 08165be40b..2d70f4da6a 100644
--- a/Sources/Db/DatabaseApiInterface.php
+++ b/Sources/Db/DatabaseApiInterface.php
@@ -27,7 +27,7 @@ interface DatabaseApiInterface
* @param resource $connection = null The connection to use (null to use $db_connection)
* @return resource|bool Returns a query result resource (for SELECT queries), true (for UPDATE queries) or false if the query failed.
*/
- public function query($identifier, $db_string, $db_values = array(), $connection = null);
+ public function query($identifier, $db_string, $db_values = [], $connection = null);
/**
* Prepares a query string for execution, but does not perform the query.
@@ -72,8 +72,8 @@ public function free_result($result);
* Gets the ID of the most recently inserted row.
*
* @param string $table The table (only used for Postgres).
- * @param string $field = null The specific field (not used here).
* @param resource $connection = null The connection (if null, $db_connection is used).
+ * @param string $field = null The specific field (not used here).
* @return int The ID of the most recently inserted row.
*/
public function insert($method, $table, $columns, $data, $keys, $returnmode = 0, $connection = null);
@@ -99,8 +99,8 @@ public function num_rows($result);
/**
* Adjusts the result pointer to an arbitrary row in a query result.
*
- * @param resource $request A query result resource.
* @param int $offset The row offset.
+ * @param resource $request A query result resource.
* @return bool True on success, or false on failuer.
*/
public function data_seek($result, int $offset);
@@ -117,8 +117,8 @@ public function num_fields($result);
* Escapes special characters in a string for use in an SQL statement,
* taking into account the current character set of the connection.
*
- * @param string The unescaped string.
* @param resource $connection = null The connection to use (null to use $db_connection).
+ * @param string The unescaped string.
* @return string The escaped string.
*/
public function escape_string(string $string, $connection = null);
@@ -210,7 +210,6 @@ public function ping($connection = null);
* id_member, log_time, ip, url, message, session, error_type, file, line, backtrace
*
* @param array Information about the error.
- * @return void
*/
public function error_insert($error_array);
@@ -220,7 +219,7 @@ public function error_insert($error_array);
*
* @param string $field name
* @param array $array_values Field values sequenced in array via order priority. Must cast to int.
- * @param boolean $desc default false
+ * @param bool $desc default false
* @return string case field when ... then ... end
*/
public function custom_order($field, $array_values, $desc = false);
@@ -228,14 +227,14 @@ public function custom_order($field, $array_values, $desc = false);
/**
* Function which return the information if the database supports native replace inserts
*
- * @return boolean true or false
+ * @return bool true or false
*/
public function native_replace();
/**
* Function which return the information if the database supports cte with recursive
*
- * @return boolean true or false
+ * @return bool true or false
*/
public function cte_support();
@@ -287,8 +286,8 @@ public function table_sql($tableName);
* This function lists all tables in the database.
* The listing could be filtered according to $filter.
*
- * @param string|boolean $db string The database name or false to use the current DB
- * @param string|boolean $filter String to filter by or false to list all tables
+ * @param string|bool $db string The database name or false to use the current DB
+ * @param string|bool $filter String to filter by or false to list all tables
* @return array An array of table names
*/
public function list_tables($db = false, $filter = false);
@@ -310,7 +309,7 @@ public function get_vendor();
/**
* Figures out if persistent connection is allowed
*
- * @return boolean
+ * @return bool
*/
public function allow_persistent();
@@ -327,13 +326,13 @@ public function allow_persistent();
* @param resource $connection The current DB connection resource
* @return resource The query result resource from $this->query()
*/
- public function search_query($identifier, $db_string, $db_values = array(), $connection = null);
+ public function search_query($identifier, $db_string, $db_values = [], $connection = null);
/**
* This function will tell you whether this database type supports this search type.
*
* @param string $search_type The search type.
- * @return boolean Whether or not the specified search type is supported by this db system
+ * @return bool Whether or not the specified search type is supported by this db system
*/
public function search_support($search_type);
@@ -363,9 +362,9 @@ public function search_language();
* @param array $parameters Not used?
* @param string $if_exists What to do if the column exists. If 'update', column is updated.
* @param string $error
- * @return boolean Whether or not the operation was successful
+ * @return bool Whether or not the operation was successful
*/
- public function add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal');
+ public function add_column($table_name, $column_info, $parameters = [], $if_exists = 'update', $error = 'fatal');
/**
* Add an index.
@@ -375,16 +374,16 @@ public function add_column($table_name, $column_info, $parameters = array(), $if
* @param array $parameters Not used?
* @param string $if_exists What to do if the index exists. If 'update', the definition will be updated.
* @param string $error
- * @return boolean Whether or not the operation was successful
+ * @return bool Whether or not the operation was successful
*/
- public function add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal');
+ public function add_index($table_name, $index_info, $parameters = [], $if_exists = 'update', $error = 'fatal');
/**
* Get the schema formatted name for a type.
*
* @param string $type_name The data type (int, varchar, smallint, etc.)
* @param int $type_size The size (8, 255, etc.)
- * @param boolean $reverse
+ * @param bool $reverse
* @return array An array containing the appropriate type and size for this DB type
*/
public function calculate_type($type_name, $type_size = null, $reverse = false);
@@ -432,9 +431,9 @@ public function change_column($table_name, $old_column, $column_info);
* @param array $parameters Extra parameters. Currently only 'engine', the desired MySQL storage engine, is used.
* @param string $if_exists What to do if the table exists.
* @param string $error
- * @return boolean Whether or not the operation was successful
+ * @return bool Whether or not the operation was successful
*/
- public function create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal');
+ public function create_table($table_name, $columns, $indexes = [], $parameters = [], $if_exists = 'ignore', $error = 'fatal');
/**
* Drop a table.
@@ -442,9 +441,9 @@ public function create_table($table_name, $columns, $indexes = array(), $paramet
* @param string $table_name The name of the table to drop
* @param array $parameters Not used at the moment
* @param string $error
- * @return boolean Whether or not the operation was successful
+ * @return bool Whether or not the operation was successful
*/
- public function drop_table($table_name, $parameters = array(), $error = 'fatal');
+ public function drop_table($table_name, $parameters = [], $error = 'fatal');
/**
* Get table structure.
@@ -462,7 +461,7 @@ public function table_structure($table_name);
* @param array $parameters Not used?
* @return array An array of column names or detailed column info, depending on $detail
*/
- public function list_columns($table_name, $detail = false, $parameters = array());
+ public function list_columns($table_name, $detail = false, $parameters = []);
/**
* Get index information.
@@ -472,7 +471,7 @@ public function list_columns($table_name, $detail = false, $parameters = array()
* @param array $parameters Not used?
* @return array An array of index names or a detailed array of index info, depending on $detail
*/
- public function list_indexes($table_name, $detail = false, $parameters = array());
+ public function list_indexes($table_name, $detail = false, $parameters = []);
/**
* Removes a column.
@@ -481,9 +480,9 @@ public function list_indexes($table_name, $detail = false, $parameters = array()
* @param string $column_name The name of the column to drop
* @param array $parameters Not used?
* @param string $error
- * @return boolean Whether or not the operation was successful
+ * @return bool Whether or not the operation was successful
*/
- public function remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal');
+ public function remove_column($table_name, $column_name, $parameters = [], $error = 'fatal');
/**
* Remove an index.
@@ -492,9 +491,9 @@ public function remove_column($table_name, $column_name, $parameters = array(),
* @param string $index_name The name of the index to remove
* @param array $parameters Not used?
* @param string $error
- * @return boolean Whether or not the operation was successful
+ * @return bool Whether or not the operation was successful
*/
- public function remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal');
+ public function remove_index($table_name, $index_name, $parameters = [], $error = 'fatal');
}
?>
\ No newline at end of file
diff --git a/Sources/Db/index.php b/Sources/Db/index.php
index 69278ce68e..976d292448 100644
--- a/Sources/Db/index.php
+++ b/Sources/Db/index.php
@@ -1,8 +1,8 @@
array(
- 'save' => 'SaveDraft',
+ private static $backcompat = [
+ 'func_names' => [
'delete' => 'DeleteDraft',
'showInEditor' => 'ShowDrafts',
'showInProfile' => 'showProfileDrafts',
- ),
- );
+ ],
+ ];
/*******************
* Public properties
@@ -147,10 +146,10 @@ class Draft
* Intended recipients for this draft.
* Only applies to personal message drafts.
*/
- public array $recipients = array(
- 'to' => array(),
- 'bcc' => array(),
- );
+ public array $recipients = [
+ 'to' => [],
+ 'bcc' => [],
+ ];
/*********************
* Internal properties
@@ -181,27 +180,21 @@ class Draft
* @param bool $check Validate that this draft belongs to the current user.
* @param array $recipientList Only used by the DraftPM class.
*/
- public function __construct(int $id_draft = 0, bool $check = true, array $recipientList = array())
+ public function __construct(int $id_draft = 0, bool $check = true, array $recipientList = [])
{
$this->id = $id_draft;
// Load any existing data for this draft.
- if (!empty($this->id))
- {
+ if (!empty($this->id)) {
$draft_info = self::read($check);
// Requested a draft that doesn't exist or belongs to someone else.
- if (empty($draft_info['id_draft']))
- {
+ if (empty($draft_info['id_draft'])) {
$this->id = 0;
- }
- else
- {
+ } else {
// Set the properties according to the existing data.
- foreach ($draft_info as $key => $value)
- {
- switch ($key)
- {
+ foreach ($draft_info as $key => $value) {
+ switch ($key) {
case 'id_draft':
$this->id = $value;
break;
@@ -219,8 +212,8 @@ public function __construct(int $id_draft = 0, bool $check = true, array $recipi
case 'to_list':
$recipientsList = Utils::jsonDecode($draft_info['to_list'], true);
- $this->recipients['to'] = $recipientsList['to'] ?? array();
- $this->recipients['bcc'] = $recipientsList['bcc'] ?? array();
+ $this->recipients['to'] = $recipientsList['to'] ?? [];
+ $this->recipients['bcc'] = $recipientsList['bcc'] ?? [];
break;
default:
@@ -232,15 +225,12 @@ public function __construct(int $id_draft = 0, bool $check = true, array $recipi
}
// Determine who this is being sent to.
- if (isset($_REQUEST['xml']))
- {
- $recipientList['to'] = isset($_POST['recipient_to']) ? explode(',', $_POST['recipient_to']) : array();
- $recipientList['bcc'] = isset($_POST['recipient_bcc']) ? explode(',', $_POST['recipient_bcc']) : array();
- }
- elseif (!empty($recipientList))
- {
- $recipientList['to'] = $recipientList['to'] ?? array();
- $recipientList['bcc'] = $recipientList['bcc'] ?? array();
+ if (isset($_REQUEST['xml'])) {
+ $recipientList['to'] = isset($_POST['recipient_to']) ? explode(',', $_POST['recipient_to']) : [];
+ $recipientList['bcc'] = isset($_POST['recipient_bcc']) ? explode(',', $_POST['recipient_bcc']) : [];
+ } elseif (!empty($recipientList)) {
+ $recipientList['to'] = $recipientList['to'] ?? [];
+ $recipientList['bcc'] = $recipientList['bcc'] ?? [];
}
$this->setProperties($recipientList);
@@ -249,7 +239,6 @@ public function __construct(int $id_draft = 0, bool $check = true, array $recipi
/**
* Prepares the draft data for use in the editor.
*
- * @return void
*/
public function prepare(): void
{
@@ -279,20 +268,22 @@ public function prepare(): void
public function save(&$post_errors): bool
{
// can you be, should you be ... here?
- if (empty(Config::$modSettings[$this->enabled_setting]) || !User::$me->allowedTo($this->permission) || !isset($_POST['save_draft']))
+ if (empty(Config::$modSettings[$this->enabled_setting]) || !User::$me->allowedTo($this->permission) || !isset($_POST['save_draft'])) {
return false;
+ }
- if (in_array('session_timeout', $post_errors))
+ if (in_array('session_timeout', $post_errors)) {
return false;
+ }
// A draft has been saved less than 5 seconds ago, let's not do the autosave again.
- if (isset($_REQUEST['xml']) && !empty($this->poster_time) && time() < $this->poster_time + 5)
- {
+ if (isset($_REQUEST['xml']) && !empty($this->poster_time) && time() < $this->poster_time + 5) {
Utils::$context['draft_saved_on'] = $this->poster_time;
// Since we were called from the autosave function, send something back.
- if (!empty($this->id))
+ if (!empty($this->id)) {
self::xml($this->id);
+ }
return true;
}
@@ -300,12 +291,12 @@ public function save(&$post_errors): bool
// Update the database entry.
$saved = $this->saveToDatabase();
- if (!$saved)
+ if (!$saved) {
$post_errors[] = 'draft_not_saved';
+ }
// If we were called from the autosave function, send something back.
- if (!empty($this->id) && isset($_REQUEST['xml']))
- {
+ if (!empty($this->id) && isset($_REQUEST['xml'])) {
Utils::$context['draft_saved_on'] = time();
self::xml($this->id);
}
@@ -330,17 +321,19 @@ public static function delete(int|array $drafts, bool $check = true): bool
{
$drafts = (array) $drafts;
- if (empty($drafts) || ($check && empty(User::$me->id)))
+ if (empty($drafts) || ($check && empty(User::$me->id))) {
return false;
+ }
- Db::$db->query('', '
- DELETE FROM {db_prefix}user_drafts
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}user_drafts
WHERE id_draft IN ({array_int:drafts})' . ($check ? '
AND id_member = {int:id_member}' : ''),
- array(
+ [
'drafts' => $drafts,
'id_member' => empty(User::$me->id) ? -1 : User::$me->id,
- )
+ ],
);
return true;
@@ -358,43 +351,45 @@ public static function delete(int|array $drafts, bool $check = true): bool
public static function showInEditor(int $member_id, int $topic = 0): bool
{
// Permissions
- if (empty(Utils::$context['drafts_save']) || empty($member_id))
+ if (empty(Utils::$context['drafts_save']) || empty($member_id)) {
return false;
+ }
Lang::load('Drafts');
- Utils::$context['drafts'] = array();
+ Utils::$context['drafts'] = [];
// Load the drafts this user has available.
- $request = Db::$db->query('', '
- SELECT subject, poster_time, id_board, id_topic, id_draft
+ $request = Db::$db->query(
+ '',
+ 'SELECT subject, poster_time, id_board, id_topic, id_draft
FROM {db_prefix}user_drafts
WHERE id_member = {int:id_member}' . (!empty($topic) ? '
AND id_topic = {int:id_topic}' : '') . '
AND type = {int:draft_type}' . (!empty(Config::$modSettings['drafts_keep_days']) ? '
AND poster_time > {int:time}' : '') . '
ORDER BY poster_time DESC',
- array(
+ [
'id_member' => $member_id,
'id_topic' => $topic,
'draft_type' => 0,
'time' => (!empty(Config::$modSettings['drafts_keep_days']) ? (time() - (Config::$modSettings['drafts_keep_days'] * 86400)) : 0),
- )
+ ],
);
// Add them to the drafts array for display.
- while ($row = Db::$db->fetch_assoc($request))
- {
- if (empty($row['subject']))
+ while ($row = Db::$db->fetch_assoc($request)) {
+ if (empty($row['subject'])) {
$row['subject'] = Lang::$txt['no_subject'];
+ }
$tmp_subject = Utils::shorten(stripslashes($row['subject']), 24);
- Utils::$context['drafts'][] = array(
+ Utils::$context['drafts'][] = [
'subject' => Lang::censorText($tmp_subject),
'poster_time' => Time::create('@' . $row['poster_time'])->format(),
'link' => '' . $row['subject'] . '',
- );
+ ];
}
Db::$db->free_result($request);
@@ -408,7 +403,6 @@ public static function showInEditor(int $member_id, int $topic = 0): bool
* The UI allows for deleting and loading/editing of drafts.
*
* @param int $memID ID of the user whose drafts should be loaded.
- * @return void
*/
public static function showInProfile(int $memID): void
{
@@ -419,46 +413,48 @@ public static function showInProfile(int $memID): void
Utils::$context['current_member'] = $memID;
// If just deleting a draft, do it and then redirect back.
- if (!empty($_REQUEST['delete']))
- {
+ if (!empty($_REQUEST['delete'])) {
User::$me->checkSession('get');
$id_delete = (int) $_REQUEST['delete'];
- Db::$db->query('', '
- DELETE FROM {db_prefix}user_drafts
+ Db::$db->query(
+ '',
+ 'DELETE FROM {db_prefix}user_drafts
WHERE id_draft = {int:id_draft}
AND id_member = {int:id_member}
AND type = {int:draft_type}',
- array(
+ [
'id_draft' => $id_delete,
'id_member' => $memID,
'draft_type' => 0,
- )
+ ],
);
Utils::redirectexit('action=profile;u=' . $memID . ';area=showdrafts;start=' . Utils::$context['start']);
}
// Default to 10.
- if (empty($_REQUEST['viewscount']) || !is_numeric($_REQUEST['viewscount']))
+ if (empty($_REQUEST['viewscount']) || !is_numeric($_REQUEST['viewscount'])) {
$_REQUEST['viewscount'] = 10;
+ }
// Get the count of applicable drafts on the boards they can (still) see ...
// @todo .. should we just let them see their drafts even if they have lost board access ?
- $request = Db::$db->query('', '
- SELECT COUNT(*)
+ $request = Db::$db->query(
+ '',
+ 'SELECT COUNT(*)
FROM {db_prefix}user_drafts AS ud
INNER JOIN {db_prefix}boards AS b ON (b.id_board = ud.id_board AND {query_see_board})
WHERE id_member = {int:id_member}
AND type={int:draft_type}' . (!empty(Config::$modSettings['drafts_keep_days']) ? '
AND poster_time > {int:time}' : ''),
- array(
+ [
'id_member' => $memID,
'draft_type' => 0,
'time' => (!empty(Config::$modSettings['drafts_keep_days']) ? (time() - (Config::$modSettings['drafts_keep_days'] * 86400)) : 0),
- )
+ ],
);
- list ($msgCount) = Db::$db->fetch_row($request);
+ list($msgCount) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
$maxPerPage = empty(Config::$modSettings['disableCustomPerPage']) && !empty(Theme::$current->options['messages_per_page']) ? Theme::$current->options['messages_per_page'] : Config::$modSettings['defaultMaxMessages'];
@@ -471,8 +467,8 @@ public static function showInProfile(int $memID): void
// Reverse the query if we're past 50% of the pages for better performance.
$start = Utils::$context['start'];
$reverse = $_REQUEST['start'] > $msgCount / 2;
- if ($reverse)
- {
+
+ if ($reverse) {
$maxIndex = $msgCount < Utils::$context['start'] + $maxPerPage + 1 && $msgCount > Utils::$context['start'] ? $msgCount - Utils::$context['start'] : $maxPerPage;
$start = $msgCount < Utils::$context['start'] + $maxPerPage + 1 || $msgCount < Utils::$context['start'] + $maxPerPage ? 0 : $msgCount - Utils::$context['start'] - $maxPerPage;
}
@@ -480,8 +476,9 @@ public static function showInProfile(int $memID): void
// Find this user's drafts for the boards they can access
// @todo ... do we want to do this? If they were able to create a draft, do we remove their access to said draft if they loose
// access to the board or if the topic moves to a board they can not see?
- $request = Db::$db->query('', '
- SELECT
+ $request = Db::$db->query(
+ '',
+ 'SELECT
b.id_board, b.name AS bname,
ud.id_member, ud.id_draft, ud.body, ud.smileys_enabled, ud.subject, ud.poster_time, ud.icon, ud.id_topic, ud.locked, ud.is_sticky
FROM {db_prefix}user_drafts AS ud
@@ -491,27 +488,30 @@ public static function showInProfile(int $memID): void
AND poster_time > {int:time}' : '') . '
ORDER BY ud.id_draft ' . ($reverse ? 'ASC' : 'DESC') . '
LIMIT {int:start}, {int:max}',
- array(
+ [
'current_member' => $memID,
'draft_type' => 0,
'time' => (!empty(Config::$modSettings['drafts_keep_days']) ? (time() - (Config::$modSettings['drafts_keep_days'] * 86400)) : 0),
'start' => $start,
'max' => $maxIndex,
- )
+ ],
);
// Start counting at the number of the first message displayed.
$counter = $reverse ? Utils::$context['start'] + $maxIndex + 1 : Utils::$context['start'];
- Utils::$context['posts'] = array();
- while ($row = Db::$db->fetch_assoc($request))
- {
+ Utils::$context['posts'] = [];
+
+ while ($row = Db::$db->fetch_assoc($request)) {
// Censor....
- if (empty($row['body']))
+ if (empty($row['body'])) {
$row['body'] = '';
+ }
$row['subject'] = Utils::htmlTrim($row['subject']);
- if (empty($row['subject']))
+
+ if (empty($row['subject'])) {
$row['subject'] = Lang::$txt['no_subject'];
+ }
Lang::censorText($row['body']);
Lang::censorText($row['subject']);
@@ -520,17 +520,17 @@ public static function showInProfile(int $memID): void
$row['body'] = BBCodeParser::load()->parse($row['body'], $row['smileys_enabled'], 'draft' . $row['id_draft']);
// And the array...
- Utils::$context['drafts'][$counter += $reverse ? -1 : 1] = array(
+ Utils::$context['drafts'][$counter += $reverse ? -1 : 1] = [
'body' => $row['body'],
'counter' => $counter,
- 'board' => array(
+ 'board' => [
'name' => $row['bname'],
- 'id' => $row['id_board']
- ),
- 'topic' => array(
+ 'id' => $row['id_board'],
+ ],
+ 'topic' => [
'id' => $row['id_topic'],
'link' => empty($row['id']) ? $row['subject'] : '' . $row['subject'] . '',
- ),
+ ],
'subject' => $row['subject'],
'time' => Time::create('@' . $row['poster_time'])->format(),
'timestamp' => $row['poster_time'],
@@ -538,34 +538,35 @@ public static function showInProfile(int $memID): void
'id_draft' => $row['id_draft'],
'locked' => $row['locked'],
'sticky' => $row['is_sticky'],
- 'quickbuttons' => array(
- 'edit' => array(
+ 'quickbuttons' => [
+ 'edit' => [
'label' => Lang::$txt['draft_edit'],
- 'href' => Config::$scripturl.'?action=post;'.(empty($row['id_topic']) ? 'board='.$row['id_board'] : 'topic='.$row['id_topic']).'.0;id_draft='.$row['id_draft'],
- 'icon' => 'modify_button'
- ),
- 'delete' => array(
+ 'href' => Config::$scripturl . '?action=post;' . (empty($row['id_topic']) ? 'board=' . $row['id_board'] : 'topic=' . $row['id_topic']) . '.0;id_draft=' . $row['id_draft'],
+ 'icon' => 'modify_button',
+ ],
+ 'delete' => [
'label' => Lang::$txt['draft_delete'],
- 'href' => Config::$scripturl.'?action=profile;u='.Utils::$context['member']['id'].';area=showdrafts;delete='.$row['id_draft'].';'.Utils::$context['session_var'].'='.Utils::$context['session_id'],
- 'javascript' => 'data-confirm="'.Lang::$txt['draft_remove'].'"',
+ 'href' => Config::$scripturl . '?action=profile;u=' . Utils::$context['member']['id'] . ';area=showdrafts;delete=' . $row['id_draft'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'],
+ 'javascript' => 'data-confirm="' . Lang::$txt['draft_remove'] . '"',
'class' => 'you_sure',
- 'icon' => 'remove_button'
- ),
- ),
- );
+ 'icon' => 'remove_button',
+ ],
+ ],
+ ];
}
Db::$db->free_result($request);
// If the drafts were retrieved in reverse order, get them right again.
- if ($reverse)
+ if ($reverse) {
Utils::$context['drafts'] = array_reverse(Utils::$context['drafts'], true);
+ }
// Menu tab
- Menu::$loaded['profile']->tab_data = array(
+ Menu::$loaded['profile']->tab_data = [
'title' => Lang::$txt['drafts_show'],
'description' => Lang::$txt['drafts_show_desc'],
- 'icon_class' => 'main_icons drafts'
- );
+ 'icon_class' => 'main_icons drafts',
+ ];
Utils::$context['sub_template'] = 'showDrafts';
}
@@ -578,41 +579,41 @@ public static function showInProfile(int $memID): void
*
* Optionally validates that this draft belongs to the current user.
*
- * @param boolean $check Validate that this draft belongs to this user.
+ * @param bool $check Validate that this draft belongs to this user.
* Default: true.
* @return array Data about the draft. Empty if draft was not found.
*/
protected function read($check = true): array
{
// Nothing to read, nothing to do.
- if (empty($this->id))
- return array();
+ if (empty($this->id)) {
+ return [];
+ }
// Fetch this draft's info from the database.
- $request = Db::$db->query('', '
- SELECT *
+ $request = Db::$db->query(
+ '',
+ 'SELECT *
FROM {db_prefix}user_drafts
WHERE id_draft = {int:id_draft}' . ($check ? '
AND id_member = {int:id_member}' : '') . '
AND type = {int:type}' . (!empty(Config::$modSettings['drafts_keep_days']) ? '
AND poster_time > {int:time}' : '') . '
LIMIT 1',
- array(
+ [
'id_member' => User::$me->id,
'id_draft' => $this->id,
'type' => $this->type,
'time' => (!empty(Config::$modSettings['drafts_keep_days']) ? (time() - (Config::$modSettings['drafts_keep_days'] * 86400)) : 0),
- )
+ ],
);
// No results?
- if (empty(Db::$db->num_rows($request)))
- {
- $draft_info = array();
+ if (empty(Db::$db->num_rows($request))) {
+ $draft_info = [];
}
// Retrieve the data.
- else
- {
+ else {
$draft_info = Db::$db->fetch_assoc($request);
}
@@ -626,54 +627,65 @@ protected function read($check = true): array
*
* @param array $recipientList ID numbers of members the PM will be sent to,
* grouped into 'to' and 'bcc' sub-arrays. Only applies to PM drafts.
- * @return void
*/
- protected function setProperties(array $recipientList = array()): void
+ protected function setProperties(array $recipientList = []): void
{
- if (!isset($_POST['message']) && isset($_POST['quickReply']))
+ if (!isset($_POST['message']) && isset($_POST['quickReply'])) {
$_POST['message'] = $_POST['quickReply'];
+ }
- if (isset($_POST['message']))
- {
+ if (isset($_POST['message'])) {
$body = Utils::htmlspecialchars($_POST['message'], ENT_QUOTES);
Msg::preparsecode($body);
}
- if (isset($body))
+ if (isset($body)) {
$this->body = $body;
+ }
- if (isset($_POST['subject']))
+ if (isset($_POST['subject'])) {
$this->subject = Utils::entitySubstr(trim(preg_replace('/(\pZ| )+/u', ' ', Utils::htmlspecialchars($_POST['subject']))), 0, 100);
+ }
- if (empty($this->member))
+ if (empty($this->member)) {
$this->member = User::$me->id;
+ }
- if (isset($_POST['ns']))
+ if (isset($_POST['ns'])) {
$this->smileys_enabled = !empty($_POST['ns']);
+ }
- if (isset($_POST['sticky']))
+ if (isset($_POST['sticky'])) {
$this->sticky = !empty($_POST['sticky']);
+ }
- if (isset($_POST['lock']))
+ if (isset($_POST['lock'])) {
$this->locked = !empty($_POST['lock']);
+ }
- if (!empty($_POST['icon']) && preg_match('/^\w+$/', $_POST['icon']))
+ if (!empty($_POST['icon']) && preg_match('/^\w+$/', $_POST['icon'])) {
$this->icon = $_POST['icon'];
+ }
- if (!empty($_REQUEST['topic']))
+ if (!empty($_REQUEST['topic'])) {
$this->topic = (int) $_REQUEST['topic'];
+ }
- if (empty($this->board))
+ if (empty($this->board)) {
$this->board = Board::$info->id ?? 0;
+ }
- if (!empty($_POST['replied_to']))
+ if (!empty($_POST['replied_to'])) {
$this->reply_to = (int) $_POST['replied_to'];
+ }
- if (!empty($recipientList['to']))
+ if (!empty($recipientList['to'])) {
$this->recipients['to'] = (array) $recipientList['to'];
+ }
- if (!empty($recipientList['bcc']))
+ if (!empty($recipientList['bcc'])) {
$this->recipients['bcc'] = (array) $recipientList['bcc'];
+ }
// These arrays should contain only integers.
$this->recipients['to'] = array_map('intval', $this->recipients['to']);
@@ -688,10 +700,10 @@ protected function setProperties(array $recipientList = array()): void
protected function saveToDatabase(): bool
{
// Updating an existing draft.
- if (!empty($this->id))
- {
- Db::$db->query('', '
- UPDATE {db_prefix}user_drafts
+ if (!empty($this->id)) {
+ Db::$db->query(
+ '',
+ 'UPDATE {db_prefix}user_drafts
SET
id_topic = {int:id_topic},
id_board = {int:id_board},
@@ -706,7 +718,7 @@ protected function saveToDatabase(): bool
is_sticky = {int:sticky},
to_list = {string:to_list}
WHERE id_draft = {int:id_draft}',
- array(
+ [
'id_draft' => $this->id,
'id_topic' => $this->topic,
'id_board' => $this->board,
@@ -720,7 +732,7 @@ protected function saveToDatabase(): bool
'locked' => (int) $this->locked,
'sticky' => (int) $this->sticky,
'to_list' => Utils::jsonEncode($this->recipients),
- )
+ ],
);
$this->poster_time = time();
@@ -730,11 +742,11 @@ protected function saveToDatabase(): bool
Utils::$context['id' . ($this->type === 1 ? '_pm' : '') . '_draft'] = $this->id;
}
// Otherwise, creating a new draft.
- else
- {
- $this->id = Db::$db->insert('',
+ else {
+ $this->id = Db::$db->insert(
+ '',
'{db_prefix}user_drafts',
- array(
+ [
'id_topic' => 'int',
'id_board' => 'int',
'id_reply' => 'int',
@@ -748,8 +760,8 @@ protected function saveToDatabase(): bool
'locked' => 'int',
'is_sticky' => 'int',
'to_list' => 'string-255',
- ),
- array(
+ ],
+ [
$this->topic,
$this->board,
$this->reply_to,
@@ -763,22 +775,21 @@ protected function saveToDatabase(): bool
(int) $this->locked,
(int) $this->sticky,
Utils::jsonEncode($this->recipients),
- ),
- array(
- 'id_draft'
- ),
- 1
+ ],
+ [
+ 'id_draft',
+ ],
+ 1,
);
// Did everything go as expected?
- if (!empty($this->id))
- {
+ if (!empty($this->id)) {
$this->poster_time = time();
Utils::$context['draft_saved'] = true;
Utils::$context['id' . ($this->type === 1 ? '_pm' : '') . '_draft'] = $this->id;
- }
- else
+ } else {
Utils::$context['draft_saved'] = false;
+ }
}
// Cleanup
@@ -793,7 +804,6 @@ protected function saveToDatabase(): bool
* Provides the ID of the draft saved and the time it was saved.
*
* @param int $id_draft
- * @return void
*/
protected static function xml(int $id_draft): void
{
@@ -811,7 +821,8 @@ protected static function xml(int $id_draft): void
}
// Export public static functions and properties to global namespace for backward compatibility.
-if (is_callable(__NAMESPACE__ . '\Draft::exportStatic'))
+if (is_callable(__NAMESPACE__ . '\\Draft::exportStatic')) {
Draft::exportStatic();
+}
?>
\ No newline at end of file
diff --git a/Sources/DynamicPropertyHelper.php b/Sources/DynamicPropertyHelper.php
index 80789e7ce4..0246202d20 100644
--- a/Sources/DynamicPropertyHelper.php
+++ b/Sources/DynamicPropertyHelper.php
@@ -88,7 +88,7 @@ trait DynamicPropertyHelper
*
* Arbitrary custom data about this object.
*/
- protected array $custom = array();
+ protected array $custom = [];
/****************
* Public methods
@@ -99,11 +99,12 @@ trait DynamicPropertyHelper
*
* @param array $props Array of properties to set.
*/
- public function set(array $props = array()): void
+ public function set(array $props = []): void
{
// The magic method already has robust logic for this job, so use that.
- foreach ($props as $prop => $value)
+ foreach ($props as $prop => $value) {
$this->__set($prop, $value);
+ }
}
/**
@@ -159,48 +160,38 @@ public function __unset(string $prop): void
*/
protected function customPropertySet(mixed $prop, mixed $value): void
{
- if (!empty($this->prop_aliases) && array_key_exists($prop, $this->prop_aliases))
- {
+ if (!empty($this->prop_aliases) && array_key_exists($prop, $this->prop_aliases)) {
// Can't unset a virtual property.
- if (is_null($value))
+ if (is_null($value)) {
return;
+ }
$real_prop = $this->prop_aliases[$prop];
// Callable properties can't be set.
- if (is_callable($real_prop))
+ if (is_callable($real_prop)) {
return;
+ }
- if (strpos($real_prop, '!') === 0)
- {
+ if (strpos($real_prop, '!') === 0) {
$real_prop = ltrim($real_prop, '!');
$value = !$value;
}
- if (strpos($real_prop, '[') !== false)
- {
+ if (strpos($real_prop, '[') !== false) {
$real_prop = explode('[', rtrim($real_prop, ']'));
- if (is_object($this->{$real_prop[0]}))
- {
+ if (is_object($this->{$real_prop[0]})) {
$this->{$real_prop[0]}->{$real_prop[1]} = $value;
- }
- else
- {
+ } else {
$this->{$real_prop[0]}[$real_prop[1]] = $value;
}
- }
- else
- {
+ } else {
$this->{$real_prop} = $value;
}
- }
- elseif (property_exists($this, $prop))
- {
+ } elseif (property_exists($this, $prop)) {
$this->{$prop} = $value;
- }
- else
- {
+ } else {
$this->custom[$prop] = $value;
}
}
@@ -212,45 +203,38 @@ protected function customPropertySet(mixed $prop, mixed $value): void
*/
protected function customPropertyGet(mixed $prop): mixed
{
- if (!empty($this->prop_aliases) && array_key_exists($prop, $this->prop_aliases))
- {
+ if (!empty($this->prop_aliases) && array_key_exists($prop, $this->prop_aliases)) {
$real_prop = $this->prop_aliases[$prop];
// Callable properties are calculated dynamically.
- if (is_callable($real_prop))
+ if (is_callable($real_prop)) {
return call_user_func($real_prop, $this);
+ }
- if (($not = strpos($real_prop, '!') === 0))
+ if (($not = strpos($real_prop, '!') === 0)) {
$real_prop = ltrim($real_prop, '!');
+ }
- if (strpos($real_prop, '[') !== false)
- {
+ if (strpos($real_prop, '[') !== false) {
$real_prop = explode('[', rtrim($real_prop, ']'));
- if (is_object($this->{$real_prop[0]}))
- {
+ if (is_object($this->{$real_prop[0]})) {
$value = $this->{$real_prop[0]}->{$real_prop[1]};
- }
- else
- {
+ } else {
$value = $this->{$real_prop[0]}[$real_prop[1]];
}
- }
- else
- {
+ } else {
$value = $this->{$real_prop};
}
return $not ? !$value : $value;
}
- elseif (property_exists($this, $prop))
- {
+
+ if (property_exists($this, $prop)) {
return $this->{$prop} ?? null;
}
- else
- {
- return $this->custom[$prop] ?? null;
- }
+
+ return $this->custom[$prop] ?? null;
}
/**
@@ -260,40 +244,32 @@ protected function customPropertyGet(mixed $prop): mixed
*/
protected function customPropertyIsset(mixed $prop): bool
{
- if (!empty($this->prop_aliases) && array_key_exists($prop, $this->prop_aliases))
- {
+ if (!empty($this->prop_aliases) && array_key_exists($prop, $this->prop_aliases)) {
$real_prop = ltrim($this->prop_aliases[$prop], '!');
// A callable property is set if it returns a non-null value.
- if (is_callable($real_prop))
+ if (is_callable($real_prop)) {
return call_user_func($real_prop, $this) !== null;
+ }
- if (strpos($real_prop, '[') !== false)
- {
+ if (strpos($real_prop, '[') !== false) {
$real_prop = explode('[', rtrim($real_prop, ']'));
- if (is_object($this->{$real_prop[0]}))
- {
+ if (is_object($this->{$real_prop[0]})) {
return isset($this->{$real_prop[0]}->{$real_prop[1]});
}
- else
- {
- return isset($this->{$real_prop[0]}[$real_prop[1]]);
- }
- }
- else
- {
- return isset($this->{$real_prop});
+
+ return isset($this->{$real_prop[0]}[$real_prop[1]]);
}
+
+ return isset($this->{$real_prop});
}
- elseif (property_exists($this, $prop))
- {
+
+ if (property_exists($this, $prop)) {
return isset($this->{$prop});
}
- else
- {
- return isset($this->custom[$prop]);
- }
+
+ return isset($this->custom[$prop]);
}
/**
@@ -303,17 +279,14 @@ protected function customPropertyIsset(mixed $prop): bool
*/
protected function customPropertyUnset(mixed $prop): void
{
- if (!empty($this->prop_aliases) && array_key_exists($prop, $this->prop_aliases))
- {
+ if (!empty($this->prop_aliases) && array_key_exists($prop, $this->prop_aliases)) {
// Can't unset a virtual property.
return;
}
- elseif (property_exists($this, $prop))
- {
+
+ if (property_exists($this, $prop)) {
unset($this->{$prop});
- }
- else
- {
+ } else {
unset($this->custom[$prop]);
}
}
diff --git a/Sources/Editor.php b/Sources/Editor.php
index 576f6b7518..c79597ac95 100644
--- a/Sources/Editor.php
+++ b/Sources/Editor.php
@@ -21,25 +21,27 @@
*/
class Editor implements \ArrayAccess
{
- use BackwardCompatibility, ArrayAccessHelper;
+ use BackwardCompatibility;
+ use ArrayAccessHelper;
/**
* @var array
*
* BackwardCompatibility settings for this class.
*/
- private static $backcompat = array(
- 'func_names' => array(
+ private static $backcompat = [
+ 'func_names' => [
'load' => 'create_control_richedit',
- ),
- );
+ 'getMessageIcons' => 'getMessageIcons',
+ ],
+ ];
/*****************
* Class constants
*****************/
- const PREVIEW_HTML = 1;
- const PREVIEW_XML = 2;
+ public const PREVIEW_HTML = 1;
+ public const PREVIEW_XML = 2;
/*******************
* Public properties
@@ -143,7 +145,7 @@ class Editor implements \ArrayAccess
*
* Options to pass to SCEditor.
*/
- public array $sce_options = array();
+ public array $sce_options = [];
/**************************
* Public static properties
@@ -154,28 +156,28 @@ class Editor implements \ArrayAccess
*
* All loaded instances of this class.
*/
- public static array $loaded = array();
+ public static array $loaded = [];
/**
* @var array
*
*
*/
- public static array $bbc_tags = array();
+ public static array $bbc_tags = [];
/**
* @var array
*
*
*/
- public static array $disabled_tags = array();
+ public static array $disabled_tags = [];
/**
* @var array
*
*
*/
- public static array $bbc_toolbar = array();
+ public static array $bbc_toolbar = [];
/**
* @var string
@@ -189,10 +191,10 @@ class Editor implements \ArrayAccess
*
*
*/
- public static array $smileys_toolbar = array(
- 'postform' => array(),
- 'popup' => array(),
- );
+ public static array $smileys_toolbar = [
+ 'postform' => [],
+ 'popup' => [],
+ ];
/****************************
* Internal static properties
@@ -203,9 +205,9 @@ class Editor implements \ArrayAccess
*
* Alternate names for some object properties.
*/
- protected array $prop_aliases = array(
+ protected array $prop_aliases = [
'rich_value' => 'value',
- );
+ ];
/****************
* Public methods
@@ -224,13 +226,13 @@ public function __construct(array $options)
// Every control must have a ID!
$this->id = (string) ($options['id'] ?? 'message');
- $this->value = strtr((string) ($options['value'] ?? ''), array(
+ $this->value = strtr((string) ($options['value'] ?? ''), [
// Tabs are not shown in SCEditor; replace with spaces.
"\t" => ' ',
// The [#] item code for creating list items causes issues with
// SCEditor, but [+] is a safe equivalent.
'[#]' => '[+]',
- ));
+ ]);
$this->disable_smiley_box = !empty($options['disable_smiley_box']);
$this->columns = (int) ($options['columns'] ?? 60);
@@ -239,7 +241,7 @@ public function __construct(array $options)
$this->height = (string) ($options['height'] ?? '175px');
$this->form = (string) ($options['form'] ?? 'postmodify');
$this->preview_type = (int) ($options['preview_type'] ?? self::PREVIEW_HTML);
- $this->labels = (array) ($options['labels'] ?? array());
+ $this->labels = (array) ($options['labels'] ?? []);
$this->required = !empty($options['required']);
$this->locale = !empty(Lang::$txt['lang_dictionary']) && Lang::$txt['lang_dictionary'] != 'en' ? Lang::$txt['lang_dictionary'] : '';
@@ -286,59 +288,56 @@ public static function load(array $options): object
*/
public static function getMessageIcons(int $board_id): array
{
- if (empty(Config::$modSettings['messageIcons_enable']))
- {
+ if (empty(Config::$modSettings['messageIcons_enable'])) {
Lang::load('Post');
- $icons = array(
- array('value' => 'xx', 'name' => Lang::$txt['standard']),
- array('value' => 'thumbup', 'name' => Lang::$txt['thumbs_up']),
- array('value' => 'thumbdown', 'name' => Lang::$txt['thumbs_down']),
- array('value' => 'exclamation', 'name' => Lang::$txt['exclamation_point']),
- array('value' => 'question', 'name' => Lang::$txt['question_mark']),
- array('value' => 'lamp', 'name' => Lang::$txt['lamp']),
- array('value' => 'smiley', 'name' => Lang::$txt['icon_smiley']),
- array('value' => 'angry', 'name' => Lang::$txt['icon_angry']),
- array('value' => 'cheesy', 'name' => Lang::$txt['icon_cheesy']),
- array('value' => 'grin', 'name' => Lang::$txt['icon_grin']),
- array('value' => 'sad', 'name' => Lang::$txt['icon_sad']),
- array('value' => 'wink', 'name' => Lang::$txt['icon_wink']),
- array('value' => 'poll', 'name' => Lang::$txt['icon_poll']),
- );
-
- foreach ($icons as $k => $dummy)
- {
+ $icons = [
+ ['value' => 'xx', 'name' => Lang::$txt['standard']],
+ ['value' => 'thumbup', 'name' => Lang::$txt['thumbs_up']],
+ ['value' => 'thumbdown', 'name' => Lang::$txt['thumbs_down']],
+ ['value' => 'exclamation', 'name' => Lang::$txt['exclamation_point']],
+ ['value' => 'question', 'name' => Lang::$txt['question_mark']],
+ ['value' => 'lamp', 'name' => Lang::$txt['lamp']],
+ ['value' => 'smiley', 'name' => Lang::$txt['icon_smiley']],
+ ['value' => 'angry', 'name' => Lang::$txt['icon_angry']],
+ ['value' => 'cheesy', 'name' => Lang::$txt['icon_cheesy']],
+ ['value' => 'grin', 'name' => Lang::$txt['icon_grin']],
+ ['value' => 'sad', 'name' => Lang::$txt['icon_sad']],
+ ['value' => 'wink', 'name' => Lang::$txt['icon_wink']],
+ ['value' => 'poll', 'name' => Lang::$txt['icon_poll']],
+ ];
+
+ foreach ($icons as $k => $dummy) {
$icons[$k]['url'] = Theme::$current->settings['images_url'] . '/post/' . $dummy['value'] . '.png';
$icons[$k]['is_last'] = false;
}
}
// Otherwise load the icons, and check we give the right image too...
- else
- {
+ else {
$icons = CacheApi::get('posting_icons-' . $board_id, 480);
- if ($icons == null)
- {
- $icons = array();
+ if ($icons == null) {
+ $icons = [];
- $request = Db::$db->query('', '
- SELECT title, filename
+ $request = Db::$db->query(
+ '',
+ 'SELECT title, filename
FROM {db_prefix}message_icons
WHERE id_board IN (0, {int:board_id})
ORDER BY icon_order',
- array(
+ [
'board_id' => $board_id,
- )
+ ],
);
- while ($row = Db::$db->fetch_assoc($request))
- {
- $icons[$row['filename']] = array(
+
+ while ($row = Db::$db->fetch_assoc($request)) {
+ $icons[$row['filename']] = [
'value' => $row['filename'],
'name' => $row['title'],
'url' => Theme::$current->settings[file_exists(Theme::$current->settings['theme_dir'] . '/images/post/' . $row['filename'] . '.png') ? 'images_url' : 'default_images_url'] . '/post/' . $row['filename'] . '.png',
'is_last' => false,
- );
+ ];
}
Db::$db->free_result($request);
@@ -346,7 +345,7 @@ public static function getMessageIcons(int $board_id): array
}
}
- IntegrationHook::call('integrate_load_message_icons', array(&$icons));
+ IntegrationHook::call('integrate_load_message_icons', [&$icons]);
return array_values($icons);
}
@@ -363,8 +362,9 @@ public static function getMessageIcons(int $board_id): array
protected function init(): void
{
// Don't do this twice.
- if (!empty(self::$loaded))
+ if (!empty(self::$loaded)) {
return;
+ }
Lang::load('Post');
Lang::load('Editor');
@@ -373,27 +373,26 @@ protected function init(): void
// Some general stuff.
Theme::$current->settings['smileys_url'] = Config::$modSettings['smileys_url'] . '/' . User::$me->smiley_set;
- if (!empty(Utils::$context['drafts_autosave']))
- {
+ if (!empty(Utils::$context['drafts_autosave'])) {
Utils::$context['drafts_autosave_frequency'] = empty(Config::$modSettings['drafts_autosave_frequency']) ? 60000 : Config::$modSettings['drafts_autosave_frequency'] * 1000;
}
// This really has some WYSIWYG stuff.
- Theme::loadCSSFile('jquery.sceditor.css', array('default_theme' => true, 'validate' => true), 'smf_jquery_sceditor');
+ Theme::loadCSSFile('jquery.sceditor.css', ['default_theme' => true, 'validate' => true], 'smf_jquery_sceditor');
Theme::loadTemplate('GenericControls');
/*
THEME AUTHORS:
- If you want to change or tweak the CSS for the editor,
+ If you want to change or tweak the CSS for the editor,
include a file named 'jquery.sceditor.theme.css' in your theme.
*/
- Theme::loadCSSFile('jquery.sceditor.theme.css', array('force_current' => true, 'validate' => true,), 'smf_jquery_sceditor_theme');
+ Theme::loadCSSFile('jquery.sceditor.theme.css', ['force_current' => true, 'validate' => true], 'smf_jquery_sceditor_theme');
// JS makes the editor go round
- Theme::loadJavaScriptFile('editor.js', array('minimize' => true), 'smf_editor');
- Theme::loadJavaScriptFile('jquery.sceditor.bbcode.min.js', array(), 'smf_sceditor_bbcode');
- Theme::loadJavaScriptFile('jquery.sceditor.smf.js', array('minimize' => true), 'smf_sceditor_smf');
+ Theme::loadJavaScriptFile('editor.js', ['minimize' => true], 'smf_editor');
+ Theme::loadJavaScriptFile('jquery.sceditor.bbcode.min.js', [], 'smf_sceditor_bbcode');
+ Theme::loadJavaScriptFile('jquery.sceditor.smf.js', ['minimize' => true], 'smf_sceditor_smf');
$scExtraLangs = '
$.sceditor.locale["' . Lang::$txt['lang_dictionary'] . '"] = {
@@ -421,13 +420,11 @@ protected function init(): void
Utils::$context['shortcuts_text'] = Lang::$txt['shortcuts' . (!empty(Utils::$context['drafts_save']) ? '_drafts' : '') . (stripos($_SERVER['HTTP_USER_AGENT'], 'Macintosh') !== false ? '_mac' : (BrowserDetector::isBrowser('is_firefox') ? '_firefox' : ''))];
- if (Utils::$context['show_spellchecking'])
- {
- Theme::loadJavaScriptFile('spellcheck.js', array('minimize' => true), 'smf_spellcheck');
+ if (Utils::$context['show_spellchecking']) {
+ Theme::loadJavaScriptFile('spellcheck.js', ['minimize' => true], 'smf_spellcheck');
// Some hidden information is needed in order to make the spell checking work.
- if (!isset($_REQUEST['xml']))
- {
+ if (!isset($_REQUEST['xml'])) {
Utils::$context['insert_after_template'] .= '
|
';
-
}
/**
@@ -1391,8 +1516,9 @@ public static function login($redirect_to = '', $output_method = 'echo')
*/
public static function topPoll($output_method = 'echo')
{
- if (!self::$setup_done)
+ if (!self::$setup_done) {
new self();
+ }
// Just use recentPoll, no need to duplicate code...
return self::recentPoll(true, $output_method);
@@ -1409,54 +1535,53 @@ public static function topPoll($output_method = 'echo')
*/
public static function recentPoll($topPollInstead = false, $output_method = 'echo')
{
- if (!self::$setup_done)
+ if (!self::$setup_done) {
new self();
+ }
$poll = Poll::load(0, ($topPollInstead ? Poll::LOAD_BY_VOTES : Poll::LOAD_BY_RECENT) | Poll::CHECK_ACCESS | Poll::CHECK_IGNORE | Poll::CHECK_LOCKED | Poll::CHECK_EXPIRY);
- if (empty($poll))
- return array();
+ if (empty($poll)) {
+ return [];
+ }
$return = $poll->format();
// If mods want to do something with this poll, let them do that now.
- IntegrationHook::call('integrate_ssi_recentPoll', array(&$return, $topPollInstead));
+ IntegrationHook::call('integrate_ssi_recentPoll', [&$return, $topPollInstead]);
- if ($output_method != 'echo')
+ if ($output_method != 'echo') {
return $return;
+ }
- if ($return['allow_vote'])
- {
+ if ($return['allow_vote']) {
echo '