Test Setup Failed
Push — irc-comment-visibility-fix ( 1f25c9...574aa6 )
by Michael
10:52
created
includes/Helpers/Interfaces/IOAuthProtocolHelper.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -15,53 +15,53 @@
 block discarded – undo
15 15
 
16 16
 interface IOAuthProtocolHelper
17 17
 {
18
-    /**
19
-     * @return stdClass
20
-     *
21
-     * @throws Exception
22
-     * @throws CurlException
23
-     */
24
-    public function getRequestToken();
18
+	/**
19
+	 * @return stdClass
20
+	 *
21
+	 * @throws Exception
22
+	 * @throws CurlException
23
+	 */
24
+	public function getRequestToken();
25 25
 
26
-    /**
27
-     * @param string $requestToken
28
-     *
29
-     * @return string
30
-     */
31
-    public function getAuthoriseUrl($requestToken);
26
+	/**
27
+	 * @param string $requestToken
28
+	 *
29
+	 * @return string
30
+	 */
31
+	public function getAuthoriseUrl($requestToken);
32 32
 
33
-    /**
34
-     * @param string $oauthRequestToken
35
-     * @param string $oauthRequestSecret
36
-     * @param string $oauthVerifier
37
-     *
38
-     * @return stdClass
39
-     * @throws CurlException
40
-     * @throws Exception
41
-     */
42
-    public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
33
+	/**
34
+	 * @param string $oauthRequestToken
35
+	 * @param string $oauthRequestSecret
36
+	 * @param string $oauthVerifier
37
+	 *
38
+	 * @return stdClass
39
+	 * @throws CurlException
40
+	 * @throws Exception
41
+	 */
42
+	public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
43 43
 
44
-    /**
45
-     * @param string $oauthAccessToken
46
-     * @param string $oauthAccessSecret
47
-     *
48
-     * @return stdClass
49
-     * @throws CurlException
50
-     * @throws Exception
51
-     * @throws \MediaWiki\OAuthClient\Exception
52
-     */
53
-    public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
44
+	/**
45
+	 * @param string $oauthAccessToken
46
+	 * @param string $oauthAccessSecret
47
+	 *
48
+	 * @return stdClass
49
+	 * @throws CurlException
50
+	 * @throws Exception
51
+	 * @throws \MediaWiki\OAuthClient\Exception
52
+	 */
53
+	public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
54 54
 
55
-    /**
56
-     * @param array  $apiParams    array of parameters to send to the API
57
-     * @param string $accessToken  user's access token
58
-     * @param string $accessSecret user's secret
59
-     * @param string $method       HTTP method
60
-     *
61
-     * @return stdClass
62
-     * @throws ApplicationLogicException
63
-     * @throws CurlException
64
-     * @throws Exception
65
-     */
66
-    public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
55
+	/**
56
+	 * @param array  $apiParams    array of parameters to send to the API
57
+	 * @param string $accessToken  user's access token
58
+	 * @param string $accessSecret user's secret
59
+	 * @param string $method       HTTP method
60
+	 *
61
+	 * @return stdClass
62
+	 * @throws ApplicationLogicException
63
+	 * @throws CurlException
64
+	 * @throws Exception
65
+	 */
66
+	public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
67 67
 }
68 68
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Providers/XffTrustProvider.php 1 patch
Indentation   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -22,156 +22,156 @@
 block discarded – undo
22 22
  */
23 23
 class XffTrustProvider implements IXffTrustProvider
24 24
 {
25
-    /**
26
-     * Array of IP addresses which are TRUSTED proxies
27
-     * @var string[]
28
-     */
29
-    private $trustedCache;
30
-    /**
31
-     * Array of IP addresses which are UNTRUSTED proxies
32
-     * @var string[]
33
-     */
34
-    private $untrustedCache = array();
35
-    /** @var PDOStatement */
36
-    private $trustedQuery;
37
-    /**
38
-     * @var PdoDatabase
39
-     */
40
-    private $database;
41
-
42
-    /**
43
-     * Creates a new instance of the trust provider
44
-     *
45
-     * @param string[]    $squidIpList List of IP addresses to pre-approve
46
-     * @param PdoDatabase $database
47
-     */
48
-    public function __construct($squidIpList, PdoDatabase $database)
49
-    {
50
-        $this->trustedCache = $squidIpList;
51
-        $this->database = $database;
52
-    }
53
-
54
-    /**
55
-     * Returns a value if the IP address is a trusted proxy
56
-     *
57
-     * @param string $ip
58
-     *
59
-     * @return bool
60
-     */
61
-    public function isTrusted($ip)
62
-    {
63
-        if (in_array($ip, $this->trustedCache)) {
64
-            return true;
65
-        }
66
-
67
-        if (in_array($ip, $this->untrustedCache)) {
68
-            return false;
69
-        }
70
-
71
-        if ($this->trustedQuery === null) {
72
-            $query = "SELECT COUNT(id) FROM xfftrustcache WHERE ip = :ip;";
73
-            $this->trustedQuery = $this->database->prepare($query);
74
-        }
75
-
76
-        $this->trustedQuery->execute(array(":ip" => $ip));
77
-        $result = $this->trustedQuery->fetchColumn();
78
-        $this->trustedQuery->closeCursor();
79
-
80
-        if ($result == 0) {
81
-            $this->untrustedCache[] = $ip;
82
-
83
-            return false;
84
-        }
85
-
86
-        if ($result >= 1) {
87
-            $this->trustedCache[] = $ip;
88
-
89
-            return true;
90
-        }
91
-
92
-        // something weird has happened if we've got here.
93
-        // default to untrusted.
94
-        return false;
95
-    }
96
-
97
-    /**
98
-     * Gets the last trusted IP in the proxy chain.
99
-     *
100
-     * @param string $ip      The IP address from REMOTE_ADDR
101
-     * @param string $proxyIp The contents of the XFF header.
102
-     *
103
-     * @return string Trusted source IP address
104
-     */
105
-    public function getTrustedClientIp($ip, $proxyIp)
106
-    {
107
-        $clientIpAddress = $ip;
108
-        if ($proxyIp) {
109
-            $ipList = explode(",", $proxyIp);
110
-            $ipList[] = $clientIpAddress;
111
-            $ipList = array_reverse($ipList);
112
-
113
-            foreach ($ipList as $ipNumber => $ipAddress) {
114
-                if ($this->isTrusted(trim($ipAddress)) && $ipNumber < (count($ipList) - 1)) {
115
-                    continue;
116
-                }
117
-
118
-                $clientIpAddress = $ipAddress;
119
-                break;
120
-            }
121
-        }
122
-
123
-        return trim($clientIpAddress);
124
-    }
125
-
126
-    /**
127
-     * Takes an array( "low" => "high" ) values, and returns true if $needle is in at least one of them.
128
-     *
129
-     * @param array  $haystack
130
-     * @param string $ip
131
-     *
132
-     * @return bool
133
-     */
134
-    public function ipInRange($haystack, $ip)
135
-    {
136
-        $needle = ip2long($ip);
137
-
138
-        foreach ($haystack as $low => $high) {
139
-            if (ip2long($low) <= $needle && ip2long($high) >= $needle) {
140
-                return true;
141
-            }
142
-        }
143
-
144
-        return false;
145
-    }
146
-
147
-    /**
148
-     * Explodes a CIDR range into an array of addresses
149
-     *
150
-     * @param string $range A CIDR-format range
151
-     *
152
-     * @return array An array containing every IP address in the range
153
-     */
154
-    public function explodeCidr($range)
155
-    {
156
-        $cidrData = explode('/', $range);
157
-
158
-        if (!isset($cidrData[1])) {
159
-            return array($range);
160
-        }
161
-
162
-        $blow = (
163
-            str_pad(decbin(ip2long($cidrData[0])), 32, "0", STR_PAD_LEFT) &
164
-            str_pad(str_pad("", $cidrData[1], "1"), 32, "0")
165
-        );
166
-        $bhigh = ($blow | str_pad(str_pad("", $cidrData[1], "0"), 32, "1"));
167
-
168
-        $list = array();
169
-
170
-        $bindecBHigh = bindec($bhigh);
171
-        for ($x = bindec($blow); $x <= $bindecBHigh; $x++) {
172
-            $list[] = long2ip($x);
173
-        }
174
-
175
-        return $list;
176
-    }
25
+	/**
26
+	 * Array of IP addresses which are TRUSTED proxies
27
+	 * @var string[]
28
+	 */
29
+	private $trustedCache;
30
+	/**
31
+	 * Array of IP addresses which are UNTRUSTED proxies
32
+	 * @var string[]
33
+	 */
34
+	private $untrustedCache = array();
35
+	/** @var PDOStatement */
36
+	private $trustedQuery;
37
+	/**
38
+	 * @var PdoDatabase
39
+	 */
40
+	private $database;
41
+
42
+	/**
43
+	 * Creates a new instance of the trust provider
44
+	 *
45
+	 * @param string[]    $squidIpList List of IP addresses to pre-approve
46
+	 * @param PdoDatabase $database
47
+	 */
48
+	public function __construct($squidIpList, PdoDatabase $database)
49
+	{
50
+		$this->trustedCache = $squidIpList;
51
+		$this->database = $database;
52
+	}
53
+
54
+	/**
55
+	 * Returns a value if the IP address is a trusted proxy
56
+	 *
57
+	 * @param string $ip
58
+	 *
59
+	 * @return bool
60
+	 */
61
+	public function isTrusted($ip)
62
+	{
63
+		if (in_array($ip, $this->trustedCache)) {
64
+			return true;
65
+		}
66
+
67
+		if (in_array($ip, $this->untrustedCache)) {
68
+			return false;
69
+		}
70
+
71
+		if ($this->trustedQuery === null) {
72
+			$query = "SELECT COUNT(id) FROM xfftrustcache WHERE ip = :ip;";
73
+			$this->trustedQuery = $this->database->prepare($query);
74
+		}
75
+
76
+		$this->trustedQuery->execute(array(":ip" => $ip));
77
+		$result = $this->trustedQuery->fetchColumn();
78
+		$this->trustedQuery->closeCursor();
79
+
80
+		if ($result == 0) {
81
+			$this->untrustedCache[] = $ip;
82
+
83
+			return false;
84
+		}
85
+
86
+		if ($result >= 1) {
87
+			$this->trustedCache[] = $ip;
88
+
89
+			return true;
90
+		}
91
+
92
+		// something weird has happened if we've got here.
93
+		// default to untrusted.
94
+		return false;
95
+	}
96
+
97
+	/**
98
+	 * Gets the last trusted IP in the proxy chain.
99
+	 *
100
+	 * @param string $ip      The IP address from REMOTE_ADDR
101
+	 * @param string $proxyIp The contents of the XFF header.
102
+	 *
103
+	 * @return string Trusted source IP address
104
+	 */
105
+	public function getTrustedClientIp($ip, $proxyIp)
106
+	{
107
+		$clientIpAddress = $ip;
108
+		if ($proxyIp) {
109
+			$ipList = explode(",", $proxyIp);
110
+			$ipList[] = $clientIpAddress;
111
+			$ipList = array_reverse($ipList);
112
+
113
+			foreach ($ipList as $ipNumber => $ipAddress) {
114
+				if ($this->isTrusted(trim($ipAddress)) && $ipNumber < (count($ipList) - 1)) {
115
+					continue;
116
+				}
117
+
118
+				$clientIpAddress = $ipAddress;
119
+				break;
120
+			}
121
+		}
122
+
123
+		return trim($clientIpAddress);
124
+	}
125
+
126
+	/**
127
+	 * Takes an array( "low" => "high" ) values, and returns true if $needle is in at least one of them.
128
+	 *
129
+	 * @param array  $haystack
130
+	 * @param string $ip
131
+	 *
132
+	 * @return bool
133
+	 */
134
+	public function ipInRange($haystack, $ip)
135
+	{
136
+		$needle = ip2long($ip);
137
+
138
+		foreach ($haystack as $low => $high) {
139
+			if (ip2long($low) <= $needle && ip2long($high) >= $needle) {
140
+				return true;
141
+			}
142
+		}
143
+
144
+		return false;
145
+	}
146
+
147
+	/**
148
+	 * Explodes a CIDR range into an array of addresses
149
+	 *
150
+	 * @param string $range A CIDR-format range
151
+	 *
152
+	 * @return array An array containing every IP address in the range
153
+	 */
154
+	public function explodeCidr($range)
155
+	{
156
+		$cidrData = explode('/', $range);
157
+
158
+		if (!isset($cidrData[1])) {
159
+			return array($range);
160
+		}
161
+
162
+		$blow = (
163
+			str_pad(decbin(ip2long($cidrData[0])), 32, "0", STR_PAD_LEFT) &
164
+			str_pad(str_pad("", $cidrData[1], "1"), 32, "0")
165
+		);
166
+		$bhigh = ($blow | str_pad(str_pad("", $cidrData[1], "0"), 32, "1"));
167
+
168
+		$list = array();
169
+
170
+		$bindecBHigh = bindec($bhigh);
171
+		for ($x = bindec($blow); $x <= $bindecBHigh; $x++) {
172
+			$list[] = long2ip($x);
173
+		}
174
+
175
+		return $list;
176
+	}
177 177
 }
