Passed
Pull Request — master (#219)
by Simon
09:13 queued 05:15
created
smarty-plugins/function.defaultsort.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -19,24 +19,24 @@
 block discarded – undo
19 19
  */
20 20
 function smarty_function_defaultsort($params, Template $template)
21 21
 {
22
-    if (empty($params['id'])) {
23
-        return "";
24
-    }
22
+	if (empty($params['id'])) {
23
+		return "";
24
+	}
25 25
 
26
-    $attr = 'data-sortname="' . htmlspecialchars($params['id'], ENT_QUOTES) . '"';
26
+	$attr = 'data-sortname="' . htmlspecialchars($params['id'], ENT_QUOTES) . '"';
27 27
 
28
-    if (empty($params['req'])) {
29
-        return $attr;
30
-    }
28
+	if (empty($params['req'])) {
29
+		return $attr;
30
+	}
31 31
 
32
-    if ($params['dir'] !== 'asc' && $params['dir'] !== 'desc') {
33
-        $params['dir'] = 'asc';
34
-    }
32
+	if ($params['dir'] !== 'asc' && $params['dir'] !== 'desc') {
33
+		$params['dir'] = 'asc';
34
+	}
35 35
 
36
-    $sort = '';
37
-    if ($params['req'] === $params['id']) {
38
-        $sort = ' data-defaultsort="' . htmlspecialchars($params['dir'], ENT_QUOTES) . '"';
39
-    }
36
+	$sort = '';
37
+	if ($params['req'] === $params['id']) {
38
+		$sort = ' data-defaultsort="' . htmlspecialchars($params['dir'], ENT_QUOTES) . '"';
39
+	}
40 40
 
41
-    return $attr . $sort;
41
+	return $attr . $sort;
42 42
 }
Please login to merge, or discard this patch.
includes/Fragments/TemplateOutput.php 1 patch
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -18,129 +18,129 @@
 block discarded – undo
18 18
 
19 19
 trait TemplateOutput
20 20
 {
21
-    /** @var Smarty */
22
-    private $smarty;
23
-
24
-    /**
25
-     * @param string $pluginsDir
26
-     *
27
-     * @return void
28
-     * @throws Exception
29
-     */
30
-    private function loadPlugins(string $pluginsDir): void
31
-    {
32
-        /** @var DirectoryIterator $file */
33
-        foreach (new DirectoryIterator($pluginsDir) as $file) {
34
-            if ($file->isDot()) {
35
-                continue;
36
-            }
37
-
38
-            if ($file->getExtension() != 'php') {
39
-                continue;
40
-            }
41
-
42
-            require_once $file->getPathname();
43
-
44
-            list($type, $name) = explode('.', $file->getBasename('.php'), 2);
45
-
46
-            switch ($type) {
47
-                case 'modifier':
48
-                    $this->smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, $name, 'smarty_modifier_' . $name);
49
-                    break;
50
-                case 'function':
51
-                    $this->smarty->registerPlugin(Smarty::PLUGIN_FUNCTION, $name, 'smarty_function_' . $name);
52
-                    break;
53
-            }
54
-        }
55
-    }
56
-
57
-    /**
58
-     * @return SiteConfiguration
59
-     */
60
-    protected abstract function getSiteConfiguration();
61
-
62
-    /**
63
-     * Assigns a Smarty variable
64
-     *
65
-     * @param  array|string $name  the template variable name(s)
66
-     * @param  mixed        $value the value to assign
67
-     */
68
-    final protected function assign($name, $value)
69
-    {
70
-        $this->smarty->assign($name, $value);
71
-    }
72
-
73
-    /**
74
-     * Sets up the variables used by the main Smarty base template.
75
-     *
76
-     * This list is getting kinda long.
77
-     * @throws Exception
78
-     */
79
-    final protected function setUpSmarty()
80
-    {
81
-        $this->smarty = new Smarty();
82
-        $pluginsDir = $this->getSiteConfiguration()->getFilePath() . '/smarty-plugins';
83
-
84
-        // Dynamically load all plugins in the plugins directory
85
-        $this->loadPlugins($pluginsDir);
86
-
87
-        $this->assign('currentUser', User::getCommunity());
88
-        $this->assign('skin', 'auto');
89
-        $this->assign('currentDomain', null);
90
-        $this->assign('loggedIn', false);
91
-        $this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
92
-        $this->assign('resourceCacheEpoch', $this->getSiteConfiguration()->getResourceCacheEpoch());
93
-
94
-        $this->assign('siteNoticeText', '');
95
-        $this->assign('siteNoticeVersion', 0);
96
-        $this->assign('siteNoticeState', 'd-none');
97
-        $this->assign('toolversion', Environment::getToolVersion());
98
-
99
-        // default these
100
-        $this->assign('onlineusers', array());
101
-        $this->assign('typeAheadBlock', '');
102
-        $this->assign('extraJs', array());
103
-
104
-        // nav menu access control
105
-        $this->assign('nav__canRequests', false);
106
-        $this->assign('nav__canLogs', false);
107
-        $this->assign('nav__canUsers', false);
108
-        $this->assign('nav__canSearch', false);
109
-        $this->assign('nav__canStats', false);
110
-        $this->assign('nav__canBan', false);
111
-        $this->assign('nav__canEmailMgmt', false);
112
-        $this->assign('nav__canWelcomeMgmt', false);
113
-        $this->assign('nav__canSiteNoticeMgmt', false);
114
-        $this->assign('nav__canUserMgmt', false);
115
-        $this->assign('nav__canViewRequest', false);
116
-        $this->assign('nav__canJobQueue', false);
117
-        $this->assign('nav__canFlaggedComments', false);
118
-        $this->assign('nav__canDomainMgmt', false);
119
-        $this->assign('nav__canQueueMgmt', false);
120
-        $this->assign('nav__canFormMgmt', false);
121
-        $this->assign('nav__canErrorLog', false);
122
-
123
-        // Navigation badges for concern areas.
124
-        $this->assign("nav__numAdmin", 0);
125
-        $this->assign("nav__numFlaggedComments", 0);
126
-        $this->assign("nav__numJobQueueFailed", 0);
127
-
128
-        // debug helpers
129
-        $this->assign('showDebugCssBreakpoints', $this->getSiteConfiguration()->getDebuggingCssBreakpointsEnabled());
130
-
131
-        $this->assign('page', $this);
132
-    }
133
-
134
-    /**
135
-     * Fetches a rendered Smarty template
136
-     *
137
-     * @param $template string Template file path, relative to /templates/
138
-     *
139
-     * @return string Templated HTML
140
-     * @throws Exception
141
-     */
142
-    final protected function fetchTemplate($template)
143
-    {
144
-        return $this->smarty->fetch($template);
145
-    }
21
+	/** @var Smarty */
22
+	private $smarty;
23
+
24
+	/**
25
+	 * @param string $pluginsDir
26
+	 *
27
+	 * @return void
28
+	 * @throws Exception
29
+	 */
30
+	private function loadPlugins(string $pluginsDir): void
31
+	{
32
+		/** @var DirectoryIterator $file */
33
+		foreach (new DirectoryIterator($pluginsDir) as $file) {
34
+			if ($file->isDot()) {
35
+				continue;
36
+			}
37
+
38
+			if ($file->getExtension() != 'php') {
39
+				continue;
40
+			}
41
+
42
+			require_once $file->getPathname();
43
+
44
+			list($type, $name) = explode('.', $file->getBasename('.php'), 2);
45
+
46
+			switch ($type) {
47
+				case 'modifier':
48
+					$this->smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, $name, 'smarty_modifier_' . $name);
49
+					break;
50
+				case 'function':
51
+					$this->smarty->registerPlugin(Smarty::PLUGIN_FUNCTION, $name, 'smarty_function_' . $name);
52
+					break;
53
+			}
54
+		}
55
+	}
56
+
57
+	/**
58
+	 * @return SiteConfiguration
59
+	 */
60
+	protected abstract function getSiteConfiguration();
61
+
62
+	/**
63
+	 * Assigns a Smarty variable
64
+	 *
65
+	 * @param  array|string $name  the template variable name(s)
66
+	 * @param  mixed        $value the value to assign
67
+	 */
68
+	final protected function assign($name, $value)
69
+	{
70
+		$this->smarty->assign($name, $value);
71
+	}
72
+
73
+	/**
74
+	 * Sets up the variables used by the main Smarty base template.
75
+	 *
76
+	 * This list is getting kinda long.
77
+	 * @throws Exception
78
+	 */
79
+	final protected function setUpSmarty()
80
+	{
81
+		$this->smarty = new Smarty();
82
+		$pluginsDir = $this->getSiteConfiguration()->getFilePath() . '/smarty-plugins';
83
+
84
+		// Dynamically load all plugins in the plugins directory
85
+		$this->loadPlugins($pluginsDir);
86
+
87
+		$this->assign('currentUser', User::getCommunity());
88
+		$this->assign('skin', 'auto');
89
+		$this->assign('currentDomain', null);
90
+		$this->assign('loggedIn', false);
91
+		$this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
92
+		$this->assign('resourceCacheEpoch', $this->getSiteConfiguration()->getResourceCacheEpoch());
93
+
94
+		$this->assign('siteNoticeText', '');
95
+		$this->assign('siteNoticeVersion', 0);
96
+		$this->assign('siteNoticeState', 'd-none');
97
+		$this->assign('toolversion', Environment::getToolVersion());
98
+
99
+		// default these
100
+		$this->assign('onlineusers', array());
101
+		$this->assign('typeAheadBlock', '');
102
+		$this->assign('extraJs', array());
103
+
104
+		// nav menu access control
105
+		$this->assign('nav__canRequests', false);
106
+		$this->assign('nav__canLogs', false);
107
+		$this->assign('nav__canUsers', false);
108
+		$this->assign('nav__canSearch', false);
109
+		$this->assign('nav__canStats', false);
110
+		$this->assign('nav__canBan', false);
111
+		$this->assign('nav__canEmailMgmt', false);
112
+		$this->assign('nav__canWelcomeMgmt', false);
113
+		$this->assign('nav__canSiteNoticeMgmt', false);
114
+		$this->assign('nav__canUserMgmt', false);
115
+		$this->assign('nav__canViewRequest', false);
116
+		$this->assign('nav__canJobQueue', false);
117
+		$this->assign('nav__canFlaggedComments', false);
118
+		$this->assign('nav__canDomainMgmt', false);
119
+		$this->assign('nav__canQueueMgmt', false);
120
+		$this->assign('nav__canFormMgmt', false);
121
+		$this->assign('nav__canErrorLog', false);
122
+
123
+		// Navigation badges for concern areas.
124
+		$this->assign("nav__numAdmin", 0);
125
+		$this->assign("nav__numFlaggedComments", 0);
126
+		$this->assign("nav__numJobQueueFailed", 0);
127
+
128
+		// debug helpers
129
+		$this->assign('showDebugCssBreakpoints', $this->getSiteConfiguration()->getDebuggingCssBreakpointsEnabled());
130
+
131
+		$this->assign('page', $this);
132
+	}
133
+
134
+	/**
135
+	 * Fetches a rendered Smarty template
136
+	 *
137
+	 * @param $template string Template file path, relative to /templates/
138
+	 *
139
+	 * @return string Templated HTML
140
+	 * @throws Exception
141
+	 */
142
+	final protected function fetchTemplate($template)
143
+	{
144
+		return $this->smarty->fetch($template);
145
+	}
146 146
 }