Please login to merge, or discard this patch.
smarty-plugins/function.defaultsort.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -16,24 +16,24 @@
 block discarded – undo
16 16
  */
17 17
 function smarty_function_defaultsort($params, Smarty_Internal_Template $template)
18 18
 {
19
-    if (empty($params['id'])) {
20
-        return "";
21
-    }
19
+	if (empty($params['id'])) {
20
+		return "";
21
+	}
22 22
 
23
-    $attr = 'data-sortname="' . htmlspecialchars($params['id'], ENT_QUOTES) . '"';
23
+	$attr = 'data-sortname="' . htmlspecialchars($params['id'], ENT_QUOTES) . '"';
24 24
 
25
-    if (empty($params['req'])) {
26
-        return $attr;
27
-    }
25
+	if (empty($params['req'])) {
26
+		return $attr;
27
+	}
28 28
 
29
-    if ($params['dir'] !== 'asc' && $params['dir'] !== 'desc') {
30
-        $params['dir'] = 'asc';
31
-    }
29
+	if ($params['dir'] !== 'asc' && $params['dir'] !== 'desc') {
30
+		$params['dir'] = 'asc';
31
+	}
32 32
 
33
-    $sort = '';
34
-    if ($params['req'] === $params['id']) {
35
-        $sort = ' data-defaultsort="' . htmlspecialchars($params['dir'], ENT_QUOTES) . '"';
36
-    }
33
+	$sort = '';
34
+	if ($params['req'] === $params['id']) {
35
+		$sort = ' data-defaultsort="' . htmlspecialchars($params['dir'], ENT_QUOTES) . '"';
36
+	}
37 37
 
38
-    return $attr . $sort;
38
+	return $attr . $sort;
39 39
 }
40 40
\ No newline at end of file
Please login to merge, or discard this patch.
smarty-plugins/modifier.timespan.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -16,78 +16,78 @@
 block discarded – undo
16 16
  */
17 17
 function smarty_modifier_timespan($input)
18 18
 {
19
-    $remaining = abs(floor($input));
19
+	$remaining = abs(floor($input));
20 20
 
21
-    $seconds = $remaining % 60;
22
-    $remaining = $remaining - $seconds;
21
+	$seconds = $remaining % 60;
22
+	$remaining = $remaining - $seconds;
23 23
 
24
-    $minutes = $remaining % (60 * 60);
25
-    $remaining = $remaining - $minutes;
26
-    $minutes /= 60;
24
+	$minutes = $remaining % (60 * 60);
25
+	$remaining = $remaining - $minutes;
26
+	$minutes /= 60;
27 27
 
28
-    $hours = $remaining % (60 * 60 * 24);
29
-    $remaining = $remaining - $hours;
30
-    $hours /= (60 * 60);
28
+	$hours = $remaining % (60 * 60 * 24);
29
+	$remaining = $remaining - $hours;
30
+	$hours /= (60 * 60);
31 31
 
32
-    $days = $remaining % (60 * 60 * 24 * 7);
33
-    $weeks = $remaining - $days;
34
-    $days /= (60 * 60 * 24);
35
-    $weeks /= (60 * 60 * 24 * 7);
32
+	$days = $remaining % (60 * 60 * 24 * 7);
33
+	$weeks = $remaining - $days;
34
+	$days /= (60 * 60 * 24);
35
+	$weeks /= (60 * 60 * 24 * 7);
36 36
 
37
-    $stringval = '';
38
-    $trip = false;
37
+	$stringval = '';
38
+	$trip = false;
39 39
 
40
-    if ($weeks > 0) {
41
-        $stringval .= "${weeks}w ";
42
-    }
40
+	if ($weeks > 0) {
41
+		$stringval .= "${weeks}w ";
42
+	}
43 43
 
44
-    if ($days > 0) {
45
-        if ($stringval !== '') {
46
-            $trip = true;
47
-        }
44
+	if ($days > 0) {
45
+		if ($stringval !== '') {
46
+			$trip = true;
47
+		}
48 48
 
49
-        $stringval .= "${days}d ";
49
+		$stringval .= "${days}d ";
50 50
 
51
-        if ($trip) {
52
-            return trim($stringval);
53
-        }
54
-    }
51
+		if ($trip) {
52
+			return trim($stringval);
53
+		}
54
+	}
55 55
 
56
-    if ($hours > 0) {
57
-        if ($stringval !== '') {
58
-            $trip = true;
59
-        }
56
+	if ($hours > 0) {
57
+		if ($stringval !== '') {
58
+			$trip = true;
59
+		}
60 60
 
61
-        $stringval .= "${hours}h ";
61
+		$stringval .= "${hours}h ";
62 62
 
63
-        if ($trip) {
64
-            return trim($stringval);
65
-        }
66
-    }
63
+		if ($trip) {
64
+			return trim($stringval);
65
+		}
66
+	}
67 67
 
68
-    if ($minutes > 0) {
69
-        if ($stringval !== '') {
70
-            $trip = true;
71
-        }
68
+	if ($minutes > 0) {
69
+		if ($stringval !== '') {
70
+			$trip = true;
71
+		}
72 72
 
73
-        $stringval .= "${minutes}m ";
73
+		$stringval .= "${minutes}m ";
74 74
 
75
-        if ($trip) {
76
-            return trim($stringval);
77
-        }
78
-    }
75
+		if ($trip) {
76
+			return trim($stringval);
77
+		}
78
+	}
79 79
 
80
-    if ($seconds > 0) {
81
-        if ($stringval !== '') {
82
-            $trip = true;
83
-        }
80
+	if ($seconds > 0) {
81
+		if ($stringval !== '') {
82
+			$trip = true;
83
+		}
84 84
 
85
-        $stringval .= "${seconds}s ";
85
+		$stringval .= "${seconds}s ";
86 86
 
87
-        if ($trip) {
88
-            return trim($stringval);
89
-        }
90
-    }
87
+		if ($trip) {
88
+			return trim($stringval);
89
+		}
90
+	}
91 91
 
92
-    return trim($stringval);
92
+	return trim($stringval);
93 93
 }
94 94
\ No newline at end of file
Please login to merge, or discard this patch.
smarty-plugins/modifier.relativedate.php 1 patch
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -16,73 +16,73 @@
 block discarded – undo
16 16
  */
17 17
 function smarty_modifier_relativedate($input)
18 18
 {
19
-    $now = new DateTime();
19
+	$now = new DateTime();
20 20
 
21
-    if (gettype($input) === 'object'
22
-        && (get_class($input) === DateTime::class || get_class($input) === DateTimeImmutable::class)
23
-    ) {
24
-        $then = $input;
25
-    }
26
-    else {
27
-        try {
28
-            $then = new DateTime($input);
29
-        }
30
-        catch (Exception $ex) {
31
-            return $input;
32
-        }
33
-    }
21
+	if (gettype($input) === 'object'
22
+		&& (get_class($input) === DateTime::class || get_class($input) === DateTimeImmutable::class)
23
+	) {
24
+		$then = $input;
25
+	}
26
+	else {
27
+		try {
28
+			$then = new DateTime($input);
29
+		}
30
+		catch (Exception $ex) {
31
+			return $input;
32
+		}
33
+	}
34 34
 
35
-    $secs = $now->getTimestamp() - $then->getTimestamp();
35
+	$secs = $now->getTimestamp() - $then->getTimestamp();
36 36
 
37
-    $second = 1;
38
-    $minute = 60 * $second;
39
-    $minuteCut = 60 * $second;
40
-    $hour = 60 * $minute;
41
-    $hourCut = 90 * $minute;
42
-    $day = 24 * $hour;
43
-    $dayCut = 48 * $hour;
44
-    $week = 7 * $day;
45
-    $weekCut = 14 * $day;
46
-    $month = 30 * $day;
47
-    $monthCut = 60 * $day;
48
-    $year = 365 * $day;
49
-    $yearCut = $year * 2;
37
+	$second = 1;
38
+	$minute = 60 * $second;
39
+	$minuteCut = 60 * $second;
40
+	$hour = 60 * $minute;
41
+	$hourCut = 90 * $minute;
42
+	$day = 24 * $hour;
43
+	$dayCut = 48 * $hour;
44
+	$week = 7 * $day;
45
+	$weekCut = 14 * $day;
46
+	$month = 30 * $day;
47
+	$monthCut = 60 * $day;
48
+	$year = 365 * $day;
49
+	$yearCut = $year * 2;
50 50
 
51
-    $pluralise = true;
51
+	$pluralise = true;
52 52
 
53
-    if ($secs <= 10) {
54
-        $output = "just now";
55
-        $pluralise = false;
56
-    }
57
-    elseif ($secs > 10 && $secs < $minuteCut) {
58
-        $output = round($secs / $second) . " second";
59
-    }
60
-    elseif ($secs >= $minuteCut && $secs < $hourCut) {
61
-        $output = round($secs / $minute) . " minute";
62
-    }
63
-    elseif ($secs >= $hourCut && $secs < $dayCut) {
64
-        $output = round($secs / $hour) . " hour";
65
-    }
66
-    elseif ($secs >= $dayCut && $secs < $weekCut) {
67
-        $output = round($secs / $day) . " day";
68
-    }
69
-    elseif ($secs >= $weekCut && $secs < $monthCut) {
70
-        $output = round($secs / $week) . " week";
71
-    }
72
-    elseif ($secs >= $monthCut && $secs < $yearCut) {
73
-        $output = round($secs / $month) . " month";
74
-    }
75
-    elseif ($secs >= $yearCut && $secs < $year * 10) {
76
-        $output = round($secs / $year) . " year";
77
-    }
78
-    else {
79
-        $output = "a long time ago";
80
-        $pluralise = false;
81
-    }
53
+	if ($secs <= 10) {
54
+		$output = "just now";
55
+		$pluralise = false;
56
+	}
57
+	elseif ($secs > 10 && $secs < $minuteCut) {
58
+		$output = round($secs / $second) . " second";
59
+	}
60
+	elseif ($secs >= $minuteCut && $secs < $hourCut) {
61
+		$output = round($secs / $minute) . " minute";
62
+	}
63
+	elseif ($secs >= $hourCut && $secs < $dayCut) {
64
+		$output = round($secs / $hour) . " hour";
65
+	}
66
+	elseif ($secs >= $dayCut && $secs < $weekCut) {
67
+		$output = round($secs / $day) . " day";
68
+	}
69
+	elseif ($secs >= $weekCut && $secs < $monthCut) {
70
+		$output = round($secs / $week) . " week";
71
+	}
72
+	elseif ($secs >= $monthCut && $secs < $yearCut) {
73
+		$output = round($secs / $month) . " month";
74
+	}
75
+	elseif ($secs >= $yearCut && $secs < $year * 10) {
76
+		$output = round($secs / $year) . " year";
77
+	}
78
+	else {
79
+		$output = "a long time ago";
80
+		$pluralise = false;
81
+	}
82 82
 
83
-    if ($pluralise) {
84
-        $output = (substr($output, 0, 2) <> "1 ") ? $output . "s ago" : $output . " ago";
85
-    }
83
+	if ($pluralise) {
84
+		$output = (substr($output, 0, 2) <> "1 ") ? $output . "s ago" : $output . " ago";
85
+	}
86 86
 
87
-    return $output;
87
+	return $output;
88 88
 }
Please login to merge, or discard this patch.
includes/Validation/ValidationError.php 1 patch
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -12,102 +12,102 @@
 block discarded – undo
12 12
 
13 13
 class ValidationError
14 14
 {
15
-    const NAME_EMPTY = "name_empty";
16
-    const NAME_TOO_LONG = "name_too_long";
17
-    const NAME_EXISTS = "name_exists";
18
-    const NAME_EXISTS_SUL = "name_exists_sul";
19
-    const NAME_NUMONLY = "name_numonly";
20
-    const NAME_INVALIDCHAR = "name_invalidchar";
21
-    const NAME_SANITISED = "name_sanitised";
22
-    const NAME_IP = "name_ip";
23
-    const EMAIL_EMPTY = "email_empty";
24
-    const EMAIL_WIKIMEDIA = "email_wikimedia";
25
-    const EMAIL_INVALID = "email_invalid";
26
-    const EMAIL_MISMATCH = "email_mismatch";
27
-    const OPEN_REQUEST_NAME = "open_request_name";
28
-    const BANNED = "banned";
29
-    const BANNED_TOR = "banned_tor";
30
-    /**
31
-     * @var array Error text for the above
32
-     */
33
-    private static $errorText = array(
34
-        self::NAME_EMPTY        => 'You\'ve not chosen a username!',
35
-        self::NAME_TOO_LONG     => 'Your chosen username is too long. Please choose a shorter one.',
36
-        self::NAME_EXISTS       => 'I\'m sorry, but the username you selected is already taken. Please try another. '
37
-            . 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
38
-            . '[[User:example]] would become [[User:Example]].',
39
-        self::NAME_EXISTS_SUL   => 'I\'m sorry, but the username you selected is already taken. Please try another. '
40
-            . 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
41
-            . '[[User:example]] would become [[User:Example]].',
42
-        self::NAME_NUMONLY      => 'The username you chose is invalid: it consists entirely of numbers. Please retry '
43
-            . 'with a valid username.',
44
-        self::NAME_INVALIDCHAR  => 'There appears to be an invalid character in your username. Please note that the '
45
-            . 'following characters are not allowed: <code># @ / &lt; &gt; [ ] | { }</code>',
46
-        self::NAME_SANITISED    => 'Your requested username has been automatically adjusted due to technical '
47
-            . 'restrictions. Underscores have been replaced with spaces, and the first character has been capitalised.',
48
-        self::NAME_IP           => 'The username you chose is invalid: it cannot be an IP address',
49
-        self::EMAIL_EMPTY       => 'You need to supply an email address.',
50
-        self::EMAIL_WIKIMEDIA   => 'Please provide your email address here.',
51
-        self::EMAIL_INVALID     => 'Invalid E-mail address supplied. Please check you entered it correctly.',
52
-        self::EMAIL_MISMATCH    => 'The email addresses you entered do not match. Please try again.',
53
-        self::OPEN_REQUEST_NAME => 'There is already an open request with this name in this system.',
54
-        self::BANNED            => 'Sorry, you are currently banned from requesting accounts using this tool.',
55
-        self::BANNED_TOR        => 'Tor exit nodes are currently banned from using this tool due to excessive abuse. '
56
-            . 'Please note that Tor is also currently banned from editing Wikipedia.',
57
-    );
58
-    /**
59
-     * Summary of $errorCode
60
-     * @var string
61
-     */
62
-    private $errorCode;
63
-    /**
64
-     * Summary of $isError
65
-     * @var bool
66
-     */
67
-    private $isError;
15
+	const NAME_EMPTY = "name_empty";
16
+	const NAME_TOO_LONG = "name_too_long";
17
+	const NAME_EXISTS = "name_exists";
18
+	const NAME_EXISTS_SUL = "name_exists_sul";
19
+	const NAME_NUMONLY = "name_numonly";
20
+	const NAME_INVALIDCHAR = "name_invalidchar";
21
+	const NAME_SANITISED = "name_sanitised";
22
+	const NAME_IP = "name_ip";
23
+	const EMAIL_EMPTY = "email_empty";
24
+	const EMAIL_WIKIMEDIA = "email_wikimedia";
25
+	const EMAIL_INVALID = "email_invalid";
26
+	const EMAIL_MISMATCH = "email_mismatch";
27
+	const OPEN_REQUEST_NAME = "open_request_name";
28
+	const BANNED = "banned";
29
+	const BANNED_TOR = "banned_tor";
30
+	/**
31
+	 * @var array Error text for the above
32
+	 */
33
+	private static $errorText = array(
34
+		self::NAME_EMPTY        => 'You\'ve not chosen a username!',
35
+		self::NAME_TOO_LONG     => 'Your chosen username is too long. Please choose a shorter one.',
36
+		self::NAME_EXISTS       => 'I\'m sorry, but the username you selected is already taken. Please try another. '
37
+			. 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
38
+			. '[[User:example]] would become [[User:Example]].',
39
+		self::NAME_EXISTS_SUL   => 'I\'m sorry, but the username you selected is already taken. Please try another. '
40
+			. 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
41
+			. '[[User:example]] would become [[User:Example]].',
42
+		self::NAME_NUMONLY      => 'The username you chose is invalid: it consists entirely of numbers. Please retry '
43
+			. 'with a valid username.',
44
+		self::NAME_INVALIDCHAR  => 'There appears to be an invalid character in your username. Please note that the '
45
+			. 'following characters are not allowed: <code># @ / &lt; &gt; [ ] | { }</code>',
46
+		self::NAME_SANITISED    => 'Your requested username has been automatically adjusted due to technical '
47
+			. 'restrictions. Underscores have been replaced with spaces, and the first character has been capitalised.',
48
+		self::NAME_IP           => 'The username you chose is invalid: it cannot be an IP address',
49
+		self::EMAIL_EMPTY       => 'You need to supply an email address.',
50
+		self::EMAIL_WIKIMEDIA   => 'Please provide your email address here.',
51
+		self::EMAIL_INVALID     => 'Invalid E-mail address supplied. Please check you entered it correctly.',
52
+		self::EMAIL_MISMATCH    => 'The email addresses you entered do not match. Please try again.',
53
+		self::OPEN_REQUEST_NAME => 'There is already an open request with this name in this system.',
54
+		self::BANNED            => 'Sorry, you are currently banned from requesting accounts using this tool.',
55
+		self::BANNED_TOR        => 'Tor exit nodes are currently banned from using this tool due to excessive abuse. '
56
+			. 'Please note that Tor is also currently banned from editing Wikipedia.',
57
+	);
58
+	/**
59
+	 * Summary of $errorCode
60
+	 * @var string
61
+	 */
62
+	private $errorCode;
63
+	/**
64
+	 * Summary of $isError
65
+	 * @var bool
66
+	 */
67
+	private $isError;
68 68
 
69
-    /**
70
-     * Summary of __construct
71
-     *
72
-     * @param string $errorCode
73
-     * @param bool   $isError
74
-     */
75
-    public function __construct($errorCode, $isError = true)
76
-    {
77
-        $this->errorCode = $errorCode;
78
-        $this->isError = $isError;
79
-    }
69
+	/**
70
+	 * Summary of __construct
71
+	 *
72
+	 * @param string $errorCode
73
+	 * @param bool   $isError
74
+	 */
75
+	public function __construct($errorCode, $isError = true)
76
+	{
77
+		$this->errorCode = $errorCode;
78
+		$this->isError = $isError;
79
+	}
80 80
 
81
-    /**
82
-     * Summary of getErrorCode
83
-     * @return string
84
-     */
85
-    public function getErrorCode()
86
-    {
87
-        return $this->errorCode;
88
-    }
81
+	/**
82
+	 * Summary of getErrorCode
83
+	 * @return string
84
+	 */
85
+	public function getErrorCode()
86
+	{
87
+		return $this->errorCode;
88
+	}
89 89
 
90
-    /**
91
-     * @return string
92
-     * @throws Exception
93
-     */
94
-    public function getErrorMessage()
95
-    {
96
-        $text = self::$errorText[$this->errorCode];
90
+	/**
91
+	 * @return string
92
+	 * @throws Exception
93
+	 */
94
+	public function getErrorMessage()
95
+	{
96
+		$text = self::$errorText[$this->errorCode];
97 97
 
98
-        if ($text == null) {
99
-            throw new Exception('Unknown validation error');
100
-        }
98
+		if ($text == null) {
99
+			throw new Exception('Unknown validation error');
100
+		}
101 101
 
102
-        return $text;
103
-    }
102
+		return $text;
103
+	}
104 104
 
105
-    /**
106
-     * Summary of isError
107
-     * @return bool
108
-     */
109
-    public function isError()
110
-    {
111
-        return $this->isError;
112
-    }
105
+	/**
106
+	 * Summary of isError
107
+	 * @return bool
108
+	 */
109
+	public function isError()
110
+	{
111
+		return $this->isError;
112
+	}
113 113
 }