Please login to merge, or discard this patch.
includes/Security/RoleConfigurationBase.php 1 patch
Indentation   +131 added lines, -131 removed lines patch added patch discarded remove patch
@@ -10,135 +10,135 @@
 block discarded – undo
10 10
 
11 11
 abstract class RoleConfigurationBase
12 12
 {
13
-    const ACCESS_ALLOW = 1;
14
-    const ACCESS_DENY = -1;
15
-    const ACCESS_DEFAULT = 0;
16
-    const MAIN = 'main';
17
-    const ALL = '*';
18
-
19
-    protected array $roleConfig;
20
-    protected array $identificationExempt;
21
-
22
-    protected function __construct(array $roleConfig, array $identificationExempt)
23
-    {
24
-        $this->roleConfig = $roleConfig;
25
-        $this->identificationExempt = $identificationExempt;
26
-    }
27
-
28
-    /**
29
-     * Takes an array of role names and flattens the values to a single
30
-     * resultant role configuration.
31
-     *
32
-     * @param string[] $activeRoles
33
-     * @category Security-Critical
34
-     */
35
-    public function getResultantRole(array $activeRoles): array
36
-    {
37
-        $result = array();
38
-
39
-        $roleConfig = $this->getApplicableRoles($activeRoles);
40
-
41
-        // Iterate over every page in every role
42
-        foreach ($roleConfig as $role) {
43
-            foreach ($role as $page => $pageRights) {
44
-                // Create holder in result for this page
45
-                if (!isset($result[$page])) {
46
-                    $result[$page] = array();
47
-                }
48
-
49
-                foreach ($pageRights as $action => $permission) {
50
-                    // Deny takes precedence, so if it's set, don't change it.
51
-                    if (isset($result[$page][$action])) {
52
-                        if ($result[$page][$action] === RoleConfigurationBase::ACCESS_DENY) {
53
-                            continue;
54
-                        }
55
-                    }
56
-
57
-                    if ($permission === RoleConfigurationBase::ACCESS_DEFAULT) {
58
-                        // Configured to do precisely nothing.
59
-                        continue;
60
-                    }
61
-
62
-                    $result[$page][$action] = $permission;
63
-                }
64
-            }
65
-        }
66
-
67
-        return $result;
68
-    }
69
-
70
-    /**
71
-     * Returns a set of all roles which are available to be set.
72
-     *
73
-     * Hidden roles and implicit roles are excluded.
74
-     */
75
-    public function getAvailableRoles(): array
76
-    {
77
-        // remove the implicit roles
78
-        $possible = array_diff(array_keys($this->roleConfig), array('public', 'loggedIn', 'user'));
79
-
80
-        $actual = array();
81
-
82
-        foreach ($possible as $role) {
83
-            if (!isset($this->roleConfig[$role]['_hidden'])) {
84
-                $actual[$role] = array(
85
-                    'description' => $this->roleConfig[$role]['_description'],
86
-                    'editableBy'  => $this->roleConfig[$role]['_editableBy'],
87
-                    'globalOnly'  => isset($this->roleConfig[$role]['_globalOnly']) && $this->roleConfig[$role]['_globalOnly'],
88
-                );
89
-            }
90
-        }
91
-
92
-        return $actual;
93
-    }
94
-
95
-    /**
96
-     * Returns a boolean for whether the provided role requires identification
97
-     * before being used by a user.
98
-     *
99
-     * @category Security-Critical
100
-     */
101
-    public function roleNeedsIdentification(string $role): bool
102
-    {
103
-        if (in_array($role, $this->identificationExempt)) {
104
-            return false;
105
-        }
106
-
107
-        return true;
108
-    }
109
-
110
-    /**
111
-     * Takes an array of role names, and returns all the relevant roles for that
112
-     * set, including any child roles found recursively.
113
-     *
114
-     * @param array $roles The names of roles to start searching with
115
-     */
116
-    private function getApplicableRoles(array $roles): array
117
-    {
118
-        $available = array();
119
-
120
-        foreach ($roles as $role) {
121
-            if (!isset($this->roleConfig[$role])) {
122
-                // wat
123
-                continue;
124
-            }
125
-
126
-            $available[$role] = $this->roleConfig[$role];
127
-
128
-            if (isset($available[$role]['_childRoles'])) {
129
-                $childRoles = $this->getApplicableRoles($available[$role]['_childRoles']);
130
-                $available = array_merge($available, $childRoles);
131
-
132
-                unset($available[$role]['_childRoles']);
133
-            }
134
-
135
-            foreach (array('_hidden', '_editableBy', '_description', '_globalOnly') as $item) {
136
-                if (isset($available[$role][$item])) {
137
-                    unset($available[$role][$item]);
138
-                }
139
-            }
140
-        }
141
-
142
-        return $available;
143
-    }
13
+	const ACCESS_ALLOW = 1;
14
+	const ACCESS_DENY = -1;
15
+	const ACCESS_DEFAULT = 0;
16
+	const MAIN = 'main';
17
+	const ALL = '*';
18
+
19
+	protected array $roleConfig;
20
+	protected array $identificationExempt;
21
+
22
+	protected function __construct(array $roleConfig, array $identificationExempt)
23
+	{
24
+		$this->roleConfig = $roleConfig;
25
+		$this->identificationExempt = $identificationExempt;
26
+	}
27
+
28
+	/**
29
+	 * Takes an array of role names and flattens the values to a single
30
+	 * resultant role configuration.
31
+	 *
32
+	 * @param string[] $activeRoles
33
+	 * @category Security-Critical
34
+	 */
35
+	public function getResultantRole(array $activeRoles): array
36
+	{
37
+		$result = array();
38
+
39
+		$roleConfig = $this->getApplicableRoles($activeRoles);
40
+
41
+		// Iterate over every page in every role
42
+		foreach ($roleConfig as $role) {
43
+			foreach ($role as $page => $pageRights) {
44
+				// Create holder in result for this page
45
+				if (!isset($result[$page])) {
46
+					$result[$page] = array();
47
+				}
48
+
49
+				foreach ($pageRights as $action => $permission) {
50
+					// Deny takes precedence, so if it's set, don't change it.
51
+					if (isset($result[$page][$action])) {
52
+						if ($result[$page][$action] === RoleConfigurationBase::ACCESS_DENY) {
53
+							continue;
54
+						}
55
+					}
56
+
57
+					if ($permission === RoleConfigurationBase::ACCESS_DEFAULT) {
58
+						// Configured to do precisely nothing.
59
+						continue;
60
+					}
61
+
62
+					$result[$page][$action] = $permission;
63
+				}
64
+			}
65
+		}
66
+
67
+		return $result;
68
+	}
69
+
70
+	/**
71
+	 * Returns a set of all roles which are available to be set.
72
+	 *
73
+	 * Hidden roles and implicit roles are excluded.
74
+	 */
75
+	public function getAvailableRoles(): array
76
+	{
77
+		// remove the implicit roles
78
+		$possible = array_diff(array_keys($this->roleConfig), array('public', 'loggedIn', 'user'));
79
+
80
+		$actual = array();
81
+
82
+		foreach ($possible as $role) {
83
+			if (!isset($this->roleConfig[$role]['_hidden'])) {
84
+				$actual[$role] = array(
85
+					'description' => $this->roleConfig[$role]['_description'],
86
+					'editableBy'  => $this->roleConfig[$role]['_editableBy'],
87
+					'globalOnly'  => isset($this->roleConfig[$role]['_globalOnly']) && $this->roleConfig[$role]['_globalOnly'],
88
+				);
89
+			}
90
+		}
91
+
92
+		return $actual;
93
+	}
94
+
95
+	/**
96
+	 * Returns a boolean for whether the provided role requires identification
97
+	 * before being used by a user.
98
+	 *
99
+	 * @category Security-Critical
100
+	 */
101
+	public function roleNeedsIdentification(string $role): bool
102
+	{
103
+		if (in_array($role, $this->identificationExempt)) {
104
+			return false;
105
+		}
106
+
107
+		return true;
108
+	}
109
+
110
+	/**
111
+	 * Takes an array of role names, and returns all the relevant roles for that
112
+	 * set, including any child roles found recursively.
113
+	 *
114
+	 * @param array $roles The names of roles to start searching with
115
+	 */
116
+	private function getApplicableRoles(array $roles): array
117
+	{
118
+		$available = array();
119
+
120
+		foreach ($roles as $role) {
121
+			if (!isset($this->roleConfig[$role])) {
122
+				// wat
123
+				continue;
124
+			}
125
+
126
+			$available[$role] = $this->roleConfig[$role];
127
+
128
+			if (isset($available[$role]['_childRoles'])) {
129
+				$childRoles = $this->getApplicableRoles($available[$role]['_childRoles']);
130
+				$available = array_merge($available, $childRoles);
131
+
132
+				unset($available[$role]['_childRoles']);
133
+			}
134
+
135
+			foreach (array('_hidden', '_editableBy', '_description', '_globalOnly') as $item) {
136
+				if (isset($available[$role][$item])) {
137
+					unset($available[$role][$item]);
138
+				}
139
+			}
140
+		}
141
+
142
+		return $available;
143
+	}
144 144
 }