Please login to merge, or discard this patch.
includes/Validation/RequestValidationHelper.php 1 patch
Indentation   +425 added lines, -425 removed lines patch added patch discarded remove patch
@@ -31,429 +31,429 @@
 block discarded – undo
31 31
  */
32 32
 class RequestValidationHelper
33 33
 {
34
-    /** @var IBanHelper */
35
-    private $banHelper;
36
-    /** @var PdoDatabase */
37
-    private $database;
38
-    /** @var IAntiSpoofProvider */
39
-    private $antiSpoofProvider;
40
-    /** @var IXffTrustProvider */
41
-    private $xffTrustProvider;
42
-    /** @var HttpHelper */
43
-    private $httpHelper;
44
-    /**
45
-     * @var string
46
-     */
47
-    private $mediawikiApiEndpoint;
48
-    private $titleBlacklistEnabled;
49
-    /**
50
-     * @var TorExitProvider
51
-     */
52
-    private $torExitProvider;
53
-    /**
54
-     * @var SiteConfiguration
55
-     */
56
-    private $siteConfiguration;
57
-
58
-    private $validationRemoteTimeout = 5000;
59
-
60
-    /**
61
-     * Summary of __construct
62
-     *
63
-     * @param IBanHelper         $banHelper
64
-     * @param PdoDatabase        $database
65
-     * @param IAntiSpoofProvider $antiSpoofProvider
66
-     * @param IXffTrustProvider  $xffTrustProvider
67
-     * @param HttpHelper         $httpHelper
68
-     * @param TorExitProvider    $torExitProvider
69
-     * @param SiteConfiguration  $siteConfiguration
70
-     */
71
-    public function __construct(
72
-        IBanHelper $banHelper,
73
-        PdoDatabase $database,
74
-        IAntiSpoofProvider $antiSpoofProvider,
75
-        IXffTrustProvider $xffTrustProvider,
76
-        HttpHelper $httpHelper,
77
-        TorExitProvider $torExitProvider,
78
-        SiteConfiguration $siteConfiguration
79
-    ) {
80
-        $this->banHelper = $banHelper;
81
-        $this->database = $database;
82
-        $this->antiSpoofProvider = $antiSpoofProvider;
83
-        $this->xffTrustProvider = $xffTrustProvider;
84
-        $this->httpHelper = $httpHelper;
85
-
86
-        // FIXME: domains!
87
-        /** @var Domain $domain */
88
-        $domain = Domain::getById(1, $database);
89
-
90
-        $this->mediawikiApiEndpoint = $domain->getWikiApiPath();
91
-        $this->titleBlacklistEnabled = $siteConfiguration->getTitleBlacklistEnabled();
92
-        $this->torExitProvider = $torExitProvider;
93
-        $this->siteConfiguration = $siteConfiguration;
94
-    }
95
-
96
-    /**
97
-     * Summary of validateName
98
-     *
99
-     * @param Request $request
100
-     *
101
-     * @return ValidationError[]
102
-     */
103
-    public function validateName(Request $request)
104
-    {
105
-        $errorList = array();
106
-
107
-        // ERRORS
108
-        // name is empty
109
-        if (trim($request->getName()) == "") {
110
-            $errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_EMPTY);
111
-        }
112
-
113
-        // name is too long
114
-        if (mb_strlen(trim($request->getName())) > 500) {
115
-            $errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_TOO_LONG);
116
-        }
117
-
118
-        // username already exists
119
-        if ($this->userExists($request)) {
120
-            $errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS);
121
-        }
122
-
123
-        // username part of SUL account
124
-        if ($this->userSulExists($request)) {
125
-            // using same error slot as name exists - it's the same sort of error, and we probably only want to show one.
126
-            $errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS_SUL);
127
-        }
128
-
129
-        // username is numbers
130
-        if (preg_match("/^[0-9]+$/", $request->getName()) === 1) {
131
-            $errorList[ValidationError::NAME_NUMONLY] = new ValidationError(ValidationError::NAME_NUMONLY);
132
-        }
133
-
134
-        // username can't contain #@/<>[]|{}
135
-        if (preg_match("/[" . preg_quote("#@/<>[]|{}", "/") . "]/", $request->getName()) === 1) {
136
-            $errorList[ValidationError::NAME_INVALIDCHAR] = new ValidationError(ValidationError::NAME_INVALIDCHAR);
137
-        }
138
-
139
-        // username is an IP
140
-        if (filter_var($request->getName(), FILTER_VALIDATE_IP)) {
141
-            $errorList[ValidationError::NAME_IP] = new ValidationError(ValidationError::NAME_IP);
142
-        }
143
-
144
-        // existing non-closed request for this name
145
-        if ($this->nameRequestExists($request)) {
146
-            $errorList[ValidationError::OPEN_REQUEST_NAME] = new ValidationError(ValidationError::OPEN_REQUEST_NAME);
147
-        }
148
-
149
-        return $errorList;
150
-    }
151
-
152
-    /**
153
-     * Summary of validateEmail
154
-     *
155
-     * @param Request $request
156
-     * @param string  $emailConfirmation
157
-     *
158
-     * @return ValidationError[]
159
-     */
160
-    public function validateEmail(Request $request, $emailConfirmation)
161
-    {
162
-        $errorList = array();
163
-
164
-        // ERRORS
165
-
166
-        // email addresses must match
167
-        if ($request->getEmail() != $emailConfirmation) {
168
-            $errorList[ValidationError::EMAIL_MISMATCH] = new ValidationError(ValidationError::EMAIL_MISMATCH);
169
-        }
170
-
171
-        // email address must be validly formed
172
-        if (trim($request->getEmail()) == "") {
173
-            $errorList[ValidationError::EMAIL_EMPTY] = new ValidationError(ValidationError::EMAIL_EMPTY);
174
-        }
175
-
176
-        // email address must be validly formed
177
-        if (!filter_var($request->getEmail(), FILTER_VALIDATE_EMAIL)) {
178
-            if (trim($request->getEmail()) != "") {
179
-                $errorList[ValidationError::EMAIL_INVALID] = new ValidationError(ValidationError::EMAIL_INVALID);
180
-            }
181
-        }
182
-
183
-        // email address can't be wikimedia/wikipedia .com/org
184
-        if (preg_match('/.*@.*wiki(m.dia|p.dia)\.(org|com)/i', $request->getEmail()) === 1) {
185
-            $errorList[ValidationError::EMAIL_WIKIMEDIA] = new ValidationError(ValidationError::EMAIL_WIKIMEDIA);
186
-        }
187
-
188
-        return $errorList;
189
-    }
190
-
191
-    /**
192
-     * Summary of validateOther
193
-     *
194
-     * @param Request $request
195
-     *
196
-     * @return ValidationError[]
197
-     */
198
-    public function validateOther(Request $request)
199
-    {
200
-        $errorList = array();
201
-
202
-        $trustedIp = $this->xffTrustProvider->getTrustedClientIp($request->getIp(),
203
-            $request->getForwardedIp());
204
-
205
-        // ERRORS
206
-
207
-        // TOR nodes
208
-        if ($this->torExitProvider->isTorExit($trustedIp)) {
209
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED_TOR);
210
-        }
211
-
212
-        // Bans
213
-        if ($this->banHelper->isBlockBanned($request)) {
214
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
215
-        }
216
-
217
-        return $errorList;
218
-    }
219
-
220
-    public function postSaveValidations(Request $request)
221
-    {
222
-        // Antispoof check
223
-        $this->checkAntiSpoof($request);
224
-
225
-        // Blacklist check
226
-        $this->checkTitleBlacklist($request);
227
-
228
-        // Add comment for form override
229
-        $this->formOverride($request);
230
-
231
-        $bans = $this->banHelper->getBans($request);
232
-
233
-        foreach ($bans as $ban) {
234
-            if ($ban->getAction() == Ban::ACTION_DROP) {
235
-                $request->setStatus(RequestStatus::CLOSED);
236
-                $request->save();
237
-
238
-                Logger::closeRequest($request->getDatabase(), $request, 0, null);
239
-
240
-                $comment = new Comment();
241
-                $comment->setDatabase($this->database);
242
-                $comment->setRequest($request->getId());
243
-                $comment->setVisibility('user');
244
-                $comment->setUser(null);
245
-
246
-                $comment->setComment('Request dropped automatically due to matching rule.');
247
-                $comment->save();
248
-            }
249
-
250
-            if ($ban->getAction() == Ban::ACTION_DEFER) {
251
-                /** @var RequestQueue|false $targetQueue */
252
-                $targetQueue = RequestQueue::getById($ban->getTargetQueue(), $this->database);
253
-
254
-                if ($targetQueue === false ) {
255
-                    $comment = new Comment();
256
-                    $comment->setDatabase($this->database);
257
-                    $comment->setRequest($request->getId());
258
-                    $comment->setVisibility('user');
259
-                    $comment->setUser(null);
260
-
261
-                    $comment->setComment("This request would have been deferred automatically due to a matching rule, but the queue to defer to could not be found.");
262
-                    $comment->save();
263
-                }
264
-                else {
265
-                    $this->deferRequest($request, $targetQueue, 'Request deferred automatically due to matching rule.');
266
-                }
267
-            }
268
-        }
269
-    }
270
-
271
-    private function checkAntiSpoof(Request $request)
272
-    {
273
-        try {
274
-            if (count($this->antiSpoofProvider->getSpoofs($request->getName())) > 0) {
275
-                // If there were spoofs an Admin should handle the request.
276
-                // FIXME: domains!
277
-                $defaultQueue = RequestQueue::getDefaultQueue($this->database, 1, RequestQueue::DEFAULT_ANTISPOOF);
278
-                $this->deferRequest($request, $defaultQueue,
279
-                    'Request automatically deferred due to AntiSpoof hit');
280
-            }
281
-        }
282
-        catch (Exception $ex) {
283
-            $skippable = [
284
-                'Contains unassigned character',
285
-                'Contains incompatible mixed scripts',
286
-                'Does not contain any letters',
287
-                'Usernames must contain one or more characters',
288
-                'Usernames cannot contain characters from different writing systems',
289
-                'Usernames cannot contain the character'
290
-            ];
291
-
292
-            $skip = false;
293
-
294
-            foreach ($skippable as $s) {
295
-                if (strpos($ex->getMessage(), 'Encountered error while getting result: ' . $s) !== false) {
296
-                    $skip = true;
297
-                    break;
298
-                }
299
-            }
300
-
301
-            // Only log to disk if this *isn't* a "skippable" error.
302
-            if (!$skip) {
303
-                ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
304
-            }
305
-        }
306
-    }
307
-
308
-    private function checkTitleBlacklist(Request $request)
309
-    {
310
-        if ($this->titleBlacklistEnabled == 1) {
311
-            try {
312
-                $apiResult = $this->httpHelper->get(
313
-                    $this->mediawikiApiEndpoint,
314
-                    array(
315
-                        'action'       => 'titleblacklist',
316
-                        'tbtitle'      => $request->getName(),
317
-                        'tbaction'     => 'new-account',
318
-                        'tbnooverride' => true,
319
-                        'format'       => 'php',
320
-                    ),
321
-                    [],
322
-                    $this->validationRemoteTimeout
323
-                );
324
-
325
-                $data = unserialize($apiResult);
326
-
327
-                $requestIsOk = $data['titleblacklist']['result'] == "ok";
328
-            }
329
-            catch (CurlException $ex) {
330
-                ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
331
-
332
-                // Don't kill the request, just assume it's fine. Humans can deal with it later.
333
-                return;
334
-            }
335
-
336
-            if (!$requestIsOk) {
337
-                // FIXME: domains!
338
-                $defaultQueue = RequestQueue::getDefaultQueue($this->database, 1, RequestQueue::DEFAULT_TITLEBLACKLIST);
339
-
340
-                $this->deferRequest($request, $defaultQueue,
341
-                    'Request automatically deferred due to title blacklist hit');
342
-            }
343
-        }
344
-    }
345
-
346
-    private function userExists(Request $request)
347
-    {
348
-        try {
349
-            $userExists = $this->httpHelper->get(
350
-                $this->mediawikiApiEndpoint,
351
-                array(
352
-                    'action'  => 'query',
353
-                    'list'    => 'users',
354
-                    'ususers' => $request->getName(),
355
-                    'format'  => 'php',
356
-                ),
357
-                [],
358
-                $this->validationRemoteTimeout
359
-            );
360
-
361
-            $ue = unserialize($userExists);
362
-            if (!isset ($ue['query']['users']['0']['missing']) && isset ($ue['query']['users']['0']['userid'])) {
363
-                return true;
364
-            }
365
-        }
366
-        catch (CurlException $ex) {
367
-            ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
368
-
369
-            // Don't kill the request, just assume it's fine. Humans can deal with it later.
370
-            return false;
371
-        }
372
-
373
-        return false;
374
-    }
375
-
376
-    private function userSulExists(Request $request)
377
-    {
378
-        $requestName = $request->getName();
379
-
380
-        try {
381
-            $userExists = $this->httpHelper->get(
382
-                $this->mediawikiApiEndpoint,
383
-                array(
384
-                    'action'  => 'query',
385
-                    'meta'    => 'globaluserinfo',
386
-                    'guiuser' => $requestName,
387
-                    'format'  => 'php',
388
-                ),
389
-                [],
390
-                $this->validationRemoteTimeout
391
-            );
392
-
393
-            $ue = unserialize($userExists);
394
-            if (isset ($ue['query']['globaluserinfo']['id'])) {
395
-                return true;
396
-            }
397
-        }
398
-        catch (CurlException $ex) {
399
-            ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
400
-
401
-            // Don't kill the request, just assume it's fine. Humans can deal with it later.
402
-            return false;
403
-        }
404
-
405
-        return false;
406
-    }
407
-
408
-    /**
409
-     * Checks if a request with this name is currently open
410
-     *
411
-     * @param Request $request
412
-     *
413
-     * @return bool
414
-     */
415
-    private function nameRequestExists(Request $request)
416
-    {
417
-        $query = "SELECT COUNT(id) FROM request WHERE status != 'Closed' AND name = :name;";
418
-        $statement = $this->database->prepare($query);
419
-        $statement->execute(array(':name' => $request->getName()));
420
-
421
-        if (!$statement) {
422
-            return false;
423
-        }
424
-
425
-        return $statement->fetchColumn() > 0;
426
-    }
427
-
428
-    private function deferRequest(Request $request, RequestQueue $targetQueue, $deferComment): void
429
-    {
430
-        $request->setQueue($targetQueue->getId());
431
-        $request->save();
432
-
433
-        $logTarget = $targetQueue->getLogName();
434
-
435
-        Logger::deferRequest($this->database, $request, $logTarget);
436
-
437
-        $comment = new Comment();
438
-        $comment->setDatabase($this->database);
439
-        $comment->setRequest($request->getId());
440
-        $comment->setVisibility('user');
441
-        $comment->setUser(null);
442
-
443
-        $comment->setComment($deferComment);
444
-        $comment->save();
445
-    }
446
-
447
-    private function formOverride(Request $request)
448
-    {
449
-        $form = $request->getOriginFormObject();
450
-        if($form === null || $form->getOverrideQueue() === null) {
451
-            return;
452
-        }
453
-
454
-        /** @var RequestQueue $targetQueue */
455
-        $targetQueue = RequestQueue::getById($form->getOverrideQueue(), $request->getDatabase());
456
-
457
-        $this->deferRequest($request, $targetQueue, 'Request deferred automatically due to request submission through a request form with a default queue set.');
458
-    }
34
+	/** @var IBanHelper */
35
+	private $banHelper;
36
+	/** @var PdoDatabase */
37
+	private $database;
38
+	/** @var IAntiSpoofProvider */
39
+	private $antiSpoofProvider;
40
+	/** @var IXffTrustProvider */
41
+	private $xffTrustProvider;
42
+	/** @var HttpHelper */
43
+	private $httpHelper;
44
+	/**
45
+	 * @var string
46
+	 */
47
+	private $mediawikiApiEndpoint;
48
+	private $titleBlacklistEnabled;
49
+	/**
50
+	 * @var TorExitProvider
51
+	 */
52
+	private $torExitProvider;
53
+	/**
54
+	 * @var SiteConfiguration
55
+	 */
56
+	private $siteConfiguration;
57
+
58
+	private $validationRemoteTimeout = 5000;
59
+
60
+	/**
61
+	 * Summary of __construct
62
+	 *
63
+	 * @param IBanHelper         $banHelper
64
+	 * @param PdoDatabase        $database
65
+	 * @param IAntiSpoofProvider $antiSpoofProvider
66
+	 * @param IXffTrustProvider  $xffTrustProvider
67
+	 * @param HttpHelper         $httpHelper
68
+	 * @param TorExitProvider    $torExitProvider
69
+	 * @param SiteConfiguration  $siteConfiguration
70
+	 */
71
+	public function __construct(
72
+		IBanHelper $banHelper,
73
+		PdoDatabase $database,
74
+		IAntiSpoofProvider $antiSpoofProvider,
75
+		IXffTrustProvider $xffTrustProvider,
76
+		HttpHelper $httpHelper,
77
+		TorExitProvider $torExitProvider,
78
+		SiteConfiguration $siteConfiguration
79
+	) {
80
+		$this->banHelper = $banHelper;
81
+		$this->database = $database;
82
+		$this->antiSpoofProvider = $antiSpoofProvider;
83
+		$this->xffTrustProvider = $xffTrustProvider;
84
+		$this->httpHelper = $httpHelper;
85
+
86
+		// FIXME: domains!
87
+		/** @var Domain $domain */
88
+		$domain = Domain::getById(1, $database);
89
+
90
+		$this->mediawikiApiEndpoint = $domain->getWikiApiPath();
91
+		$this->titleBlacklistEnabled = $siteConfiguration->getTitleBlacklistEnabled();
92
+		$this->torExitProvider = $torExitProvider;
93
+		$this->siteConfiguration = $siteConfiguration;
94
+	}
95
+
96
+	/**
97
+	 * Summary of validateName
98
+	 *
99
+	 * @param Request $request
100
+	 *
101
+	 * @return ValidationError[]
102
+	 */
103
+	public function validateName(Request $request)
104
+	{
105
+		$errorList = array();
106
+
107
+		// ERRORS
108
+		// name is empty
109
+		if (trim($request->getName()) == "") {
110
+			$errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_EMPTY);
111
+		}
112
+
113
+		// name is too long
114
+		if (mb_strlen(trim($request->getName())) > 500) {
115
+			$errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_TOO_LONG);
116
+		}
117
+
118
+		// username already exists
119
+		if ($this->userExists($request)) {
120
+			$errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS);
121
+		}
122
+
123
+		// username part of SUL account
124
+		if ($this->userSulExists($request)) {
125
+			// using same error slot as name exists - it's the same sort of error, and we probably only want to show one.
126
+			$errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS_SUL);
127
+		}
128
+
129
+		// username is numbers
130
+		if (preg_match("/^[0-9]+$/", $request->getName()) === 1) {
131
+			$errorList[ValidationError::NAME_NUMONLY] = new ValidationError(ValidationError::NAME_NUMONLY);
132
+		}
133
+
134
+		// username can't contain #@/<>[]|{}
135
+		if (preg_match("/[" . preg_quote("#@/<>[]|{}", "/") . "]/", $request->getName()) === 1) {
136
+			$errorList[ValidationError::NAME_INVALIDCHAR] = new ValidationError(ValidationError::NAME_INVALIDCHAR);
137
+		}
138
+
139
+		// username is an IP
140
+		if (filter_var($request->getName(), FILTER_VALIDATE_IP)) {
141
+			$errorList[ValidationError::NAME_IP] = new ValidationError(ValidationError::NAME_IP);
142
+		}
143
+
144
+		// existing non-closed request for this name
145
+		if ($this->nameRequestExists($request)) {
146
+			$errorList[ValidationError::OPEN_REQUEST_NAME] = new ValidationError(ValidationError::OPEN_REQUEST_NAME);
147
+		}
148
+
149
+		return $errorList;
150
+	}
151
+
152
+	/**
153
+	 * Summary of validateEmail
154
+	 *
155
+	 * @param Request $request
156
+	 * @param string  $emailConfirmation
157
+	 *
158
+	 * @return ValidationError[]
159
+	 */
160
+	public function validateEmail(Request $request, $emailConfirmation)
161
+	{
162
+		$errorList = array();
163
+
164
+		// ERRORS
165
+
166
+		// email addresses must match
167
+		if ($request->getEmail() != $emailConfirmation) {
168
+			$errorList[ValidationError::EMAIL_MISMATCH] = new ValidationError(ValidationError::EMAIL_MISMATCH);
169
+		}
170
+
171
+		// email address must be validly formed
172
+		if (trim($request->getEmail()) == "") {
173
+			$errorList[ValidationError::EMAIL_EMPTY] = new ValidationError(ValidationError::EMAIL_EMPTY);
174
+		}
175
+
176
+		// email address must be validly formed
177
+		if (!filter_var($request->getEmail(), FILTER_VALIDATE_EMAIL)) {
178
+			if (trim($request->getEmail()) != "") {
179
+				$errorList[ValidationError::EMAIL_INVALID] = new ValidationError(ValidationError::EMAIL_INVALID);
180
+			}
181
+		}
182
+
183
+		// email address can't be wikimedia/wikipedia .com/org
184
+		if (preg_match('/.*@.*wiki(m.dia|p.dia)\.(org|com)/i', $request->getEmail()) === 1) {
185
+			$errorList[ValidationError::EMAIL_WIKIMEDIA] = new ValidationError(ValidationError::EMAIL_WIKIMEDIA);
186
+		}
187
+
188
+		return $errorList;
189
+	}
190
+
191
+	/**
192
+	 * Summary of validateOther
193
+	 *
194
+	 * @param Request $request
195
+	 *
196
+	 * @return ValidationError[]
197
+	 */
198
+	public function validateOther(Request $request)
199
+	{
200
+		$errorList = array();
201
+
202
+		$trustedIp = $this->xffTrustProvider->getTrustedClientIp($request->getIp(),
203
+			$request->getForwardedIp());
204
+
205
+		// ERRORS
206
+
207
+		// TOR nodes
208
+		if ($this->torExitProvider->isTorExit($trustedIp)) {
209
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED_TOR);
210
+		}
211
+
212
+		// Bans
213
+		if ($this->banHelper->isBlockBanned($request)) {
214
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
215
+		}
216
+
217
+		return $errorList;
218
+	}
219
+
220
+	public function postSaveValidations(Request $request)
221
+	{
222
+		// Antispoof check
223
+		$this->checkAntiSpoof($request);
224
+
225
+		// Blacklist check
226
+		$this->checkTitleBlacklist($request);
227
+
228
+		// Add comment for form override
229
+		$this->formOverride($request);
230
+
231
+		$bans = $this->banHelper->getBans($request);
232
+
233
+		foreach ($bans as $ban) {
234
+			if ($ban->getAction() == Ban::ACTION_DROP) {
235
+				$request->setStatus(RequestStatus::CLOSED);
236
+				$request->save();
237
+
238
+				Logger::closeRequest($request->getDatabase(), $request, 0, null);
239
+
240
+				$comment = new Comment();
241
+				$comment->setDatabase($this->database);
242
+				$comment->setRequest($request->getId());
243
+				$comment->setVisibility('user');
244
+				$comment->setUser(null);
245
+
246
+				$comment->setComment('Request dropped automatically due to matching rule.');
247
+				$comment->save();
248
+			}
249
+
250
+			if ($ban->getAction() == Ban::ACTION_DEFER) {
251
+				/** @var RequestQueue|false $targetQueue */
252
+				$targetQueue = RequestQueue::getById($ban->getTargetQueue(), $this->database);
253
+
254
+				if ($targetQueue === false ) {
255
+					$comment = new Comment();
256
+					$comment->setDatabase($this->database);
257
+					$comment->setRequest($request->getId());
258
+					$comment->setVisibility('user');
259
+					$comment->setUser(null);
260
+
261
+					$comment->setComment("This request would have been deferred automatically due to a matching rule, but the queue to defer to could not be found.");
262
+					$comment->save();
263
+				}
264
+				else {
265
+					$this->deferRequest($request, $targetQueue, 'Request deferred automatically due to matching rule.');
266
+				}
267
+			}
268
+		}
269
+	}
270
+
271
+	private function checkAntiSpoof(Request $request)
272
+	{
273
+		try {
274
+			if (count($this->antiSpoofProvider->getSpoofs($request->getName())) > 0) {
275
+				// If there were spoofs an Admin should handle the request.
276
+				// FIXME: domains!
277
+				$defaultQueue = RequestQueue::getDefaultQueue($this->database, 1, RequestQueue::DEFAULT_ANTISPOOF);
278
+				$this->deferRequest($request, $defaultQueue,
279
+					'Request automatically deferred due to AntiSpoof hit');
280
+			}
281
+		}
282
+		catch (Exception $ex) {
283
+			$skippable = [
284
+				'Contains unassigned character',
285
+				'Contains incompatible mixed scripts',
286
+				'Does not contain any letters',
287
+				'Usernames must contain one or more characters',
288
+				'Usernames cannot contain characters from different writing systems',
289
+				'Usernames cannot contain the character'
290
+			];
291
+
292
+			$skip = false;
293
+
294
+			foreach ($skippable as $s) {
295
+				if (strpos($ex->getMessage(), 'Encountered error while getting result: ' . $s) !== false) {
296
+					$skip = true;
297
+					break;
298
+				}
299
+			}
300
+
301
+			// Only log to disk if this *isn't* a "skippable" error.
302
+			if (!$skip) {
303
+				ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
304
+			}
305
+		}
306
+	}
307
+
308
+	private function checkTitleBlacklist(Request $request)
309
+	{
310
+		if ($this->titleBlacklistEnabled == 1) {
311
+			try {
312
+				$apiResult = $this->httpHelper->get(
313
+					$this->mediawikiApiEndpoint,
314
+					array(
315
+						'action'       => 'titleblacklist',
316
+						'tbtitle'      => $request->getName(),
317
+						'tbaction'     => 'new-account',
318
+						'tbnooverride' => true,
319
+						'format'       => 'php',
320
+					),
321
+					[],
322
+					$this->validationRemoteTimeout
323
+				);
324
+
325
+				$data = unserialize($apiResult);
326
+
327
+				$requestIsOk = $data['titleblacklist']['result'] == "ok";
328
+			}
329
+			catch (CurlException $ex) {
330
+				ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
331
+
332
+				// Don't kill the request, just assume it's fine. Humans can deal with it later.
333
+				return;
334
+			}
335
+
336
+			if (!$requestIsOk) {
337
+				// FIXME: domains!
338
+				$defaultQueue = RequestQueue::getDefaultQueue($this->database, 1, RequestQueue::DEFAULT_TITLEBLACKLIST);
339
+
340
+				$this->deferRequest($request, $defaultQueue,
341
+					'Request automatically deferred due to title blacklist hit');
342
+			}
343
+		}
344
+	}
345
+
346
+	private function userExists(Request $request)
347
+	{
348
+		try {
349
+			$userExists = $this->httpHelper->get(
350
+				$this->mediawikiApiEndpoint,
351
+				array(
352
+					'action'  => 'query',
353
+					'list'    => 'users',
354
+					'ususers' => $request->getName(),
355
+					'format'  => 'php',
356
+				),
357
+				[],
358
+				$this->validationRemoteTimeout
359
+			);
360
+
361
+			$ue = unserialize($userExists);
362
+			if (!isset ($ue['query']['users']['0']['missing']) && isset ($ue['query']['users']['0']['userid'])) {
363
+				return true;
364
+			}
365
+		}
366
+		catch (CurlException $ex) {
367
+			ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
368
+
369
+			// Don't kill the request, just assume it's fine. Humans can deal with it later.
370
+			return false;
371
+		}
372
+
373
+		return false;
374
+	}
375
+
376
+	private function userSulExists(Request $request)
377
+	{
378
+		$requestName = $request->getName();
379
+
380
+		try {
381
+			$userExists = $this->httpHelper->get(
382
+				$this->mediawikiApiEndpoint,
383
+				array(
384
+					'action'  => 'query',
385
+					'meta'    => 'globaluserinfo',
386
+					'guiuser' => $requestName,
387
+					'format'  => 'php',
388
+				),
389
+				[],
390
+				$this->validationRemoteTimeout
391
+			);
392
+
393
+			$ue = unserialize($userExists);
394
+			if (isset ($ue['query']['globaluserinfo']['id'])) {
395
+				return true;
396
+			}
397
+		}
398
+		catch (CurlException $ex) {
399
+			ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
400
+
401
+			// Don't kill the request, just assume it's fine. Humans can deal with it later.
402
+			return false;
403
+		}
404
+
405
+		return false;
406
+	}
407
+
408
+	/**
409
+	 * Checks if a request with this name is currently open
410
+	 *
411
+	 * @param Request $request
412
+	 *
413
+	 * @return bool
414
+	 */
415
+	private function nameRequestExists(Request $request)
416
+	{
417
+		$query = "SELECT COUNT(id) FROM request WHERE status != 'Closed' AND name = :name;";
418
+		$statement = $this->database->prepare($query);
419
+		$statement->execute(array(':name' => $request->getName()));
420
+
421
+		if (!$statement) {
422
+			return false;
423
+		}
424
+
425
+		return $statement->fetchColumn() > 0;
426
+	}
427
+
428
+	private function deferRequest(Request $request, RequestQueue $targetQueue, $deferComment): void
429
+	{
430
+		$request->setQueue($targetQueue->getId());
431
+		$request->save();
432
+
433
+		$logTarget = $targetQueue->getLogName();
434
+
435
+		Logger::deferRequest($this->database, $request, $logTarget);
436
+
437
+		$comment = new Comment();
438
+		$comment->setDatabase($this->database);
439
+		$comment->setRequest($request->getId());
440
+		$comment->setVisibility('user');
441
+		$comment->setUser(null);
442
+
443
+		$comment->setComment($deferComment);
444
+		$comment->save();
445
+	}
446
+
447
+	private function formOverride(Request $request)
448
+	{
449
+		$form = $request->getOriginFormObject();
450
+		if($form === null || $form->getOverrideQueue() === null) {
451
+			return;
452
+		}
453
+
454
+		/** @var RequestQueue $targetQueue */
455
+		$targetQueue = RequestQueue::getById($form->getOverrideQueue(), $request->getDatabase());
456
+
457
+		$this->deferRequest($request, $targetQueue, 'Request deferred automatically due to request submission through a request form with a default queue set.');
458
+	}
459 459
 }