145 145
\ No newline at end of file
Please login to merge, or discard this patch.
includes/ExceptionHandler.php 1 patch
Indentation   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -14,22 +14,22 @@  discard block
 block discarded – undo
14 14
 
15 15
 class ExceptionHandler
16 16
 {
17
-    /**
18
-     * Global exception handler
19
-     *
20
-     * Smarty would be nice to use, but it COULD BE smarty that throws the errors.
21
-     * Let's build something ourselves, and hope it works.
22
-     *
23
-     * @param $exception
24
-     *
25
-     * @category Security-Critical - has the potential to leak data when exception is thrown.
26
-     */
27
-    public static function exceptionHandler(Throwable $exception)
28
-    {
29
-        /** @global $siteConfiguration SiteConfiguration */
30
-        global $siteConfiguration;
31
-
32
-        $errorDocument = <<<HTML
17
+	/**
18
+	 * Global exception handler
19
+	 *
20
+	 * Smarty would be nice to use, but it COULD BE smarty that throws the errors.
21
+	 * Let's build something ourselves, and hope it works.
22
+	 *
23
+	 * @param $exception
24
+	 *
25
+	 * @category Security-Critical - has the potential to leak data when exception is thrown.
26
+	 */
27
+	public static function exceptionHandler(Throwable $exception)
28
+	{
29
+		/** @global $siteConfiguration SiteConfiguration */
30
+		global $siteConfiguration;
31
+
32
+		$errorDocument = <<<HTML
33 33
 <!DOCTYPE html>
34 34
 <html lang="en"><head>
35 35
 <meta charset="utf-8">
@@ -49,106 +49,106 @@  discard block
 block discarded – undo
49 49
 </div></body></html>
50 50
 HTML;
51 51
 
52
-        list($errorData, $errorId) = self::logExceptionToDisk($exception, $siteConfiguration, true);
53
-
54
-        error_log('Unhandled ' . get_class($exception) . ': ' . $exception->getMessage());
55
-
56
-        // clear and discard any content that's been saved to the output buffer
57
-        if (ob_get_level() > 0) {
58
-            ob_end_clean();
59
-        }
60
-
61
-        // push error ID into the document.
62
-        $message = str_replace('$1$', $errorId, $errorDocument);
63
-
64
-        if ($siteConfiguration->getDebuggingTraceEnabled()) {
65
-            ob_start();
66
-            var_dump($errorData);
67
-            $textErrorData = ob_get_contents();
68
-            ob_end_clean();
69
-
70
-            $message = str_replace('$2$', $textErrorData, $message);
71
-        }
72
-        else {
73
-            $message = str_replace('$2$', "", $message);
74
-        }
75
-
76
-        // While we *shouldn't* have sent headers by now due to the output buffering, PHPUnit does weird things.
77
-        // This is "only" needed for the tests, but it's a good idea to wrap this anyway.
78
-        if (!headers_sent()) {
79
-            header('HTTP/1.1 500 Internal Server Error');
80
-        }
81
-
82
-        // output the document
83
-        print $message;
84
-    }
85
-
86
-    /**
87
-     * @param int    $errorSeverity The severity level of the exception.
88
-     * @param string $errorMessage  The Exception message to throw.
89
-     * @param string $errorFile     The filename where the exception is thrown.
90
-     * @param int    $errorLine     The line number where the exception is thrown.
91
-     *
92
-     * @throws ErrorException
93
-     */
94
-    public static function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine)
95
-    {
96
-        // call into the main exception handler above
97
-        throw new ErrorException($errorMessage, 0, $errorSeverity, $errorFile, $errorLine);
98
-    }
99
-
100
-    /**
101
-     * @param Throwable $exception
102
-     *
103
-     * @return null|array
104
-     */
105
-    public static function getExceptionData($exception)
106
-    {
107
-        if ($exception == null) {
108
-            return null;
109
-        }
110
-
111
-        $array = array(
112
-            'exception' => get_class($exception),
113
-            'message'   => $exception->getMessage(),
114
-            'stack'     => $exception->getTraceAsString(),
115
-        );
116
-
117
-        $array['previous'] = self::getExceptionData($exception->getPrevious());
118
-
119
-        return $array;
120
-    }
121
-
122
-    public static function logExceptionToDisk(
123
-        Throwable $exception,
124
-        SiteConfiguration $siteConfiguration,
125
-        bool $fromGlobalHandler = false
126
-    ): array {
127
-        $errorData = self::getExceptionData($exception);
128
-        $errorData['server'] = $_SERVER;
129
-        $errorData['get'] = $_GET;
130
-        $errorData['post'] = $_POST;
131
-
132
-        $redactions = ['password', 'newpassword', 'newpasswordconfirm', 'otp'];
133
-        foreach ($redactions as $redaction) {
134
-            if (isset($errorData['post'][$redaction])) {
135
-                $errorData['post'][$redaction] = '<redacted>';
136
-            }
137
-        }
138
-
139
-        if ($fromGlobalHandler) {
140
-            $errorData['globalHandler'] = true;
141
-        }
142
-        else {
143
-            $errorData['globalHandler'] = false;
144
-        }
145
-
146
-        $state = serialize($errorData);
147
-        $errorId = sha1($state);
148
-
149
-        // Save the error for later analysis
150
-        file_put_contents($siteConfiguration->getErrorLog() . '/' . $errorId . '.log', $state);
151
-
152
-        return array($errorData, $errorId);
153
-    }
52
+		list($errorData, $errorId) = self::logExceptionToDisk($exception, $siteConfiguration, true);
53
+
54
+		error_log('Unhandled ' . get_class($exception) . ': ' . $exception->getMessage());
55
+
56
+		// clear and discard any content that's been saved to the output buffer
57
+		if (ob_get_level() > 0) {
58
+			ob_end_clean();
59
+		}
60
+
61
+		// push error ID into the document.
62
+		$message = str_replace('$1$', $errorId, $errorDocument);
63
+
64
+		if ($siteConfiguration->getDebuggingTraceEnabled()) {
65
+			ob_start();
66
+			var_dump($errorData);
67
+			$textErrorData = ob_get_contents();
68
+			ob_end_clean();
69
+
70
+			$message = str_replace('$2$', $textErrorData, $message);
71
+		}
72
+		else {
73
+			$message = str_replace('$2$', "", $message);
74
+		}
75
+
76
+		// While we *shouldn't* have sent headers by now due to the output buffering, PHPUnit does weird things.
77
+		// This is "only" needed for the tests, but it's a good idea to wrap this anyway.
78
+		if (!headers_sent()) {
79
+			header('HTTP/1.1 500 Internal Server Error');
80
+		}
81
+
82
+		// output the document
83
+		print $message;
84
+	}
85
+
86
+	/**
87
+	 * @param int    $errorSeverity The severity level of the exception.
88
+	 * @param string $errorMessage  The Exception message to throw.
89
+	 * @param string $errorFile     The filename where the exception is thrown.
90
+	 * @param int    $errorLine     The line number where the exception is thrown.
91
+	 *
92
+	 * @throws ErrorException
93
+	 */
94
+	public static function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine)
95
+	{
96
+		// call into the main exception handler above
97
+		throw new ErrorException($errorMessage, 0, $errorSeverity, $errorFile, $errorLine);
98
+	}
99
+
100
+	/**
101
+	 * @param Throwable $exception
102
+	 *
103
+	 * @return null|array
104
+	 */
105
+	public static function getExceptionData($exception)
106
+	{
107
+		if ($exception == null) {
108
+			return null;
109
+		}
110
+
111
+		$array = array(
112
+			'exception' => get_class($exception),
113
+			'message'   => $exception->getMessage(),
114
+			'stack'     => $exception->getTraceAsString(),
115
+		);
116
+
117
+		$array['previous'] = self::getExceptionData($exception->getPrevious());
118
+
119
+		return $array;
120
+	}
121
+
122
+	public static function logExceptionToDisk(
123
+		Throwable $exception,
124
+		SiteConfiguration $siteConfiguration,
125
+		bool $fromGlobalHandler = false
126
+	): array {
127
+		$errorData = self::getExceptionData($exception);
128
+		$errorData['server'] = $_SERVER;
129
+		$errorData['get'] = $_GET;
130
+		$errorData['post'] = $_POST;
131
+
132
+		$redactions = ['password', 'newpassword', 'newpasswordconfirm', 'otp'];
133
+		foreach ($redactions as $redaction) {
134
+			if (isset($errorData['post'][$redaction])) {
135
+				$errorData['post'][$redaction] = '<redacted>';
136
+			}
137
+		}
138
+
139
+		if ($fromGlobalHandler) {
140
+			$errorData['globalHandler'] = true;
141
+		}
142
+		else {
143
+			$errorData['globalHandler'] = false;
144
+		}
145
+
146
+		$state = serialize($errorData);
147
+		$errorId = sha1($state);
148
+
149
+		// Save the error for later analysis
150
+		file_put_contents($siteConfiguration->getErrorLog() . '/' . $errorId . '.log', $state);
151
+
152
+		return array($errorData, $errorId);
153
+	}
154 154
 }
Please login to merge, or discard this patch.
includes/Pages/PageBan.php 1 patch
Indentation   +659 added lines, -659 removed lines patch added patch discarded remove patch
@@ -27,665 +27,665 @@
 block discarded – undo
27 27
 
28 28
 class PageBan extends InternalPageBase