Please login to merge, or discard this patch.
includes/ConsoleStart.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -15,66 +15,66 @@
 block discarded – undo
15 15
 
16 16
 class ConsoleStart extends ApplicationBase
17 17
 {
18
-    /**
19
-     * @var ConsoleTaskBase
20
-     */
21
-    private $consoleTask;
18
+	/**
19
+	 * @var ConsoleTaskBase
20
+	 */
21
+	private $consoleTask;
22 22
 
23
-    /**
24
-     * ConsoleStart constructor.
25
-     *
26
-     * @param SiteConfiguration $configuration
27
-     * @param ConsoleTaskBase   $consoleTask
28
-     */
29
-    public function __construct(SiteConfiguration $configuration, ConsoleTaskBase $consoleTask)
30
-    {
31
-        parent::__construct($configuration);
32
-        $this->consoleTask = $consoleTask;
33
-    }
23
+	/**
24
+	 * ConsoleStart constructor.
25
+	 *
26
+	 * @param SiteConfiguration $configuration
27
+	 * @param ConsoleTaskBase   $consoleTask
28
+	 */
29
+	public function __construct(SiteConfiguration $configuration, ConsoleTaskBase $consoleTask)
30
+	{
31
+		parent::__construct($configuration);
32
+		$this->consoleTask = $consoleTask;
33
+	}
34 34
 
35
-    protected function setupEnvironment()
36
-    {
37
-        // initialise super-global providers
38
-        WebRequest::setGlobalStateProvider(new FakeGlobalStateProvider());
35
+	protected function setupEnvironment()
36
+	{
37
+		// initialise super-global providers
38
+		WebRequest::setGlobalStateProvider(new FakeGlobalStateProvider());
39 39
 
40
-        if (WebRequest::method() !== null) {
41
-            throw new EnvironmentException('This is a console task, which cannot be executed via the web.');
42
-        }
40
+		if (WebRequest::method() !== null) {
41
+			throw new EnvironmentException('This is a console task, which cannot be executed via the web.');
42
+		}
43 43
 
44
-        return parent::setupEnvironment();
45
-    }
44
+		return parent::setupEnvironment();
45
+	}
46 46
 
47
-    protected function cleanupEnvironment()
48
-    {
49
-    }
47
+	protected function cleanupEnvironment()
48
+	{
49
+	}
50 50
 
51
-    /**
52
-     * Main application logic
53
-     */
54
-    protected function main()
55
-    {
56
-        $database = PdoDatabase::getDatabaseConnection('acc');
51
+	/**
52
+	 * Main application logic
53
+	 */
54
+	protected function main()
55
+	{
56
+		$database = PdoDatabase::getDatabaseConnection('acc');
57 57
 
58
-        $this->setupHelpers($this->consoleTask, $this->getConfiguration(), $database);
58
+		$this->setupHelpers($this->consoleTask, $this->getConfiguration(), $database);
59 59
 
60
-        // initialise a database transaction
61
-        if (!$database->beginTransaction()) {
62
-            throw new Exception('Failed to start transaction on primary database.');
63
-        }
60
+		// initialise a database transaction
61
+		if (!$database->beginTransaction()) {
62
+			throw new Exception('Failed to start transaction on primary database.');
63
+		}
64 64
 
65
-        try {
66
-            // run the task
67
-            $this->consoleTask->execute();
65
+		try {
66
+			// run the task
67
+			$this->consoleTask->execute();
68 68
 
69
-            if ($database->hasActiveTransaction()) {
70
-                $database->commit();
71
-            }
72
-        }
73
-        finally {
74
-            // Catch any hanging on transactions
75
-            if ($database->hasActiveTransaction()) {
76
-                $database->rollBack();
77
-            }
78
-        }
79
-    }
69
+			if ($database->hasActiveTransaction()) {
70
+				$database->commit();
71
+			}
72
+		}
73
+		finally {
74
+			// Catch any hanging on transactions
75
+			if ($database->hasActiveTransaction()) {
76
+				$database->rollBack();
77
+			}
78
+		}
79
+	}
80 80
 }