29 29
 {
30
-    /**
31
-     * Main function for this page, when no specific actions are called.
32
-     */
33
-    protected function main(): void
34
-    {
35
-        $this->assignCSRFToken();
36
-        $this->setHtmlTitle('Bans');
37
-
38
-        $database = $this->getDatabase();
39
-        $currentDomain = Domain::getCurrent($database);
40
-        $bans = Ban::getActiveBans($database, $currentDomain->getId());
41
-
42
-        $this->setupBanList($bans);
43
-
44
-        $this->assign('isFiltered', false);
45
-        $this->assign('currentUnixTime', time());
46
-        $this->setTemplate('bans/main.tpl');
47
-    }
48
-
49
-    protected function show(): void
50
-    {
51
-        $this->assignCSRFToken();
52
-        $this->setHtmlTitle('Bans');
53
-
54
-        $rawIdList = WebRequest::getString('id');
55
-        if ($rawIdList === null) {
56
-            $this->redirect('bans');
57
-
58
-            return;
59
-        }
60
-
61
-        $idList = explode(',', $rawIdList);
62
-
63
-        $database = $this->getDatabase();
64
-        $currentDomain = Domain::getCurrent($database);
65
-        $bans = Ban::getByIdList($idList, $database, $currentDomain->getId());
66
-
67
-        $this->setupBanList($bans);
68
-        $this->assign('isFiltered', true);
69
-        $this->assign('currentUnixTime', time());
70
-        $this->setTemplate('bans/main.tpl');
71
-    }
72
-
73
-    /**
74
-     * Entry point for the ban set action
75
-     * @throws SmartyException
76
-     * @throws Exception
77
-     */
78
-    protected function set(): void
79
-    {
80
-        $this->setHtmlTitle('Bans');
81
-
82
-        // dual-mode action
83
-        if (WebRequest::wasPosted()) {
84
-            try {
85
-                $this->handlePostMethodForSetBan();
86
-            }
87
-            catch (ApplicationLogicException $ex) {
88
-                SessionAlert::error($ex->getMessage());
89
-                $this->redirect("bans", "set");
90
-            }
91
-        }
92
-        else {
93
-            $this->handleGetMethodForSetBan();
94
-
95
-            $user = User::getCurrent($this->getDatabase());
96
-            $banType = WebRequest::getString('type');
97
-            $banRequest = WebRequest::getInt('request');
98
-
99
-            // if the parameters are null, skip loading a request.
100
-            if ($banType !== null && $banRequest !== null && $banRequest !== 0) {
101
-                $this->preloadFormForRequest($banRequest, $banType, $user);
102
-            }
103
-        }
104
-    }
105
-
106
-    protected function replace(): void
107
-    {
108
-        $this->setHtmlTitle('Bans');
109
-
110
-        $database = $this->getDatabase();
111
-        $domain = Domain::getCurrent($database);
112
-
113
-        // dual-mode action
114
-        if (WebRequest::wasPosted()) {
115
-            try {
116
-                $originalBanId = WebRequest::postInt('replaceBanId');
117
-                $originalBanUpdateVersion = WebRequest::postInt('replaceBanUpdateVersion');
118
-
119
-                $originalBan = Ban::getActiveId($originalBanId, $database, $domain->getId());
120
-
121
-                if ($originalBan === false) {
122
-                    throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
123
-                }
124
-
125
-                // Discard original ban; we're replacing it.
126
-                $originalBan->setUpdateVersion($originalBanUpdateVersion);
127
-                $originalBan->setActive(false);
128
-                $originalBan->save();
129
-
130
-                Logger::banReplaced($database, $originalBan);
131
-
132
-                // Proceed as normal to save the new ban.
133
-                $this->handlePostMethodForSetBan();
134
-            }
135
-            catch (ApplicationLogicException $ex) {
136
-                $database->rollback();
137
-                SessionAlert::error($ex->getMessage());
138
-                $this->redirect("bans", "set");
139
-            }
140
-        }
141
-        else {
142
-            $this->handleGetMethodForSetBan();
143
-
144
-            $user = User::getCurrent($database);
145
-            $originalBanId = WebRequest::getString('id');
146
-
147
-            $originalBan = Ban::getActiveId($originalBanId, $database, $domain->getId());
148
-
149
-            if ($originalBan === false) {
150
-                throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
151
-            }
152
-
153
-            if ($originalBan->getName() !== null) {
154
-                if (!$this->barrierTest('name', $user, 'BanType')) {
155
-                    SessionAlert::error("You are not allowed to set this type of ban.");
156
-                    $this->redirect("bans", "set");
157
-                    return;
158
-                }
159
-
160
-                $this->assign('banName', $originalBan->getName());
161
-            }
162
-
163
-            if ($originalBan->getEmail() !== null) {
164
-                if (!$this->barrierTest('email', $user, 'BanType')) {
165
-                    SessionAlert::error("You are not allowed to set this type of ban.");
166
-                    $this->redirect("bans", "set");
167
-                    return;
168
-                }
169
-
170
-                $this->assign('banEmail', $originalBan->getEmail());
171
-            }
172
-
173
-            if ($originalBan->getUseragent() !== null) {
174
-                if (!$this->barrierTest('useragent', $user, 'BanType')) {
175
-                    SessionAlert::error("You are not allowed to set this type of ban.");
176
-                    $this->redirect("bans", "set");
177
-                    return;
178
-                }
179
-
180
-                $this->assign('banUseragent', $originalBan->getUseragent());
181
-            }
182
-
183
-            if ($originalBan->getIp() !== null) {
184
-                if (!$this->barrierTest('ip', $user, 'BanType')) {
185
-                    SessionAlert::error("You are not allowed to set this type of ban.");
186
-                    $this->redirect("bans", "set");
187
-                    return;
188
-                }
189
-
190
-                $this->assign('banIP', $originalBan->getIp() . '/' . $originalBan->getIpMask());
191
-            }
192
-
193
-            $banIsGlobal = $originalBan->getDomain() === null;
194
-            if ($banIsGlobal) {
195
-                if (!$this->barrierTest('global', $user, 'BanType')) {
196
-                    SessionAlert::error("You are not allowed to set this type of ban.");
197
-                    $this->redirect("bans", "set");
198
-                    return;
199
-                }
200
-            }
201
-
202
-            if (!$this->barrierTest($originalBan->getVisibility(), $user, 'BanVisibility')) {
203
-                SessionAlert::error("You are not allowed to set this type of ban.");
204
-                $this->redirect("bans", "set");
205
-                return;
206
-            }
207
-
208
-            $this->assign('banGlobal', $banIsGlobal);
209
-            $this->assign('banVisibility', $originalBan->getVisibility());
210
-
211
-            if ($originalBan->getDuration() !== null) {
212
-                $this->assign('banDuration', date('c', $originalBan->getDuration()));
213
-            }
214
-
215
-            $this->assign('banReason', $originalBan->getReason());
216
-            $this->assign('banAction', $originalBan->getAction());
217
-            $this->assign('banQueue', $originalBan->getTargetQueue());
218
-
219
-            $this->assign('replaceBanId', $originalBan->getId());
220
-            $this->assign('replaceBanUpdateVersion', $originalBan->getUpdateVersion());
221
-        }
222
-    }
223
-
224
-    /**
225
-     * Entry point for the ban remove action
226
-     *
227
-     * @throws AccessDeniedException
228
-     * @throws ApplicationLogicException
229
-     * @throws SmartyException
230
-     */
231
-    protected function remove(): void
232
-    {
233
-        $this->setHtmlTitle('Bans');
234
-
235
-        $ban = $this->getBanForUnban();
236
-
237
-        $banHelper = new BanHelper($this->getDatabase(), $this->getXffTrustProvider(), $this->getSecurityManager());
238
-        if (!$banHelper->canUnban($ban)) {
239
-            // triggered when a user tries to unban a ban they can't see the entirety of.
240
-            // there's no UI way to get to this, so a raw exception is fine.
241
-            throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
242
-        }
243
-
244
-        // dual mode
245
-        if (WebRequest::wasPosted()) {
246
-            $this->validateCSRFToken();
247
-            $unbanReason = WebRequest::postString('unbanreason');
248
-
249
-            if ($unbanReason === null || trim($unbanReason) === "") {
250
-                SessionAlert::error('No unban reason specified');
251
-                $this->redirect("bans", "remove", array('id' => $ban->getId()));
252
-            }
253
-
254
-            // set optimistic locking from delete form page load
255
-            $updateVersion = WebRequest::postInt('updateversion');
256
-            $ban->setUpdateVersion($updateVersion);
257
-
258
-            $database = $this->getDatabase();
259
-            $ban->setActive(false);
260
-            $ban->save();
261
-
262
-            Logger::unbanned($database, $ban, $unbanReason);
263
-
264
-            SessionAlert::quick('Disabled ban.');
265
-            $this->getNotificationHelper()->unbanned($ban, $unbanReason);
266
-
267
-            $this->redirect('bans');
268
-        }
269
-        else {
270
-            $this->assignCSRFToken();
271
-            $this->assign('ban', $ban);
272
-            $this->setTemplate('bans/unban.tpl');
273
-        }
274
-    }
275
-
276
-    /**
277
-     * Retrieves the requested ban duration from the WebRequest
278
-     *
279
-     * @throws ApplicationLogicException
280
-     */
281
-    private function getBanDuration(): ?int
282
-    {
283
-        $duration = WebRequest::postString('duration');
284
-        if ($duration === "other") {
285
-            $duration = strtotime(WebRequest::postString('otherduration'));
286
-
287
-            if (!$duration) {
288
-                throw new ApplicationLogicException('Invalid ban time');
289
-            }
290
-            elseif (time() > $duration) {
291
-                throw new ApplicationLogicException('Ban time has already expired!');
292
-            }
293
-
294
-            return $duration;
295
-        }
296
-        elseif ($duration === "-1") {
297
-            return null;
298
-        }
299
-        else {
300
-            return WebRequest::postInt('duration') + time();
301
-        }
302
-    }
303
-
304
-    /**
305
-     * Handles the POST method on the set action
306
-     *
307
-     * @throws ApplicationLogicException
308
-     * @throws Exception
309
-     */
310
-    private function handlePostMethodForSetBan()
311
-    {
312
-        $this->validateCSRFToken();
313
-        $database = $this->getDatabase();
314
-        $user = User::getCurrent($database);
315
-        $currentDomain = Domain::getCurrent($database);
316
-
317
-        // Checks whether there is a reason entered for ban.
318
-        $reason = WebRequest::postString('banreason');
319
-        if ($reason === null || trim($reason) === "") {
320
-            throw new ApplicationLogicException('You must specify a ban reason');
321
-        }
322
-
323
-        // ban targets
324
-        list($targetName, $targetIp, $targetEmail, $targetUseragent) = $this->getRawBanTargets($user);
325
-
326
-        $visibility = $this->getBanVisibility();
327
-
328
-        // Validate ban duration
329
-        $duration = $this->getBanDuration();
330
-
331
-        $action = WebRequest::postString('banAction') ?? Ban::ACTION_NONE;
332
-
333
-        $global = WebRequest::postBoolean('banGlobal');
334
-        if (!$this->barrierTest('global', $user, 'BanType')) {
335
-            $global = false;
336
-        }
337
-
338
-        if ($action === Ban::ACTION_DEFER && $global) {
339
-            throw new ApplicationLogicException("Cannot set a global ban in defer-to-queue mode.");
340
-        }
341
-
342
-        // handle CIDR ranges
343
-        $targetMask = null;
344
-        if ($targetIp !== null) {
345
-            list($targetIp, $targetMask) = $this->splitCidrRange($targetIp);
346
-            $this->validateIpBan($targetIp, $targetMask, $user, $action);
347
-        }
348
-
349
-        $banHelper = new BanHelper($this->getDatabase(), $this->getXffTrustProvider(), $this->getSecurityManager());
350
-
351
-        $bansByTarget = $banHelper->getBansByTarget(
352
-            $targetName,
353
-            $targetEmail,
354
-            $targetIp,
355
-            $targetMask,
356
-            $targetUseragent,
357
-            $currentDomain->getId());
358
-
359
-        if (count($bansByTarget) > 0) {
360
-            throw new ApplicationLogicException('This target is already banned!');
361
-        }
362
-
363
-        $ban = new Ban();
364
-        $ban->setDatabase($database);
365
-        $ban->setActive(true);
366
-
367
-        $ban->setName($targetName);
368
-        $ban->setIp($targetIp, $targetMask);
369
-        $ban->setEmail($targetEmail);
370
-        $ban->setUseragent($targetUseragent);
371
-
372
-        $ban->setUser($user->getId());
373
-        $ban->setReason($reason);
374
-        $ban->setDuration($duration);
375
-        $ban->setVisibility($visibility);
376
-
377
-        $ban->setDomain($global ? null : $currentDomain->getId());
378
-
379
-        $ban->setAction($action);
380
-        if ($ban->getAction() === Ban::ACTION_DEFER) {
381
-            //FIXME: domains
382
-            $queue = RequestQueue::getByApiName($database, WebRequest::postString('banActionTarget'), 1);
383
-            if ($queue === false) {
384
-                throw new ApplicationLogicException("Unknown target queue");
385
-            }
386
-
387
-            if (!$queue->isEnabled()) {
388
-                throw new ApplicationLogicException("Target queue is not enabled");
389
-            }
390
-
391
-            $ban->setTargetQueue($queue->getId());
392
-        }
393
-
394
-        $ban->save();
395
-
396
-        Logger::banned($database, $ban, $reason);
397
-
398
-        $this->getNotificationHelper()->banned($ban);
399
-        SessionAlert::quick('Ban has been set.');
400
-
401
-        $this->redirect('bans');
402
-    }
403
-
404
-    /**
405
-     * Handles the GET method on the set action
406
-     * @throws Exception
407
-     */
408
-    private function handleGetMethodForSetBan()
409
-    {
410
-        $this->setTemplate('bans/banform.tpl');
411
-        $this->assignCSRFToken();
412
-
413
-        $this->assign('maxIpRange', $this->getSiteConfiguration()->getBanMaxIpRange());
414
-        $this->assign('maxIpBlockRange', $this->getSiteConfiguration()->getBanMaxIpBlockRange());
415
-
416
-        $this->assign('banVisibility', 'user');
417
-        $this->assign('banGlobal', false);
418
-        $this->assign('banQueue', false);
419
-        $this->assign('banAction', Ban::ACTION_BLOCK);
420
-        $this->assign('banDuration', '');
421
-        $this->assign('banReason', '');
422
-
423
-        $this->assign('banEmail', '');
424
-        $this->assign('banIP', '');
425
-        $this->assign('banName', '');
426
-        $this->assign('banUseragent', '');
427
-
428
-        $this->assign('replaceBanId', null);
429
-
430
-
431
-
432
-        $database = $this->getDatabase();
433
-
434
-        $user = User::getCurrent($database);
435
-        $this->setupSecurity($user);
436
-
437
-        $queues = RequestQueue::getEnabledQueues($database);
438
-
439
-        $this->assign('requestQueues', $queues);
440
-    }
441
-
442
-    /**
443
-     * Finds the Ban object referenced in the WebRequest if it is valid
444
-     *
445
-     * @return Ban
446
-     * @throws ApplicationLogicException
447
-     */
448
-    private function getBanForUnban(): Ban
449
-    {
450
-        $banId = WebRequest::getInt('id');
451
-        if ($banId === null || $banId === 0) {
452
-            throw new ApplicationLogicException("The ban ID appears to be missing. This is probably a bug.");
453
-        }
454
-
455
-        $database = $this->getDatabase();
456
-        $this->setupSecurity(User::getCurrent($database));
457
-        $currentDomain = Domain::getCurrent($database);
458
-        $ban = Ban::getActiveId($banId, $database, $currentDomain->getId());
459
-
460
-        if ($ban === false) {
461
-            throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
462
-        }
463
-
464
-        return $ban;
465
-    }
466
-
467
-    /**
468
-     * Sets up Smarty variables for access control
469
-     */
470
-    private function setupSecurity(User $user): void
471
-    {
472
-        $this->assign('canSeeIpBan', $this->barrierTest('ip', $user, 'BanType'));
473
-        $this->assign('canSeeNameBan', $this->barrierTest('name', $user, 'BanType'));
474
-        $this->assign('canSeeEmailBan', $this->barrierTest('email', $user, 'BanType'));
475
-        $this->assign('canSeeUseragentBan', $this->barrierTest('useragent', $user, 'BanType'));
476
-
477
-        $this->assign('canGlobalBan', $this->barrierTest('global', $user, 'BanType'));
478
-
479
-        $this->assign('canSeeUserVisibility', $this->barrierTest('user', $user, 'BanVisibility'));
480
-        $this->assign('canSeeAdminVisibility', $this->barrierTest('admin', $user, 'BanVisibility'));
481
-        $this->assign('canSeeCheckuserVisibility', $this->barrierTest('checkuser', $user, 'BanVisibility'));
482
-    }
483
-
484
-    /**
485
-     * Validates that the provided IP is acceptable for a ban of this type
486
-     *
487
-     * @param string $targetIp   IP address
488
-     * @param int    $targetMask CIDR prefix length
489
-     * @param User   $user       User performing the ban
490
-     * @param string $action     Ban action to take
491
-     *
492
-     * @throws ApplicationLogicException
493
-     */
494
-    private function validateIpBan(string $targetIp, int $targetMask, User $user, string $action): void
495
-    {
496
-        // validate this is an IP
497
-        if (!filter_var($targetIp, FILTER_VALIDATE_IP)) {
498
-            throw new ApplicationLogicException("Not a valid IP address");
499
-        }
500
-
501
-        $canLargeIpBan = $this->barrierTest('ip-largerange', $user, 'BanType');
502
-        $maxIpBlockRange = $this->getSiteConfiguration()->getBanMaxIpBlockRange();
503
-        $maxIpRange = $this->getSiteConfiguration()->getBanMaxIpRange();
504
-
505
-        // validate CIDR ranges
506
-        if (filter_var($targetIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
507
-            if ($targetMask < 0 || $targetMask > 128) {
508
-                throw new ApplicationLogicException("CIDR mask out of range for IPv6");
509
-            }
510
-
511
-            // prevent setting the ban if:
512
-            //  * the user isn't allowed to set large bans, AND
513
-            //  * the ban is a drop or a block (preventing human review of the request), AND
514
-            //  * the mask is too wide-reaching
515
-            if (!$canLargeIpBan && ($action == Ban::ACTION_BLOCK || $action == Ban::ACTION_DROP) && $targetMask < $maxIpBlockRange[6]) {
516
-                throw new ApplicationLogicException("The requested IP range for this ban is too wide for the block/drop action.");
517
-            }
518
-
519
-            if (!$canLargeIpBan && $targetMask < $maxIpRange[6]) {
520
-                throw new ApplicationLogicException("The requested IP range for this ban is too wide.");
521
-            }
522
-        }
523
-
524
-        if (filter_var($targetIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
525
-            if ($targetMask < 0 || $targetMask > 32) {
526
-                throw new ApplicationLogicException("CIDR mask out of range for IPv4");
527
-            }
528
-
529
-            if (!$canLargeIpBan && ($action == Ban::ACTION_BLOCK || $action == Ban::ACTION_DROP) && $targetMask < $maxIpBlockRange[4]) {
530
-                throw new ApplicationLogicException("The IP range for this ban is too wide for the block/drop action.");
531
-            }
532
-
533
-            if (!$canLargeIpBan && $targetMask < $maxIpRange[4]) {
534
-                throw new ApplicationLogicException("The requested IP range for this ban is too wide.");
535
-            }
536
-        }
537
-
538
-        $squidIpList = $this->getSiteConfiguration()->getSquidList();
539
-        if (in_array($targetIp, $squidIpList)) {
540
-            throw new ApplicationLogicException("This IP address is on the protected list of proxies, and cannot be banned.");
541
-        }
542
-    }
543
-
544
-    /**
545
-     * Configures a ban list template for display
546
-     *
547
-     * @param Ban[] $bans
548
-     */
549
-    private function setupBanList(array $bans): void
550
-    {
551
-        $userIds = array_map(fn(Ban $entry) => $entry->getUser(), $bans);
552
-        $userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
553
-
554
-        $domainIds = array_filter(array_unique(array_map(fn(Ban $entry) => $entry->getDomain(), $bans)));
555
-        $domains = [];
556
-        foreach ($domainIds as $d) {
557
-            if ($d === null) {
558
-                continue;
559
-            }
560
-            $domains[$d] = Domain::getById($d, $this->getDatabase());
561
-        }
562
-
563
-        $this->assign('domains', $domains);
564
-
565
-        $user = User::getCurrent($this->getDatabase());
566
-        $this->assign('canSet', $this->barrierTest('set', $user));
567
-        $this->assign('canRemove', $this->barrierTest('remove', $user));
568
-
569
-        $this->setupSecurity($user);
570
-
571
-        $this->assign('usernames', $userList);
572
-        $this->assign('activebans', $bans);
573
-
574
-        $banHelper = new BanHelper($this->getDatabase(), $this->getXffTrustProvider(), $this->getSecurityManager());
575
-        $this->assign('banHelper', $banHelper);
576
-    }
577
-
578
-    /**
579
-     * Converts a plain IP or CIDR mask into an IP and a CIDR suffix
580
-     *
581
-     * @param string $targetIp IP or CIDR range
582
-     *
583
-     * @return array
584
-     */
585
-    private function splitCidrRange(string $targetIp): array
586
-    {
587
-        if (strpos($targetIp, '/') !== false) {
588
-            $ipParts = explode('/', $targetIp, 2);
589
-            $targetIp = $ipParts[0];
590
-            $targetMask = (int)$ipParts[1];
591
-        }
592
-        else {
593
-            // Default the CIDR range based on the IP type
594
-            $targetMask = filter_var($targetIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? 128 : 32;
595
-        }
596
-
597
-        return array($targetIp, $targetMask);
30
+	/**
31
+	 * Main function for this page, when no specific actions are called.
32
+	 */
33
+	protected function main(): void
34
+	{
35
+		$this->assignCSRFToken();
36
+		$this->setHtmlTitle('Bans');
37
+
38
+		$database = $this->getDatabase();
39
+		$currentDomain = Domain::getCurrent($database);
40
+		$bans = Ban::getActiveBans($database, $currentDomain->getId());
41
+
42
+		$this->setupBanList($bans);
43
+
44
+		$this->assign('isFiltered', false);
45
+		$this->assign('currentUnixTime', time());
46
+		$this->setTemplate('bans/main.tpl');
47
+	}
48
+
49
+	protected function show(): void
50
+	{
51
+		$this->assignCSRFToken();
52
+		$this->setHtmlTitle('Bans');
53
+
54
+		$rawIdList = WebRequest::getString('id');
55
+		if ($rawIdList === null) {
56
+			$this->redirect('bans');
57
+
58
+			return;
59
+		}
60
+
61
+		$idList = explode(',', $rawIdList);
62
+
63
+		$database = $this->getDatabase();
64
+		$currentDomain = Domain::getCurrent($database);
65
+		$bans = Ban::getByIdList($idList, $database, $currentDomain->getId());
66
+
67
+		$this->setupBanList($bans);
68
+		$this->assign('isFiltered', true);
69
+		$this->assign('currentUnixTime', time());
70
+		$this->setTemplate('bans/main.tpl');
71
+	}
72
+
73
+	/**
74
+	 * Entry point for the ban set action
75
+	 * @throws SmartyException
76
+	 * @throws Exception
77
+	 */
78
+	protected function set(): void
79
+	{
80
+		$this->setHtmlTitle('Bans');
81
+
82
+		// dual-mode action
83
+		if (WebRequest::wasPosted()) {
84
+			try {
85
+				$this->handlePostMethodForSetBan();
86
+			}
87
+			catch (ApplicationLogicException $ex) {
88
+				SessionAlert::error($ex->getMessage());
89
+				$this->redirect("bans", "set");
90
+			}
91
+		}
92
+		else {
93
+			$this->handleGetMethodForSetBan();
94
+
95
+			$user = User::getCurrent($this->getDatabase());
96
+			$banType = WebRequest::getString('type');
97
+			$banRequest = WebRequest::getInt('request');
98
+
99
+			// if the parameters are null, skip loading a request.
100
+			if ($banType !== null && $banRequest !== null && $banRequest !== 0) {
101
+				$this->preloadFormForRequest($banRequest, $banType, $user);
102
+			}
103
+		}
104
+	}
105
+
106
+	protected function replace(): void
107
+	{
108
+		$this->setHtmlTitle('Bans');
109
+
110
+		$database = $this->getDatabase();
111
+		$domain = Domain::getCurrent($database);
112
+
113
+		// dual-mode action
114
+		if (WebRequest::wasPosted()) {
115
+			try {
116
+				$originalBanId = WebRequest::postInt('replaceBanId');
117
+				$originalBanUpdateVersion = WebRequest::postInt('replaceBanUpdateVersion');
118
+
119
+				$originalBan = Ban::getActiveId($originalBanId, $database, $domain->getId());
120
+
121
+				if ($originalBan === false) {
122
+					throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
123
+				}
124
+
125
+				// Discard original ban; we're replacing it.
126
+				$originalBan->setUpdateVersion($originalBanUpdateVersion);
127
+				$originalBan->setActive(false);
128
+				$originalBan->save();
129
+
130
+				Logger::banReplaced($database, $originalBan);
131
+
132
+				// Proceed as normal to save the new ban.
133
+				$this->handlePostMethodForSetBan();
134
+			}
135
+			catch (ApplicationLogicException $ex) {
136
+				$database->rollback();
137
+				SessionAlert::error($ex->getMessage());
138
+				$this->redirect("bans", "set");
139
+			}
140
+		}
141
+		else {
142
+			$this->handleGetMethodForSetBan();
143
+
144
+			$user = User::getCurrent($database);
145
+			$originalBanId = WebRequest::getString('id');
146
+
147
+			$originalBan = Ban::getActiveId($originalBanId, $database, $domain->getId());
148
+
149
+			if ($originalBan === false) {
150
+				throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
151
+			}
152
+
153
+			if ($originalBan->getName() !== null) {
154
+				if (!$this->barrierTest('name', $user, 'BanType')) {
155
+					SessionAlert::error("You are not allowed to set this type of ban.");
156
+					$this->redirect("bans", "set");
157
+					return;
158
+				}
159
+
160
+				$this->assign('banName', $originalBan->getName());
161
+			}
162
+
163
+			if ($originalBan->getEmail() !== null) {
164
+				if (!$this->barrierTest('email', $user, 'BanType')) {
165
+					SessionAlert::error("You are not allowed to set this type of ban.");
166
+					$this->redirect("bans", "set");
167
+					return;
168
+				}
169
+
170
+				$this->assign('banEmail', $originalBan->getEmail());
171
+			}
172
+
173
+			if ($originalBan->getUseragent() !== null) {
174
+				if (!$this->barrierTest('useragent', $user, 'BanType')) {
175
+					SessionAlert::error("You are not allowed to set this type of ban.");
176
+					$this->redirect("bans", "set");
177
+					return;
178
+				}
179
+
180
+				$this->assign('banUseragent', $originalBan->getUseragent());
181
+			}
182
+
183
+			if ($originalBan->getIp() !== null) {
184
+				if (!$this->barrierTest('ip', $user, 'BanType')) {
185
+					SessionAlert::error("You are not allowed to set this type of ban.");
186
+					$this->redirect("bans", "set");
187
+					return;
188
+				}
189
+
190
+				$this->assign('banIP', $originalBan->getIp() . '/' . $originalBan->getIpMask());
191
+			}
192
+
193
+			$banIsGlobal = $originalBan->getDomain() === null;
194
+			if ($banIsGlobal) {
195
+				if (!$this->barrierTest('global', $user, 'BanType')) {
196
+					SessionAlert::error("You are not allowed to set this type of ban.");
197
+					$this->redirect("bans", "set");
198
+					return;
199
+				}
200
+			}
201
+
202
+			if (!$this->barrierTest($originalBan->getVisibility(), $user, 'BanVisibility')) {
203
+				SessionAlert::error("You are not allowed to set this type of ban.");
204
+				$this->redirect("bans", "set");
205
+				return;
206
+			}
207
+
208
+			$this->assign('banGlobal', $banIsGlobal);
209
+			$this->assign('banVisibility', $originalBan->getVisibility());
210
+
211
+			if ($originalBan->getDuration() !== null) {
212
+				$this->assign('banDuration', date('c', $originalBan->getDuration()));
213
+			}
214
+
215
+			$this->assign('banReason', $originalBan->getReason());
216
+			$this->assign('banAction', $originalBan->getAction());
217
+			$this->assign('banQueue', $originalBan->getTargetQueue());
218
+
219
+			$this->assign('replaceBanId', $originalBan->getId());
220
+			$this->assign('replaceBanUpdateVersion', $originalBan->getUpdateVersion());
221
+		}
222
+	}
223
+
224
+	/**
225
+	 * Entry point for the ban remove action
226
+	 *
227
+	 * @throws AccessDeniedException
228
+	 * @throws ApplicationLogicException
229
+	 * @throws SmartyException
230
+	 */
231
+	protected function remove(): void
232
+	{
233
+		$this->setHtmlTitle('Bans');
234
+
235
+		$ban = $this->getBanForUnban();
236
+
237
+		$banHelper = new BanHelper($this->getDatabase(), $this->getXffTrustProvider(), $this->getSecurityManager());
238
+		if (!$banHelper->canUnban($ban)) {
239
+			// triggered when a user tries to unban a ban they can't see the entirety of.
240
+			// there's no UI way to get to this, so a raw exception is fine.
241
+			throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
242
+		}
243
+
244
+		// dual mode
245
+		if (WebRequest::wasPosted()) {
246
+			$this->validateCSRFToken();
247
+			$unbanReason = WebRequest::postString('unbanreason');
248
+
249
+			if ($unbanReason === null || trim($unbanReason) === "") {
250
+				SessionAlert::error('No unban reason specified');
251
+				$this->redirect("bans", "remove", array('id' => $ban->getId()));
252
+			}
253
+
254
+			// set optimistic locking from delete form page load
255
+			$updateVersion = WebRequest::postInt('updateversion');
256
+			$ban->setUpdateVersion($updateVersion);
257
+
258
+			$database = $this->getDatabase();
259
+			$ban->setActive(false);
260
+			$ban->save();
261
+
262
+			Logger::unbanned($database, $ban, $unbanReason);
263
+
264
+			SessionAlert::quick('Disabled ban.');
265
+			$this->getNotificationHelper()->unbanned($ban, $unbanReason);
266
+
267
+			$this->redirect('bans');
268
+		}
269
+		else {
270
+			$this->assignCSRFToken();
271
+			$this->assign('ban', $ban);
272
+			$this->setTemplate('bans/unban.tpl');
273
+		}
274
+	}
275
+
276
+	/**
277
+	 * Retrieves the requested ban duration from the WebRequest
278
+	 *
279
+	 * @throws ApplicationLogicException
280
+	 */
281
+	private function getBanDuration(): ?int
282
+	{
283
+		$duration = WebRequest::postString('duration');
284
+		if ($duration === "other") {
285
+			$duration = strtotime(WebRequest::postString('otherduration'));
286
+
287
+			if (!$duration) {
288
+				throw new ApplicationLogicException('Invalid ban time');
289
+			}
290
+			elseif (time() > $duration) {
291
+				throw new ApplicationLogicException('Ban time has already expired!');
292
+			}
293
+
294
+			return $duration;
295
+		}
296
+		elseif ($duration === "-1") {
297
+			return null;
298
+		}
299
+		else {
300
+			return WebRequest::postInt('duration') + time();
301
+		}
302
+	}
303
+
304
+	/**
305
+	 * Handles the POST method on the set action
306
+	 *
307
+	 * @throws ApplicationLogicException
308
+	 * @throws Exception
309
+	 */
310
+	private function handlePostMethodForSetBan()
311
+	{
312
+		$this->validateCSRFToken();
313
+		$database = $this->getDatabase();
314
+		$user = User::getCurrent($database);
315
+		$currentDomain = Domain::getCurrent($database);
316
+
317
+		// Checks whether there is a reason entered for ban.
318
+		$reason = WebRequest::postString('banreason');
319
+		if ($reason === null || trim($reason) === "") {
320
+			throw new ApplicationLogicException('You must specify a ban reason');
321
+		}
322
+
323
+		// ban targets
324
+		list($targetName, $targetIp, $targetEmail, $targetUseragent) = $this->getRawBanTargets($user);
325
+
326
+		$visibility = $this->getBanVisibility();
327
+
328
+		// Validate ban duration
329
+		$duration = $this->getBanDuration();
330
+
331
+		$action = WebRequest::postString('banAction') ?? Ban::ACTION_NONE;
332
+
333
+		$global = WebRequest::postBoolean('banGlobal');
334
+		if (!$this->barrierTest('global', $user, 'BanType')) {
335
+			$global = false;
336
+		}
337
+
338
+		if ($action === Ban::ACTION_DEFER && $global) {
339
+			throw new ApplicationLogicException("Cannot set a global ban in defer-to-queue mode.");
340
+		}
341
+
342
+		// handle CIDR ranges
343
+		$targetMask = null;
344
+		if ($targetIp !== null) {
345
+			list($targetIp, $targetMask) = $this->splitCidrRange($targetIp);
346
+			$this->validateIpBan($targetIp, $targetMask, $user, $action);
347
+		}
348
+
349
+		$banHelper = new BanHelper($this->getDatabase(), $this->getXffTrustProvider(), $this->getSecurityManager());
350
+
351
+		$bansByTarget = $banHelper->getBansByTarget(
352
+			$targetName,
353
+			$targetEmail,
354
+			$targetIp,
355
+			$targetMask,
356
+			$targetUseragent,
357
+			$currentDomain->getId());
358
+
359
+		if (count($bansByTarget) > 0) {
360
+			throw new ApplicationLogicException('This target is already banned!');
361
+		}
362
+
363
+		$ban = new Ban();
364
+		$ban->setDatabase($database);
365
+		$ban->setActive(true);
366
+
367
+		$ban->setName($targetName);
368
+		$ban->setIp($targetIp, $targetMask);
369
+		$ban->setEmail($targetEmail);
370
+		$ban->setUseragent($targetUseragent);
371
+
372
+		$ban->setUser($user->getId());
373
+		$ban->setReason($reason);
374
+		$ban->setDuration($duration);
375
+		$ban->setVisibility($visibility);
376
+
377
+		$ban->setDomain($global ? null : $currentDomain->getId());
378
+
379
+		$ban->setAction($action);
380
+		if ($ban->getAction() === Ban::ACTION_DEFER) {
381
+			//FIXME: domains
382
+			$queue = RequestQueue::getByApiName($database, WebRequest::postString('banActionTarget'), 1);
383
+			if ($queue === false) {
384
+				throw new ApplicationLogicException("Unknown target queue");
385
+			}
386
+
387
+			if (!$queue->isEnabled()) {
388
+				throw new ApplicationLogicException("Target queue is not enabled");
389
+			}
390
+
391
+			$ban->setTargetQueue($queue->getId());
392
+		}
393
+
394
+		$ban->save();
395
+
396
+		Logger::banned($database, $ban, $reason);
397
+
398
+		$this->getNotificationHelper()->banned($ban);
399
+		SessionAlert::quick('Ban has been set.');
400
+
401
+		$this->redirect('bans');
402
+	}
403
+
404
+	/**
405
+	 * Handles the GET method on the set action
406
+	 * @throws Exception
407
+	 */
408
+	private function handleGetMethodForSetBan()
409
+	{
410
+		$this->setTemplate('bans/banform.tpl');
411
+		$this->assignCSRFToken();
412
+
413
+		$this->assign('maxIpRange', $this->getSiteConfiguration()->getBanMaxIpRange());
414
+		$this->assign('maxIpBlockRange', $this->getSiteConfiguration()->getBanMaxIpBlockRange());
415
+
416
+		$this->assign('banVisibility', 'user');
417
+		$this->assign('banGlobal', false);
418
+		$this->assign('banQueue', false);
419
+		$this->assign('banAction', Ban::ACTION_BLOCK);
420
+		$this->assign('banDuration', '');
421
+		$this->assign('banReason', '');
422
+
423
+		$this->assign('banEmail', '');
424
+		$this->assign('banIP', '');
425
+		$this->assign('banName', '');
426
+		$this->assign('banUseragent', '');
427
+
428
+		$this->assign('replaceBanId', null);
429
+
430
+
431
+
432
+		$database = $this->getDatabase();
433
+
434
+		$user = User::getCurrent($database);
435
+		$this->setupSecurity($user);
436
+
437
+		$queues = RequestQueue::getEnabledQueues($database);
438
+
439
+		$this->assign('requestQueues', $queues);
440
+	}
441
+
442
+	/**
443
+	 * Finds the Ban object referenced in the WebRequest if it is valid
444
+	 *
445
+	 * @return Ban
446
+	 * @throws ApplicationLogicException
447
+	 */
448
+	private function getBanForUnban(): Ban
449
+	{
450
+		$banId = WebRequest::getInt('id');
451
+		if ($banId === null || $banId === 0) {
452
+			throw new ApplicationLogicException("The ban ID appears to be missing. This is probably a bug.");
453
+		}
454
+
455
+		$database = $this->getDatabase();
456
+		$this->setupSecurity(User::getCurrent($database));
457
+		$currentDomain = Domain::getCurrent($database);
458
+		$ban = Ban::getActiveId($banId, $database, $currentDomain->getId());
459
+
460
+		if ($ban === false) {
461
+			throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
462
+		}
463
+
464
+		return $ban;
465
+	}
466
+
467
+	/**
468
+	 * Sets up Smarty variables for access control
469
+	 */
470
+	private function setupSecurity(User $user): void
471
+	{
472
+		$this->assign('canSeeIpBan', $this->barrierTest('ip', $user, 'BanType'));
473
+		$this->assign('canSeeNameBan', $this->barrierTest('name', $user, 'BanType'));
474
+		$this->assign('canSeeEmailBan', $this->barrierTest('email', $user, 'BanType'));
475
+		$this->assign('canSeeUseragentBan', $this->barrierTest('useragent', $user, 'BanType'));
476
+
477
+		$this->assign('canGlobalBan', $this->barrierTest('global', $user, 'BanType'));
478
+
479
+		$this->assign('canSeeUserVisibility', $this->barrierTest('user', $user, 'BanVisibility'));
480
+		$this->assign('canSeeAdminVisibility', $this->barrierTest('admin', $user, 'BanVisibility'));
481
+		$this->assign('canSeeCheckuserVisibility', $this->barrierTest('checkuser', $user, 'BanVisibility'));
482
+	}
483
+
484
+	/**
485
+	 * Validates that the provided IP is acceptable for a ban of this type
486
+	 *
487
+	 * @param string $targetIp   IP address
488
+	 * @param int    $targetMask CIDR prefix length
489
+	 * @param User   $user       User performing the ban
490
+	 * @param string $action     Ban action to take
491
+	 *
492
+	 * @throws ApplicationLogicException
493
+	 */
494
+	private function validateIpBan(string $targetIp, int $targetMask, User $user, string $action): void
495
+	{
496
+		// validate this is an IP
497
+		if (!filter_var($targetIp, FILTER_VALIDATE_IP)) {
498
+			throw new ApplicationLogicException("Not a valid IP address");
499
+		}
500
+
501
+		$canLargeIpBan = $this->barrierTest('ip-largerange', $user, 'BanType');
502
+		$maxIpBlockRange = $this->getSiteConfiguration()->getBanMaxIpBlockRange();
503
+		$maxIpRange = $this->getSiteConfiguration()->getBanMaxIpRange();
504
+
505
+		// validate CIDR ranges
506
+		if (filter_var($targetIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
507
+			if ($targetMask < 0 || $targetMask > 128) {
508
+				throw new ApplicationLogicException("CIDR mask out of range for IPv6");
509
+			}
510
+
511
+			// prevent setting the ban if:
512
+			//  * the user isn't allowed to set large bans, AND
513
+			//  * the ban is a drop or a block (preventing human review of the request), AND
514
+			//  * the mask is too wide-reaching
515
+			if (!$canLargeIpBan && ($action == Ban::ACTION_BLOCK || $action == Ban::ACTION_DROP) && $targetMask < $maxIpBlockRange[6]) {
516
+				throw new ApplicationLogicException("The requested IP range for this ban is too wide for the block/drop action.");
517
+			}
518
+
519
+			if (!$canLargeIpBan && $targetMask < $maxIpRange[6]) {
520
+				throw new ApplicationLogicException("The requested IP range for this ban is too wide.");
521
+			}
522
+		}
523
+
524
+		if (filter_var($targetIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
525
+			if ($targetMask < 0 || $targetMask > 32) {
526
+				throw new ApplicationLogicException("CIDR mask out of range for IPv4");
527
+			}
528
+
529
+			if (!$canLargeIpBan && ($action == Ban::ACTION_BLOCK || $action == Ban::ACTION_DROP) && $targetMask < $maxIpBlockRange[4]) {
530
+				throw new ApplicationLogicException("The IP range for this ban is too wide for the block/drop action.");
531
+			}
532
+
533
+			if (!$canLargeIpBan && $targetMask < $maxIpRange[4]) {
534
+				throw new ApplicationLogicException("The requested IP range for this ban is too wide.");
535
+			}
536
+		}
537
+
538
+		$squidIpList = $this->getSiteConfiguration()->getSquidList();
539
+		if (in_array($targetIp, $squidIpList)) {
540
+			throw new ApplicationLogicException("This IP address is on the protected list of proxies, and cannot be banned.");
541
+		}
542
+	}
543
+
544
+	/**
545
+	 * Configures a ban list template for display
546
+	 *
547
+	 * @param Ban[] $bans
548
+	 */
549
+	private function setupBanList(array $bans): void
550
+	{
551
+		$userIds = array_map(fn(Ban $entry) => $entry->getUser(), $bans);
552
+		$userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
553
+
554
+		$domainIds = array_filter(array_unique(array_map(fn(Ban $entry) => $entry->getDomain(), $bans)));
555
+		$domains = [];
556
+		foreach ($domainIds as $d) {
557
+			if ($d === null) {
558
+				continue;
559
+			}
560
+			$domains[$d] = Domain::getById($d, $this->getDatabase());
561
+		}
562
+
563
+		$this->assign('domains', $domains);
564
+
565
+		$user = User::getCurrent($this->getDatabase());
566
+		$this->assign('canSet', $this->barrierTest('set', $user));
567
+		$this->assign('canRemove', $this->barrierTest('remove', $user));
568
+
569
+		$this->setupSecurity($user);
570
+
571
+		$this->assign('usernames', $userList);
572
+		$this->assign('activebans', $bans);
573
+
574
+		$banHelper = new BanHelper($this->getDatabase(), $this->getXffTrustProvider(), $this->getSecurityManager());
575
+		$this->assign('banHelper', $banHelper);
576
+	}
577
+
578
+	/**
579
+	 * Converts a plain IP or CIDR mask into an IP and a CIDR suffix
580
+	 *
581
+	 * @param string $targetIp IP or CIDR range
582
+	 *
583
+	 * @return array
584
+	 */
585
+	private function splitCidrRange(string $targetIp): array
586
+	{
587
+		if (strpos($targetIp, '/') !== false) {
588
+			$ipParts = explode('/', $targetIp, 2);
589
+			$targetIp = $ipParts[0];
590
+			$targetMask = (int)$ipParts[1];
591
+		}
592
+		else {
593
+			// Default the CIDR range based on the IP type
594
+			$targetMask = filter_var($targetIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? 128 : 32;
595
+		}
596
+
597
+		return array($targetIp, $targetMask);
598 598
 }
599 599
 
600
-    /**
601
-     * Returns the validated ban visibility from WebRequest
602
-     *
603
-     * @throws ApplicationLogicException
604
-     */
605
-    private function getBanVisibility(): string
606
-    {
607
-        $visibility = WebRequest::postString('banVisibility');
608
-        if ($visibility !== 'user' && $visibility !== 'admin' && $visibility !== 'checkuser') {
609
-            throw new ApplicationLogicException('Invalid ban visibility');
610
-        }
611
-
612
-        return $visibility;
613
-    }
614
-
615
-    /**
616
-     * Returns array of [username, ip, email, ua] as ban targets from WebRequest,
617
-     * filtered for whether the user is allowed to set bans including those types.
618
-     *
619
-     * @return string[]
620
-     * @throws ApplicationLogicException
621
-     */
622
-    private function getRawBanTargets(User $user): array
623
-    {
624
-        $targetName = WebRequest::postString('banName');
625
-        $targetIp = WebRequest::postString('banIP');
626
-        $targetEmail = WebRequest::postString('banEmail');
627
-        $targetUseragent = WebRequest::postString('banUseragent');
628
-
629
-        // check the user is allowed to use provided targets
630
-        if (!$this->barrierTest('name', $user, 'BanType')) {
631
-            $targetName = null;
632
-        }
633
-        if (!$this->barrierTest('ip', $user, 'BanType')) {
634
-            $targetIp = null;
635
-        }
636
-        if (!$this->barrierTest('email', $user, 'BanType')) {
637
-            $targetEmail = null;
638
-        }
639
-        if (!$this->barrierTest('useragent', $user, 'BanType')) {
640
-            $targetUseragent = null;
641
-        }
642
-
643
-        // Checks whether there is a target entered to ban.
644
-        if ($targetName === null && $targetIp === null && $targetEmail === null && $targetUseragent === null) {
645
-            throw new ApplicationLogicException('You must specify a target to be banned');
646
-        }
647
-
648
-        return array($targetName, $targetIp, $targetEmail, $targetUseragent);
649
-    }
650
-
651
-    private function preloadFormForRequest(int $banRequest, string $banType, User $user): void
652
-    {
653
-        $database = $this->getDatabase();
654
-
655
-        // Attempt to resolve the correct target
656
-        /** @var Request|false $request */
657
-        $request = Request::getById($banRequest, $database);
658
-        if ($request === false) {
659
-            $this->assign('bantarget', '');
660
-
661
-            return;
662
-        }
663
-
664
-        switch ($banType) {
665
-            case 'EMail':
666
-                if ($this->barrierTest('email', $user, 'BanType')) {
667
-                    $this->assign('banEmail', $request->getEmail());
668
-                }
669
-                break;
670
-            case 'IP':
671
-                if ($this->barrierTest('ip', $user, 'BanType')) {
672
-                    $trustedIp = $this->getXffTrustProvider()->getTrustedClientIp(
673
-                        $request->getIp(),
674
-                        $request->getForwardedIp());
675
-
676
-                    $this->assign('banIP', $trustedIp);
677
-                }
678
-                break;
679
-            case 'Name':
680
-                if ($this->barrierTest('name', $user, 'BanType')) {
681
-                    $this->assign('banName', $request->getName());
682
-                }
683
-                break;
684
-            case 'UA':
685
-                if ($this->barrierTest('useragent', $user, 'BanType')) {
686
-                    $this->assign('banUseragent', $request->getEmail());
687
-                }
688
-                break;
689
-        }
690
-    }
600
+	/**
601
+	 * Returns the validated ban visibility from WebRequest
602
+	 *
603
+	 * @throws ApplicationLogicException
604
+	 */
605
+	private function getBanVisibility(): string
606
+	{
607
+		$visibility = WebRequest::postString('banVisibility');
608
+		if ($visibility !== 'user' && $visibility !== 'admin' && $visibility !== 'checkuser') {
609
+			throw new ApplicationLogicException('Invalid ban visibility');
610
+		}
611
+
612
+		return $visibility;
613
+	}
614
+
615
+	/**
616
+	 * Returns array of [username, ip, email, ua] as ban targets from WebRequest,
617
+	 * filtered for whether the user is allowed to set bans including those types.
618
+	 *
619
+	 * @return string[]
620
+	 * @throws ApplicationLogicException
621
+	 */
622
+	private function getRawBanTargets(User $user): array
623
+	{
624
+		$targetName = WebRequest::postString('banName');
625
+		$targetIp = WebRequest::postString('banIP');
626
+		$targetEmail = WebRequest::postString('banEmail');
627
+		$targetUseragent = WebRequest::postString('banUseragent');
628
+
629
+		// check the user is allowed to use provided targets
630
+		if (!$this->barrierTest('name', $user, 'BanType')) {
631
+			$targetName = null;
632
+		}
633
+		if (!$this->barrierTest('ip', $user, 'BanType')) {
634
+			$targetIp = null;
635
+		}
636
+		if (!$this->barrierTest('email', $user, 'BanType')) {
637
+			$targetEmail = null;
638
+		}
639
+		if (!$this->barrierTest('useragent', $user, 'BanType')) {
640
+			$targetUseragent = null;
641
+		}
642
+
643
+		// Checks whether there is a target entered to ban.
644
+		if ($targetName === null && $targetIp === null && $targetEmail === null && $targetUseragent === null) {
645
+			throw new ApplicationLogicException('You must specify a target to be banned');
646
+		}
647
+
648
+		return array($targetName, $targetIp, $targetEmail, $targetUseragent);
649
+	}
650
+
651
+	private function preloadFormForRequest(int $banRequest, string $banType, User $user): void
652
+	{
653
+		$database = $this->getDatabase();
654
+
655
+		// Attempt to resolve the correct target
656
+		/** @var Request|false $request */
657
+		$request = Request::getById($banRequest, $database);
658
+		if ($request === false) {
659
+			$this->assign('bantarget', '');
660
+
661
+			return;
662
+		}
663
+
664
+		switch ($banType) {
665
+			case 'EMail':
666
+				if ($this->barrierTest('email', $user, 'BanType')) {
667
+					$this->assign('banEmail', $request->getEmail());
668
+				}
669
+				break;
670
+			case 'IP':
671
+				if ($this->barrierTest('ip', $user, 'BanType')) {
672
+					$trustedIp = $this->getXffTrustProvider()->getTrustedClientIp(
673
+						$request->getIp(),
674
+						$request->getForwardedIp());
675
+
676
+					$this->assign('banIP', $trustedIp);
677
+				}
678
+				break;
679
+			case 'Name':
680
+				if ($this->barrierTest('name', $user, 'BanType')) {
681
+					$this->assign('banName', $request->getName());
682
+				}
683
+				break;
684
+			case 'UA':
685
+				if ($this->barrierTest('useragent', $user, 'BanType')) {
686
+					$this->assign('banUseragent', $request->getEmail());
687
+				}
688
+				break;
689
+		}
690
+	}
691 691
 }
Please login to merge, or discard this patch.