81 81
\ No newline at end of file
Please login to merge, or discard this patch.
includes/WebStart.php 1 patch
Indentation   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -33,206 +33,206 @@
 block discarded – undo
33 33
  */
34 34
 class WebStart extends ApplicationBase
35 35
 {
36
-    /**
37
-     * @var IRequestRouter $requestRouter The request router to use. Note that different entry points have different
38
-     *                                    routers and hence different URL mappings
39
-     */
40
-    private $requestRouter;
41
-    /**
42
-     * @var bool $isPublic Determines whether to use public interface objects or internal interface objects
43
-     */
44
-    private $isPublic = false;
45
-
46
-    /**
47
-     * WebStart constructor.
48
-     *
49
-     * @param SiteConfiguration $configuration The site configuration
50
-     * @param IRequestRouter    $router        The request router to use
51
-     */
52
-    public function __construct(SiteConfiguration $configuration, IRequestRouter $router)
53
-    {
54
-        parent::__construct($configuration);
55
-
56
-        $this->requestRouter = $router;
57
-    }
58
-
59
-    /**
60
-     * @param ITask             $page
61
-     * @param SiteConfiguration $siteConfiguration
62
-     * @param PdoDatabase       $database
63
-     *
64
-     * @return void
65
-     */
66
-    protected function setupHelpers(
67
-        ITask $page,
68
-        SiteConfiguration $siteConfiguration,
69
-        PdoDatabase $database
70
-    ) {
71
-        parent::setupHelpers($page, $siteConfiguration, $database);
72
-
73
-        if ($page instanceof PageBase) {
74
-            $page->setTokenManager(new TokenManager());
75
-            $page->setCspManager(new ContentSecurityPolicyManager($siteConfiguration));
76
-
77
-            if ($page instanceof InternalPageBase) {
78
-                $page->setTypeAheadHelper(new TypeAheadHelper());
79
-
80
-                $identificationVerifier = new IdentificationVerifier($page->getHttpHelper(), $siteConfiguration, $database);
81
-                $page->setSecurityManager(new SecurityManager($identificationVerifier, new RoleConfiguration()));
82
-
83
-                if ($siteConfiguration->getTitleBlacklistEnabled()) {
84
-                    $page->setBlacklistHelper(new BlacklistHelper($page->getHttpHelper(), $database, $siteConfiguration));
85
-                }
86
-                else {
87
-                    $page->setBlacklistHelper(new FakeBlacklistHelper());
88
-                }
89
-
90
-                $page->setDomainAccessManager(new DomainAccessManager($page->getSecurityManager()));
91
-            }
92
-        }
93
-    }
94
-
95
-    /**
96
-     * Application entry point.
97
-     *
98
-     * Sets up the environment and runs the application, performing any global cleanup operations when done.
99
-     */
100
-    public function run()
101
-    {
102
-        try {
103
-            if ($this->setupEnvironment()) {
104
-                $this->main();
105
-            }
106
-        }
107
-        catch (EnvironmentException $ex) {
108
-            ob_end_clean();
109
-            print Offline::getOfflineMessage($this->isPublic(), $ex->getMessage());
110
-        }
111
-            /** @noinspection PhpRedundantCatchClauseInspection */
112
-        catch (ReadableException $ex) {
113
-            ob_end_clean();
114
-            print $ex->getReadableError();
115
-        }
116
-        finally {
117
-            $this->cleanupEnvironment();
118
-        }
119
-    }
120
-
121
-    /**
122
-     * Environment setup
123
-     *
124
-     * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
125
-     * and shut down prematurely.
126
-     *
127
-     * @return bool
128
-     * @throws EnvironmentException
129
-     */
130
-    protected function setupEnvironment()
131
-    {
132
-        // initialise global exception handler
133
-        set_exception_handler(array(ExceptionHandler::class, 'exceptionHandler'));
134
-        set_error_handler(array(ExceptionHandler::class, 'errorHandler'), E_RECOVERABLE_ERROR);
135
-
136
-        // start output buffering if necessary
137
-        if (ob_get_level() === 0) {
138
-            ob_start();
139
-        }
140
-
141
-        // initialise super-global providers
142
-        WebRequest::setGlobalStateProvider(new GlobalStateProvider());
143
-
144
-        if (Offline::isOffline()) {
145
-            print Offline::getOfflineMessage($this->isPublic());
146
-            ob_end_flush();
147
-
148
-            return false;
149
-        }
150
-
151
-        // Call parent setup
152
-        if (!parent::setupEnvironment()) {
153
-            return false;
154
-        }
155
-
156
-        // Start up sessions
157
-        Session::start();
158
-
159
-        // Check the user is allowed to be logged in still. This must be before we call any user-loading functions and
160
-        // get the current user cached.
161
-        // I'm not sure if this function call being here is particularly a good thing, but it's part of starting up a
162
-        // session I suppose.
163
-        $this->checkForceLogout();
164
-
165
-        // environment initialised!
166
-        return true;
167
-    }
168
-
169
-    /**
170
-     * Main application logic
171
-     */
172
-    protected function main()
173
-    {
174
-        // Get the right route for the request
175
-        $page = $this->requestRouter->route();
176
-
177
-        $siteConfiguration = $this->getConfiguration();
178
-        $database = PdoDatabase::getDatabaseConnection('acc');
179
-
180
-        $this->setupHelpers($page, $siteConfiguration, $database);
181
-
182
-        // run the route code for the request.
183
-        $page->execute();
184
-    }
185
-
186
-    /**
187
-     * Any cleanup tasks should go here
188
-     *
189
-     * Note that we need to be very careful here, as exceptions may have been thrown and handled.
190
-     * This should *only* be for cleaning up, no logic should go here.
191
-     */
192
-    protected function cleanupEnvironment()
193
-    {
194
-        // Clean up anything we splurged after sending the page.
195
-        if (ob_get_level() > 0) {
196
-            for ($i = ob_get_level(); $i > 0; $i--) {
197
-                ob_end_clean();
198
-            }
199
-        }
200
-    }
201
-
202
-    private function checkForceLogout()
203
-    {
204
-        $database = PdoDatabase::getDatabaseConnection('acc');
205
-
206
-        $sessionUserId = WebRequest::getSessionUserId();
207
-        iF ($sessionUserId === null) {
208
-            return;
209
-        }
210
-
211
-        // Note, User::getCurrent() caches it's result, which we *really* don't want to trigger.
212
-        $currentUser = User::getById($sessionUserId, $database);
213
-
214
-        if ($currentUser === false) {
215
-            // Umm... this user has a session cookie with a userId set, but no user exists...
216
-            Session::restart();
217
-
218
-            $currentUser = User::getCurrent($database);
219
-        }
220
-
221
-        if ($currentUser->getForceLogout()) {
222
-            Session::restart();
223
-
224
-            $currentUser->setForceLogout(false);
225
-            $currentUser->save();
226
-        }
227
-    }
228
-
229
-    public function isPublic()
230
-    {
231
-        return $this->isPublic;
232
-    }
233
-
234
-    public function setPublic($isPublic)
235
-    {
236
-        $this->isPublic = $isPublic;
237
-    }
36
+	/**
37
+	 * @var IRequestRouter $requestRouter The request router to use. Note that different entry points have different
38
+	 *                                    routers and hence different URL mappings
39
+	 */
40
+	private $requestRouter;
41
+	/**
42
+	 * @var bool $isPublic Determines whether to use public interface objects or internal interface objects
43
+	 */
44
+	private $isPublic = false;
45
+
46
+	/**
47
+	 * WebStart constructor.
48
+	 *
49
+	 * @param SiteConfiguration $configuration The site configuration
50
+	 * @param IRequestRouter    $router        The request router to use
51
+	 */
52
+	public function __construct(SiteConfiguration $configuration, IRequestRouter $router)
53
+	{
54
+		parent::__construct($configuration);
55
+
56
+		$this->requestRouter = $router;
57
+	}
58
+
59
+	/**
60
+	 * @param ITask             $page
61
+	 * @param SiteConfiguration $siteConfiguration
62
+	 * @param PdoDatabase       $database
63
+	 *
64
+	 * @return void
65
+	 */
66
+	protected function setupHelpers(
67
+		ITask $page,
68
+		SiteConfiguration $siteConfiguration,
69
+		PdoDatabase $database
70
+	) {
71
+		parent::setupHelpers($page, $siteConfiguration, $database);
72
+
73
+		if ($page instanceof PageBase) {
74
+			$page->setTokenManager(new TokenManager());
75
+			$page->setCspManager(new ContentSecurityPolicyManager($siteConfiguration));
76
+
77
+			if ($page instanceof InternalPageBase) {
78
+				$page->setTypeAheadHelper(new TypeAheadHelper());
79
+
80
+				$identificationVerifier = new IdentificationVerifier($page->getHttpHelper(), $siteConfiguration, $database);
81
+				$page->setSecurityManager(new SecurityManager($identificationVerifier, new RoleConfiguration()));
82
+
83
+				if ($siteConfiguration->getTitleBlacklistEnabled()) {
84
+					$page->setBlacklistHelper(new BlacklistHelper($page->getHttpHelper(), $database, $siteConfiguration));
85
+				}
86
+				else {
87
+					$page->setBlacklistHelper(new FakeBlacklistHelper());
88
+				}
89
+
90
+				$page->setDomainAccessManager(new DomainAccessManager($page->getSecurityManager()));
91
+			}
92
+		}
93
+	}
94
+
95
+	/**
96
+	 * Application entry point.
97
+	 *
98
+	 * Sets up the environment and runs the application, performing any global cleanup operations when done.
99
+	 */
100
+	public function run()
101
+	{
102
+		try {
103
+			if ($this->setupEnvironment()) {
104
+				$this->main();
105
+			}
106
+		}
107
+		catch (EnvironmentException $ex) {
108
+			ob_end_clean();
109
+			print Offline::getOfflineMessage($this->isPublic(), $ex->getMessage());
110
+		}
111
+			/** @noinspection PhpRedundantCatchClauseInspection */
112
+		catch (ReadableException $ex) {
113
+			ob_end_clean();
114
+			print $ex->getReadableError();
115
+		}
116
+		finally {
117
+			$this->cleanupEnvironment();
118
+		}
119
+	}
120
+
121
+	/**
122
+	 * Environment setup
123
+	 *
124
+	 * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
125
+	 * and shut down prematurely.
126
+	 *
127
+	 * @return bool
128
+	 * @throws EnvironmentException
129
+	 */
130
+	protected function setupEnvironment()
131
+	{
132
+		// initialise global exception handler
133
+		set_exception_handler(array(ExceptionHandler::class, 'exceptionHandler'));
134
+		set_error_handler(array(ExceptionHandler::class, 'errorHandler'), E_RECOVERABLE_ERROR);
135
+
136
+		// start output buffering if necessary
137
+		if (ob_get_level() === 0) {
138
+			ob_start();
139
+		}
140
+
141
+		// initialise super-global providers
142
+		WebRequest::setGlobalStateProvider(new GlobalStateProvider());
143
+
144
+		if (Offline::isOffline()) {
145
+			print Offline::getOfflineMessage($this->isPublic());
146
+			ob_end_flush();
147
+
148
+			return false;
149
+		}
150
+
151
+		// Call parent setup
152
+		if (!parent::setupEnvironment()) {
153
+			return false;
154
+		}
155
+
156
+		// Start up sessions
157
+		Session::start();
158
+
159
+		// Check the user is allowed to be logged in still. This must be before we call any user-loading functions and
160
+		// get the current user cached.
161
+		// I'm not sure if this function call being here is particularly a good thing, but it's part of starting up a
162
+		// session I suppose.
163
+		$this->checkForceLogout();
164
+
165
+		// environment initialised!
166
+		return true;
167
+	}
168
+
169
+	/**
170
+	 * Main application logic
171
+	 */
172
+	protected function main()
173
+	{
174
+		// Get the right route for the request
175
+		$page = $this->requestRouter->route();
176
+
177
+		$siteConfiguration = $this->getConfiguration();
178
+		$database = PdoDatabase::getDatabaseConnection('acc');
179
+
180
+		$this->setupHelpers($page, $siteConfiguration, $database);
181
+
182
+		// run the route code for the request.
183
+		$page->execute();
184
+	}
185
+
186
+	/**
187
+	 * Any cleanup tasks should go here
188
+	 *
189
+	 * Note that we need to be very careful here, as exceptions may have been thrown and handled.
190
+	 * This should *only* be for cleaning up, no logic should go here.
191
+	 */
192
+	protected function cleanupEnvironment()
193
+	{
194
+		// Clean up anything we splurged after sending the page.
195
+		if (ob_get_level() > 0) {
196
+			for ($i = ob_get_level(); $i > 0; $i--) {
197
+				ob_end_clean();
198
+			}
199
+		}
200
+	}
201
+
202
+	private function checkForceLogout()
203
+	{
204
+		$database = PdoDatabase::getDatabaseConnection('acc');
205
+
206
+		$sessionUserId = WebRequest::getSessionUserId();
207
+		iF ($sessionUserId === null) {
208
+			return;
209
+		}
210
+
211
+		// Note, User::getCurrent() caches it's result, which we *really* don't want to trigger.
212
+		$currentUser = User::getById($sessionUserId, $database);
213
+
214
+		if ($currentUser === false) {
215
+			// Umm... this user has a session cookie with a userId set, but no user exists...
216
+			Session::restart();
217
+
218
+			$currentUser = User::getCurrent($database);
219
+		}
220
+
221
+		if ($currentUser->getForceLogout()) {
222
+			Session::restart();
223
+
224
+			$currentUser->setForceLogout(false);
225
+			$currentUser->save();
226
+		}
227
+	}
228
+
229
+	public function isPublic()
230
+	{
231
+		return $this->isPublic;
232
+	}
233
+
234
+	public function setPublic($isPublic)
235
+	{
236
+		$this->isPublic = $isPublic;
237
+	}
238 238
 }
Please login to merge, or discard this patch.