Passed
Push — dependabot/composer/newinterna... ( 13eb18 )
by
unknown
04:37
created
backup.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@  discard block
 block discarded – undo
7 7
  ******************************************************************************/
8 8
 
9 9
 if (isset($_SERVER['REQUEST_METHOD'])) {
10
-    die();
10
+	die();
11 11
 } //Web clients die.
12 12
 
13 13
 // Get all the classes.
@@ -19,12 +19,12 @@  discard block
 block discarded – undo
19 19
 
20 20
 $arg = $argv['1'];
21 21
 if ($arg == "--monthly") {
22
-    echo "running monthly backups.\n";
23
-    $dateModifier = date("FY");
24
-    $cmdLine = "$BUtar $BUmonthdir/mBackup-$dateModifier.tar $BUdir/*.sql.gz; rm $BUdir/*.sql.gz";
25
-    echo "running command $cmdLine\n";
26
-    shell_exec($cmdLine);
27
-    die("done.");
22
+	echo "running monthly backups.\n";
23
+	$dateModifier = date("FY");
24
+	$cmdLine = "$BUtar $BUmonthdir/mBackup-$dateModifier.tar $BUdir/*.sql.gz; rm $BUdir/*.sql.gz";
25
+	echo "running command $cmdLine\n";
26
+	shell_exec($cmdLine);
27
+	die("done.");
28 28
 }
29 29
 
30 30
 echo "running nightly backups\n";
Please login to merge, or discard this patch.
smarty-plugins/modifier.date.php 2 patches
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -16,16 +16,16 @@
 block discarded – undo
16 16
  */
17 17
 function smarty_modifier_date($input)
18 18
 {
19
-    if (gettype($input) === 'object'
20
-        && (get_class($input) === DateTime::class || get_class($input) === DateTimeImmutable::class)
21
-    ) {
22
-        /** @var $date DateTime|DateTimeImmutable */
23
-        $date = $input;
24
-        $dateString = $date->format('Y-m-d H:i:s');
19
+	if (gettype($input) === 'object'
20
+		&& (get_class($input) === DateTime::class || get_class($input) === DateTimeImmutable::class)
21
+	) {
22
+		/** @var $date DateTime|DateTimeImmutable */
23
+		$date = $input;
24
+		$dateString = $date->format('Y-m-d H:i:s');
25 25
 
26
-        return $dateString;
27
-    }
28
-    else {
29
-        return $input;
30
-    }
26
+		return $dateString;
27
+	}
28
+	else {
29
+		return $input;
30
+	}
31 31
 }
32 32
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -24,8 +24,7 @@
 block discarded – undo
24 24
         $dateString = $date->format('Y-m-d H:i:s');
25 25
 
26 26
         return $dateString;
27
-    }
28
-    else {
27
+    } else {
29 28
         return $input;
30 29
     }
31 30
 }
32 31
\ No newline at end of file
Please login to merge, or discard this patch.
smarty-plugins/modifier.relativedate.php 2 patches
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -16,68 +16,68 @@
 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
-        $then = new DateTime($input);
28
-    }
21
+	if (gettype($input) === 'object'
22
+		&& (get_class($input) === DateTime::class || get_class($input) === DateTimeImmutable::class)
23
+	) {
24
+		$then = $input;
25
+	}
26
+	else {
27
+		$then = new DateTime($input);
28
+	}
29 29
 
30
-    $secs = $now->getTimestamp() - $then->getTimestamp();
30
+	$secs = $now->getTimestamp() - $then->getTimestamp();
31 31
 
32
-    $second = 1;
33
-    $minute = 60 * $second;
34
-    $minuteCut = 60 * $second;
35
-    $hour = 60 * $minute;
36
-    $hourCut = 90 * $minute;
37
-    $day = 24 * $hour;
38
-    $dayCut = 48 * $hour;
39
-    $week = 7 * $day;
40
-    $weekCut = 14 * $day;
41
-    $month = 30 * $day;
42
-    $monthCut = 60 * $day;
43
-    $year = 365 * $day;
44
-    $yearCut = $year * 2;
32
+	$second = 1;
33
+	$minute = 60 * $second;
34
+	$minuteCut = 60 * $second;
35
+	$hour = 60 * $minute;
36
+	$hourCut = 90 * $minute;
37
+	$day = 24 * $hour;
38
+	$dayCut = 48 * $hour;
39
+	$week = 7 * $day;
40
+	$weekCut = 14 * $day;
41
+	$month = 30 * $day;
42
+	$monthCut = 60 * $day;
43
+	$year = 365 * $day;
44
+	$yearCut = $year * 2;
45 45
 
46
-    $pluralise = true;
46
+	$pluralise = true;
47 47
 
48
-    if ($secs <= 10) {
49
-        $output = "just now";
50
-        $pluralise = false;
51
-    }
52
-    elseif ($secs > 10 && $secs < $minuteCut) {
53
-        $output = round($secs / $second) . " second";
54
-    }
55
-    elseif ($secs >= $minuteCut && $secs < $hourCut) {
56
-        $output = round($secs / $minute) . " minute";
57
-    }
58
-    elseif ($secs >= $hourCut && $secs < $dayCut) {
59
-        $output = round($secs / $hour) . " hour";
60
-    }
61
-    elseif ($secs >= $dayCut && $secs < $weekCut) {
62
-        $output = round($secs / $day) . " day";
63
-    }
64
-    elseif ($secs >= $weekCut && $secs < $monthCut) {
65
-        $output = round($secs / $week) . " week";
66
-    }
67
-    elseif ($secs >= $monthCut && $secs < $yearCut) {
68
-        $output = round($secs / $month) . " month";
69
-    }
70
-    elseif ($secs >= $yearCut && $secs < $year * 10) {
71
-        $output = round($secs / $year) . " year";
72
-    }
73
-    else {
74
-        $output = "a long time ago";
75
-        $pluralise = false;
76
-    }
48
+	if ($secs <= 10) {
49
+		$output = "just now";
50
+		$pluralise = false;
51
+	}
52
+	elseif ($secs > 10 && $secs < $minuteCut) {
53
+		$output = round($secs / $second) . " second";
54
+	}
55
+	elseif ($secs >= $minuteCut && $secs < $hourCut) {
56
+		$output = round($secs / $minute) . " minute";
57
+	}
58
+	elseif ($secs >= $hourCut && $secs < $dayCut) {
59
+		$output = round($secs / $hour) . " hour";
60
+	}
61
+	elseif ($secs >= $dayCut && $secs < $weekCut) {
62
+		$output = round($secs / $day) . " day";
63
+	}
64
+	elseif ($secs >= $weekCut && $secs < $monthCut) {
65
+		$output = round($secs / $week) . " week";
66
+	}
67
+	elseif ($secs >= $monthCut && $secs < $yearCut) {
68
+		$output = round($secs / $month) . " month";
69
+	}
70
+	elseif ($secs >= $yearCut && $secs < $year * 10) {
71
+		$output = round($secs / $year) . " year";
72
+	}
73
+	else {
74
+		$output = "a long time ago";
75
+		$pluralise = false;
76
+	}
77 77
 
78
-    if ($pluralise) {
79
-        $output = (substr($output, 0, 2) <> "1 ") ? $output . "s ago" : $output . " ago";
80
-    }
78
+	if ($pluralise) {
79
+		$output = (substr($output, 0, 2) <> "1 ") ? $output . "s ago" : $output . " ago";
80
+	}
81 81
 
82
-    return $output;
82
+	return $output;
83 83
 }
84 84
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +9 added lines, -18 removed lines patch added patch discarded remove patch
@@ -22,8 +22,7 @@  discard block
 block discarded – undo
22 22
         && (get_class($input) === DateTime::class || get_class($input) === DateTimeImmutable::class)
23 23
     ) {
24 24
         $then = $input;
25
-    }
26
-    else {
25
+    } else {
27 26
         $then = new DateTime($input);
28 27
     }
29 28
 
@@ -48,29 +47,21 @@  discard block
 block discarded – undo
48 47
     if ($secs <= 10) {
49 48
         $output = "just now";
50 49
         $pluralise = false;
51
-    }
52
-    elseif ($secs > 10 && $secs < $minuteCut) {
50
+    } elseif ($secs > 10 && $secs < $minuteCut) {
53 51
         $output = round($secs / $second) . " second";
54
-    }
55
-    elseif ($secs >= $minuteCut && $secs < $hourCut) {
52
+    } elseif ($secs >= $minuteCut && $secs < $hourCut) {
56 53
         $output = round($secs / $minute) . " minute";
57
-    }
58
-    elseif ($secs >= $hourCut && $secs < $dayCut) {
54
+    } elseif ($secs >= $hourCut && $secs < $dayCut) {
59 55
         $output = round($secs / $hour) . " hour";
60
-    }
61
-    elseif ($secs >= $dayCut && $secs < $weekCut) {
56
+    } elseif ($secs >= $dayCut && $secs < $weekCut) {
62 57
         $output = round($secs / $day) . " day";
63
-    }
64
-    elseif ($secs >= $weekCut && $secs < $monthCut) {
58
+    } elseif ($secs >= $weekCut && $secs < $monthCut) {
65 59
         $output = round($secs / $week) . " week";
66
-    }
67
-    elseif ($secs >= $monthCut && $secs < $yearCut) {
60
+    } elseif ($secs >= $monthCut && $secs < $yearCut) {
68 61
         $output = round($secs / $month) . " month";
69
-    }
70
-    elseif ($secs >= $yearCut && $secs < $year * 10) {
62
+    } elseif ($secs >= $yearCut && $secs < $year * 10) {
71 63
         $output = round($secs / $year) . " year";
72
-    }
73
-    else {
64
+    } else {
74 65
         $output = "a long time ago";
75 66
         $pluralise = false;
76 67
     }
Please login to merge, or discard this patch.
includes/ExceptionHandler.php 2 patches
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -13,22 +13,22 @@  discard block
 block discarded – undo
13 13
 
14 14
 class ExceptionHandler
15 15
 {
16
-    /**
17
-     * Global exception handler
18
-     *
19
-     * Smarty would be nice to use, but it COULD BE smarty that throws the errors.
20
-     * Let's build something ourselves, and hope it works.
21
-     *
22
-     * @param $exception
23
-     *
24
-     * @category Security-Critical - has the potential to leak data when exception is thrown.
25
-     */
26
-    public static function exceptionHandler(Exception $exception)
27
-    {
28
-        /** @global $siteConfiguration SiteConfiguration */
29
-        global $siteConfiguration;
30
-
31
-        $errorDocument = <<<HTML
16
+	/**
17
+	 * Global exception handler
18
+	 *
19
+	 * Smarty would be nice to use, but it COULD BE smarty that throws the errors.
20
+	 * Let's build something ourselves, and hope it works.
21
+	 *
22
+	 * @param $exception
23
+	 *
24
+	 * @category Security-Critical - has the potential to leak data when exception is thrown.
25
+	 */
26
+	public static function exceptionHandler(Exception $exception)
27
+	{
28
+		/** @global $siteConfiguration SiteConfiguration */
29
+		global $siteConfiguration;
30
+
31
+		$errorDocument = <<<HTML
32 32
 <!DOCTYPE html>
33 33
 <html lang="en"><head>
34 34
 <meta charset="utf-8">
@@ -49,77 +49,77 @@  discard block
 block discarded – undo
49 49
 </div></body></html>
50 50
 HTML;
51 51
 
52
-        $errorData = self::getExceptionData($exception);
53
-        $errorData['server'] = $_SERVER;
54
-        $errorData['get'] = $_GET;
55
-        $errorData['post'] = $_POST;
56
-
57
-        $state = serialize($errorData);
58
-        $errorId = sha1($state);
59
-
60
-        // Save the error for later analysis
61
-        file_put_contents($siteConfiguration->getErrorLog() . '/' . $errorId . '.log', $state);
62
-
63
-        // clear and discard any content that's been saved to the output buffer
64
-        if (ob_get_level() > 0) {
65
-            ob_end_clean();
66
-        }
67
-
68
-        // push error ID into the document.
69
-        $message = str_replace('$1$', $errorId, $errorDocument);
70
-
71
-        if ($siteConfiguration->getDebuggingTraceEnabled()) {
72
-            ob_start();
73
-            var_dump($errorData);
74
-            $textErrorData = ob_get_contents();
75
-            ob_end_clean();
76
-
77
-            $message = str_replace('$2$', $textErrorData, $message);
78
-        }
79
-        else {
80
-            $message = str_replace('$2$', "", $message);
81
-        }
82
-
83
-        // While we *shouldn't* have sent headers by now due to the output buffering, PHPUnit does weird things.
84
-        // This is "only" needed for the tests, but it's a good idea to wrap this anyway.
85
-        if (!headers_sent()) {
86
-            header('HTTP/1.1 500 Internal Server Error');
87
-        }
88
-
89
-        // output the document
90
-        print $message;
91
-    }
92
-
93
-    /**
94
-     * @param int    $errorSeverity The severity level of the exception.
95
-     * @param string $errorMessage  The Exception message to throw.
96
-     * @param string $errorFile     The filename where the exception is thrown.
97
-     * @param int    $errorLine     The line number where the exception is thrown.
98
-     *
99
-     * @throws ErrorException
100
-     */
101
-    public static function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine)
102
-    {
103
-        // call into the main exception handler above
104
-        throw new ErrorException($errorMessage, 0, $errorSeverity, $errorFile, $errorLine);
105
-    }
106
-
107
-    /**
108
-     * @param Exception $exception
109
-     *
110
-     * @return null|array
111
-     */
112
-    private static function getExceptionData($exception)
113
-    {
114
-        if ($exception == null) {
115
-            return null;
116
-        }
117
-
118
-        return array(
119
-            'exception' => get_class($exception),
120
-            'message'   => $exception->getMessage(),
121
-            'stack'     => $exception->getTraceAsString(),
122
-            'previous'  => self::getExceptionData($exception->getPrevious()),
123
-        );
124
-    }
52
+		$errorData = self::getExceptionData($exception);
53
+		$errorData['server'] = $_SERVER;
54
+		$errorData['get'] = $_GET;
55
+		$errorData['post'] = $_POST;
56
+
57
+		$state = serialize($errorData);
58
+		$errorId = sha1($state);
59
+
60
+		// Save the error for later analysis
61
+		file_put_contents($siteConfiguration->getErrorLog() . '/' . $errorId . '.log', $state);
62
+
63
+		// clear and discard any content that's been saved to the output buffer
64
+		if (ob_get_level() > 0) {
65
+			ob_end_clean();
66
+		}
67
+
68
+		// push error ID into the document.
69
+		$message = str_replace('$1$', $errorId, $errorDocument);
70
+
71
+		if ($siteConfiguration->getDebuggingTraceEnabled()) {
72
+			ob_start();
73
+			var_dump($errorData);
74
+			$textErrorData = ob_get_contents();
75
+			ob_end_clean();
76
+
77
+			$message = str_replace('$2$', $textErrorData, $message);
78
+		}
79
+		else {
80
+			$message = str_replace('$2$', "", $message);
81
+		}
82
+
83
+		// While we *shouldn't* have sent headers by now due to the output buffering, PHPUnit does weird things.
84
+		// This is "only" needed for the tests, but it's a good idea to wrap this anyway.
85
+		if (!headers_sent()) {
86
+			header('HTTP/1.1 500 Internal Server Error');
87
+		}
88
+
89
+		// output the document
90
+		print $message;
91
+	}
92
+
93
+	/**
94
+	 * @param int    $errorSeverity The severity level of the exception.
95
+	 * @param string $errorMessage  The Exception message to throw.
96
+	 * @param string $errorFile     The filename where the exception is thrown.
97
+	 * @param int    $errorLine     The line number where the exception is thrown.
98
+	 *
99
+	 * @throws ErrorException
100
+	 */
101
+	public static function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine)
102
+	{
103
+		// call into the main exception handler above
104
+		throw new ErrorException($errorMessage, 0, $errorSeverity, $errorFile, $errorLine);
105
+	}
106
+
107
+	/**
108
+	 * @param Exception $exception
109
+	 *
110
+	 * @return null|array
111
+	 */
112
+	private static function getExceptionData($exception)
113
+	{
114
+		if ($exception == null) {
115
+			return null;
116
+		}
117
+
118
+		return array(
119
+			'exception' => get_class($exception),
120
+			'message'   => $exception->getMessage(),
121
+			'stack'     => $exception->getTraceAsString(),
122
+			'previous'  => self::getExceptionData($exception->getPrevious()),
123
+		);
124
+	}
125 125
 }
126 126
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -75,8 +75,7 @@
 block discarded – undo
75 75
             ob_end_clean();
76 76
 
77 77
             $message = str_replace('$2$', $textErrorData, $message);
78
-        }
79
-        else {
78
+        } else {
80 79
             $message = str_replace('$2$', "", $message);
81 80
         }
82 81
 
Please login to merge, or discard this patch.
includes/Fragments/RequestData.php 2 patches
Indentation   +318 added lines, -318 removed lines patch added patch discarded remove patch
@@ -23,322 +23,322 @@
 block discarded – undo
23 23
 
24 24
 trait RequestData
25 25
 {
26
-    /**
27
-     * @var array Array of IP address classed as 'private' by RFC1918.
28
-     */
29
-    protected static $rfc1918ips = array(
30
-        "10.0.0.0"    => "10.255.255.255",
31
-        "172.16.0.0"  => "172.31.255.255",
32
-        "192.168.0.0" => "192.168.255.255",
33
-        "169.254.0.0" => "169.254.255.255",
34
-        "127.0.0.0"   => "127.255.255.255",
35
-    );
36
-
37
-    /**
38
-     * Gets a request object
39
-     *
40
-     * @param PdoDatabase $database  The database connection
41
-     * @param int         $requestId The ID of the request to retrieve
42
-     *
43
-     * @return Request
44
-     * @throws ApplicationLogicException
45
-     */
46
-    protected function getRequest(PdoDatabase $database, $requestId)
47
-    {
48
-        if ($requestId === null) {
49
-            throw new ApplicationLogicException("No request specified");
50
-        }
51
-
52
-        $request = Request::getById($requestId, $database);
53
-        if ($request === false || !is_a($request, Request::class)) {
54
-            throw new ApplicationLogicException('Could not load the requested request!');
55
-        }
56
-
57
-        return $request;
58
-    }
59
-
60
-    /**
61
-     * Returns a value stating whether the user is allowed to see private data or not
62
-     *
63
-     * @param Request $request
64
-     * @param User    $currentUser
65
-     *
66
-     * @return bool
67
-     * @category Security-Critical
68
-     */
69
-    protected function isAllowedPrivateData(Request $request, User $currentUser)
70
-    {
71
-        // Test the main security barrier for private data access using SecurityManager
72
-        if ($this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')) {
73
-            // Tool admins/check-users can always see private data
74
-            return true;
75
-        }
76
-
77
-        // reserving user is allowed to see the data
78
-        if ($currentUser->getId() === $request->getReserved()
79
-            && $request->getReserved() !== null
80
-            && $this->barrierTest('seePrivateDataWhenReserved', $currentUser, 'RequestData')
81
-        ) {
82
-            return true;
83
-        }
84
-
85
-        // user has the reveal hash
86
-        if (WebRequest::getString('hash') === $request->getRevealHash()
87
-            && $this->barrierTest('seePrivateDataWithHash', $currentUser, 'RequestData')
88
-        ) {
89
-            return true;
90
-        }
91
-
92
-        // nope. Not allowed.
93
-        return false;
94
-    }
95
-
96
-    /**
97
-     * Tests the security barrier for a specified action.
98
-     *
99
-     * Don't use within templates
100
-     *
101
-     * @param string      $action
102
-     *
103
-     * @param User        $user
104
-     * @param null|string $pageName
105
-     *
106
-     * @return bool
107
-     * @category Security-Critical
108
-     */
109
-    abstract protected function barrierTest($action, User $user, $pageName = null);
110
-
111
-    /**
112
-     * Gets the name of the route that has been passed from the request router.
113
-     * @return string
114
-     */
115
-    abstract protected function getRouteName();
116
-
117
-    /** @return SecurityManager */
118
-    abstract protected function getSecurityManager();
119
-
120
-    /**
121
-     * Sets the name of the template this page should display.
122
-     *
123
-     * @param string $name
124
-     */
125
-    abstract protected function setTemplate($name);
126
-
127
-    /** @return IXffTrustProvider */
128
-    abstract protected function getXffTrustProvider();
129
-
130
-    /** @return ILocationProvider */
131
-    abstract protected function getLocationProvider();
132
-
133
-    /** @return IRDnsProvider */
134
-    abstract protected function getRdnsProvider();
135
-
136
-    /**
137
-     * Assigns a Smarty variable
138
-     *
139
-     * @param  array|string $name  the template variable name(s)
140
-     * @param  mixed        $value the value to assign
141
-     */
142
-    abstract protected function assign($name, $value);
143
-
144
-    /**
145
-     * @param int         $requestReservationId
146
-     * @param PdoDatabase $database
147
-     * @param User        $currentUser
148
-     */
149
-    protected function setupReservationDetails($requestReservationId, PdoDatabase $database, User $currentUser)
150
-    {
151
-        $requestIsReserved = $requestReservationId !== null;
152
-        $this->assign('requestIsReserved', $requestIsReserved);
153
-        $this->assign('requestIsReservedByMe', false);
154
-
155
-        if ($requestIsReserved) {
156
-            $this->assign('requestReservedByName', User::getById($requestReservationId, $database)->getUsername());
157
-            $this->assign('requestReservedById', $requestReservationId);
158
-
159
-            if ($requestReservationId === $currentUser->getId()) {
160
-                $this->assign('requestIsReservedByMe', true);
161
-            }
162
-        }
163
-
164
-        $this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
165
-    }
166
-
167
-    /**
168
-     * Adds private request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
169
-     *
170
-     * @param Request           $request
171
-     * @param User              $currentUser
172
-     * @param SiteConfiguration $configuration
173
-     *
174
-     * @param PdoDatabase       $database
175
-     */
176
-    protected function setupPrivateData(
177
-        $request,
178
-        User $currentUser,
179
-        SiteConfiguration $configuration,
180
-        PdoDatabase $database
181
-    ) {
182
-        $xffProvider = $this->getXffTrustProvider();
183
-
184
-        $relatedEmailRequests = RequestSearchHelper::get($database)
185
-            ->byEmailAddress($request->getEmail())
186
-            ->withConfirmedEmail()
187
-            ->excludingPurgedData($configuration)
188
-            ->excludingRequest($request->getId())
189
-            ->fetch();
190
-
191
-        $this->assign('requestEmail', $request->getEmail());
192
-        $emailDomain = explode("@", $request->getEmail())[1];
193
-        $this->assign("emailurl", $emailDomain);
194
-        $this->assign('requestRelatedEmailRequestsCount', count($relatedEmailRequests));
195
-        $this->assign('requestRelatedEmailRequests', $relatedEmailRequests);
196
-
197
-        $trustedIp = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
198
-        $this->assign('requestTrustedIp', $trustedIp);
199
-        $this->assign('requestRealIp', $request->getIp());
200
-        $this->assign('requestForwardedIp', $request->getForwardedIp());
201
-
202
-        $trustedIpLocation = $this->getLocationProvider()->getIpLocation($trustedIp);
203
-        $this->assign('requestTrustedIpLocation', $trustedIpLocation);
204
-
205
-        $this->assign('requestHasForwardedIp', $request->getForwardedIp() !== null);
206
-
207
-        $relatedIpRequests = RequestSearchHelper::get($database)
208
-            ->byIp($trustedIp)
209
-            ->withConfirmedEmail()
210
-            ->excludingPurgedData($configuration)
211
-            ->excludingRequest($request->getId())
212
-            ->fetch();
213
-
214
-        $this->assign('requestRelatedIpRequestsCount', count($relatedIpRequests));
215
-        $this->assign('requestRelatedIpRequests', $relatedIpRequests);
216
-
217
-        $this->assign('showRevealLink', false);
218
-        if ($request->getReserved() === $currentUser->getId() ||
219
-            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
220
-        ) {
221
-            $this->assign('showRevealLink', true);
222
-            $this->assign('revealHash', $request->getRevealHash());
223
-        }
224
-
225
-        $this->setupForwardedIpData($request);
226
-    }
227
-
228
-    /**
229
-     * Adds checkuser request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
230
-     *
231
-     * @param Request $request
232
-     */
233
-    protected function setupCheckUserData(Request $request)
234
-    {
235
-        $this->assign('requestUserAgent', $request->getUserAgent());
236
-    }
237
-
238
-    /**
239
-     * Sets up the basic data for this request, and adds it to Smarty
240
-     *
241
-     * @param Request           $request
242
-     * @param SiteConfiguration $config
243
-     */
244
-    protected function setupBasicData(Request $request, SiteConfiguration $config)
245
-    {
246
-        $this->assign('requestId', $request->getId());
247
-        $this->assign('updateVersion', $request->getUpdateVersion());
248
-        $this->assign('requestName', $request->getName());
249
-        $this->assign('requestDate', $request->getDate());
250
-        $this->assign('requestStatus', $request->getStatus());
251
-
252
-        $this->assign('requestIsClosed', !array_key_exists($request->getStatus(), $config->getRequestStates()));
253
-    }
254
-
255
-    /**
256
-     * Sets up the forwarded IP data for this request and adds it to Smarty
257
-     *
258
-     * @param Request $request
259
-     */
260
-    protected function setupForwardedIpData(Request $request)
261
-    {
262
-        if ($request->getForwardedIp() !== null) {
263
-            $requestProxyData = array(); // Initialize array to store data to be output in Smarty template.
264
-            $proxyIndex = 0;
265
-
266
-            // Assuming [client] <=> [proxy1] <=> [proxy2] <=> [proxy3] <=> [us], we will see an XFF header of [client],
267
-            // [proxy1], [proxy2], and our actual IP will be [proxy3]
268
-            $proxies = explode(",", $request->getForwardedIp());
269
-            $proxies[] = $request->getIp();
270
-
271
-            // Origin is the supposed "client" IP.
272
-            $origin = $proxies[0];
273
-            $this->assign("forwardedOrigin", $origin);
274
-
275
-            // We step through the servers in reverse order, from closest to furthest
276
-            $proxies = array_reverse($proxies);
277
-
278
-            // By default, we have trust, because the first in the chain is now REMOTE_ADDR, which is hardest to spoof.
279
-            $trust = true;
280
-
281
-            /**
282
-             * @var int    $index     The zero-based index of the proxy.
283
-             * @var string $proxyData The proxy IP address (although possibly not!)
284
-             */
285
-            foreach ($proxies as $index => $proxyData) {
286
-                $proxyAddress = trim($proxyData);
287
-                $requestProxyData[$proxyIndex]['ip'] = $proxyAddress;
288
-
289
-                // get data on this IP.
290
-                $thisProxyIsTrusted = $this->getXffTrustProvider()->isTrusted($proxyAddress);
291
-
292
-                $proxyIsInPrivateRange = $this->getXffTrustProvider()
293
-                    ->ipInRange(self::$rfc1918ips, $proxyAddress);
294
-
295
-                if (!$proxyIsInPrivateRange) {
296
-                    $proxyReverseDns = $this->getRdnsProvider()->getReverseDNS($proxyAddress);
297
-                    $proxyLocation = $this->getLocationProvider()->getIpLocation($proxyAddress);
298
-                }
299
-                else {
300
-                    // this is going to fail, so why bother trying?
301
-                    $proxyReverseDns = false;
302
-                    $proxyLocation = false;
303
-                }
304
-
305
-                // current trust chain status BEFORE this link
306
-                $preLinkTrust = $trust;
307
-
308
-                // is *this* link trusted? Note, this will be true even if there is an untrusted link before this!
309
-                $requestProxyData[$proxyIndex]['trustedlink'] = $thisProxyIsTrusted;
310
-
311
-                // set the trust status of the chain to this point
312
-                $trust = $trust & $thisProxyIsTrusted;
313
-
314
-                // If this is the origin address, and the chain was trusted before this point, then we can trust
315
-                // the origin.
316
-                if ($preLinkTrust && $proxyAddress == $origin) {
317
-                    // if this is the origin, then we are at the last point in the chain.
318
-                    // @todo: this is probably the cause of some bugs when an IP appears twice - we're missing a check
319
-                    // to see if this is *really* the last in the chain, rather than just the same IP as it.
320
-                    $trust = true;
321
-                }
322
-
323
-                $requestProxyData[$proxyIndex]['trust'] = $trust;
324
-
325
-                $requestProxyData[$proxyIndex]['rdnsfailed'] = $proxyReverseDns === false;
326
-                $requestProxyData[$proxyIndex]['rdns'] = $proxyReverseDns;
327
-                $requestProxyData[$proxyIndex]['routable'] = !$proxyIsInPrivateRange;
328
-
329
-                $requestProxyData[$proxyIndex]['location'] = $proxyLocation;
330
-
331
-                if ($proxyReverseDns === $proxyAddress && $proxyIsInPrivateRange === false) {
332
-                    $requestProxyData[$proxyIndex]['rdns'] = null;
333
-                }
334
-
335
-                $showLinks = (!$trust || $proxyAddress == $origin) && !$proxyIsInPrivateRange;
336
-                $requestProxyData[$proxyIndex]['showlinks'] = $showLinks;
337
-
338
-                $proxyIndex++;
339
-            }
340
-
341
-            $this->assign("requestProxyData", $requestProxyData);
342
-        }
343
-    }
26
+	/**
27
+	 * @var array Array of IP address classed as 'private' by RFC1918.
28
+	 */
29
+	protected static $rfc1918ips = array(
30
+		"10.0.0.0"    => "10.255.255.255",
31
+		"172.16.0.0"  => "172.31.255.255",
32
+		"192.168.0.0" => "192.168.255.255",
33
+		"169.254.0.0" => "169.254.255.255",
34
+		"127.0.0.0"   => "127.255.255.255",
35
+	);
36
+
37
+	/**
38
+	 * Gets a request object
39
+	 *
40
+	 * @param PdoDatabase $database  The database connection
41
+	 * @param int         $requestId The ID of the request to retrieve
42
+	 *
43
+	 * @return Request
44
+	 * @throws ApplicationLogicException
45
+	 */
46
+	protected function getRequest(PdoDatabase $database, $requestId)
47
+	{
48
+		if ($requestId === null) {
49
+			throw new ApplicationLogicException("No request specified");
50
+		}
51
+
52
+		$request = Request::getById($requestId, $database);
53
+		if ($request === false || !is_a($request, Request::class)) {
54
+			throw new ApplicationLogicException('Could not load the requested request!');
55
+		}
56
+
57
+		return $request;
58
+	}
59
+
60
+	/**
61
+	 * Returns a value stating whether the user is allowed to see private data or not
62
+	 *
63
+	 * @param Request $request
64
+	 * @param User    $currentUser
65
+	 *
66
+	 * @return bool
67
+	 * @category Security-Critical
68
+	 */
69
+	protected function isAllowedPrivateData(Request $request, User $currentUser)
70
+	{
71
+		// Test the main security barrier for private data access using SecurityManager
72
+		if ($this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')) {
73
+			// Tool admins/check-users can always see private data
74
+			return true;
75
+		}
76
+
77
+		// reserving user is allowed to see the data
78
+		if ($currentUser->getId() === $request->getReserved()
79
+			&& $request->getReserved() !== null
80
+			&& $this->barrierTest('seePrivateDataWhenReserved', $currentUser, 'RequestData')
81
+		) {
82
+			return true;
83
+		}
84
+
85
+		// user has the reveal hash
86
+		if (WebRequest::getString('hash') === $request->getRevealHash()
87
+			&& $this->barrierTest('seePrivateDataWithHash', $currentUser, 'RequestData')
88
+		) {
89
+			return true;
90
+		}
91
+
92
+		// nope. Not allowed.
93
+		return false;
94
+	}
95
+
96
+	/**
97
+	 * Tests the security barrier for a specified action.
98
+	 *
99
+	 * Don't use within templates
100
+	 *
101
+	 * @param string      $action
102
+	 *
103
+	 * @param User        $user
104
+	 * @param null|string $pageName
105
+	 *
106
+	 * @return bool
107
+	 * @category Security-Critical
108
+	 */
109
+	abstract protected function barrierTest($action, User $user, $pageName = null);
110
+
111
+	/**
112
+	 * Gets the name of the route that has been passed from the request router.
113
+	 * @return string
114
+	 */
115
+	abstract protected function getRouteName();
116
+
117
+	/** @return SecurityManager */
118
+	abstract protected function getSecurityManager();
119
+
120
+	/**
121
+	 * Sets the name of the template this page should display.
122
+	 *
123
+	 * @param string $name
124
+	 */
125
+	abstract protected function setTemplate($name);
126
+
127
+	/** @return IXffTrustProvider */
128
+	abstract protected function getXffTrustProvider();
129
+
130
+	/** @return ILocationProvider */
131
+	abstract protected function getLocationProvider();
132
+
133
+	/** @return IRDnsProvider */
134
+	abstract protected function getRdnsProvider();
135
+
136
+	/**
137
+	 * Assigns a Smarty variable
138
+	 *
139
+	 * @param  array|string $name  the template variable name(s)
140
+	 * @param  mixed        $value the value to assign
141
+	 */
142
+	abstract protected function assign($name, $value);
143
+
144
+	/**
145
+	 * @param int         $requestReservationId
146
+	 * @param PdoDatabase $database
147
+	 * @param User        $currentUser
148
+	 */
149
+	protected function setupReservationDetails($requestReservationId, PdoDatabase $database, User $currentUser)
150
+	{
151
+		$requestIsReserved = $requestReservationId !== null;
152
+		$this->assign('requestIsReserved', $requestIsReserved);
153
+		$this->assign('requestIsReservedByMe', false);
154
+
155
+		if ($requestIsReserved) {
156
+			$this->assign('requestReservedByName', User::getById($requestReservationId, $database)->getUsername());
157
+			$this->assign('requestReservedById', $requestReservationId);
158
+
159
+			if ($requestReservationId === $currentUser->getId()) {
160
+				$this->assign('requestIsReservedByMe', true);
161
+			}
162
+		}
163
+
164
+		$this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
165
+	}
166
+
167
+	/**
168
+	 * Adds private request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
169
+	 *
170
+	 * @param Request           $request
171
+	 * @param User              $currentUser
172
+	 * @param SiteConfiguration $configuration
173
+	 *
174
+	 * @param PdoDatabase       $database
175
+	 */
176
+	protected function setupPrivateData(
177
+		$request,
178
+		User $currentUser,
179
+		SiteConfiguration $configuration,
180
+		PdoDatabase $database
181
+	) {
182
+		$xffProvider = $this->getXffTrustProvider();
183
+
184
+		$relatedEmailRequests = RequestSearchHelper::get($database)
185
+			->byEmailAddress($request->getEmail())
186
+			->withConfirmedEmail()
187
+			->excludingPurgedData($configuration)
188
+			->excludingRequest($request->getId())
189
+			->fetch();
190
+
191
+		$this->assign('requestEmail', $request->getEmail());
192
+		$emailDomain = explode("@", $request->getEmail())[1];
193
+		$this->assign("emailurl", $emailDomain);
194
+		$this->assign('requestRelatedEmailRequestsCount', count($relatedEmailRequests));
195
+		$this->assign('requestRelatedEmailRequests', $relatedEmailRequests);
196
+
197
+		$trustedIp = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
198
+		$this->assign('requestTrustedIp', $trustedIp);
199
+		$this->assign('requestRealIp', $request->getIp());
200
+		$this->assign('requestForwardedIp', $request->getForwardedIp());
201
+
202
+		$trustedIpLocation = $this->getLocationProvider()->getIpLocation($trustedIp);
203
+		$this->assign('requestTrustedIpLocation', $trustedIpLocation);
204
+
205
+		$this->assign('requestHasForwardedIp', $request->getForwardedIp() !== null);
206
+
207
+		$relatedIpRequests = RequestSearchHelper::get($database)
208
+			->byIp($trustedIp)
209
+			->withConfirmedEmail()
210
+			->excludingPurgedData($configuration)
211
+			->excludingRequest($request->getId())
212
+			->fetch();
213
+
214
+		$this->assign('requestRelatedIpRequestsCount', count($relatedIpRequests));
215
+		$this->assign('requestRelatedIpRequests', $relatedIpRequests);
216
+
217
+		$this->assign('showRevealLink', false);
218
+		if ($request->getReserved() === $currentUser->getId() ||
219
+			$this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
220
+		) {
221
+			$this->assign('showRevealLink', true);
222
+			$this->assign('revealHash', $request->getRevealHash());
223
+		}
224
+
225
+		$this->setupForwardedIpData($request);
226
+	}
227
+
228
+	/**
229
+	 * Adds checkuser request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
230
+	 *
231
+	 * @param Request $request
232
+	 */
233
+	protected function setupCheckUserData(Request $request)
234
+	{
235
+		$this->assign('requestUserAgent', $request->getUserAgent());
236
+	}
237
+
238
+	/**
239
+	 * Sets up the basic data for this request, and adds it to Smarty
240
+	 *
241
+	 * @param Request           $request
242
+	 * @param SiteConfiguration $config
243
+	 */
244
+	protected function setupBasicData(Request $request, SiteConfiguration $config)
245
+	{
246
+		$this->assign('requestId', $request->getId());
247
+		$this->assign('updateVersion', $request->getUpdateVersion());
248
+		$this->assign('requestName', $request->getName());
249
+		$this->assign('requestDate', $request->getDate());
250
+		$this->assign('requestStatus', $request->getStatus());
251
+
252
+		$this->assign('requestIsClosed', !array_key_exists($request->getStatus(), $config->getRequestStates()));
253
+	}
254
+
255
+	/**
256
+	 * Sets up the forwarded IP data for this request and adds it to Smarty
257
+	 *
258
+	 * @param Request $request
259
+	 */
260
+	protected function setupForwardedIpData(Request $request)
261
+	{
262
+		if ($request->getForwardedIp() !== null) {
263
+			$requestProxyData = array(); // Initialize array to store data to be output in Smarty template.
264
+			$proxyIndex = 0;
265
+
266
+			// Assuming [client] <=> [proxy1] <=> [proxy2] <=> [proxy3] <=> [us], we will see an XFF header of [client],
267
+			// [proxy1], [proxy2], and our actual IP will be [proxy3]
268
+			$proxies = explode(",", $request->getForwardedIp());
269
+			$proxies[] = $request->getIp();
270
+
271
+			// Origin is the supposed "client" IP.
272
+			$origin = $proxies[0];
273
+			$this->assign("forwardedOrigin", $origin);
274
+
275
+			// We step through the servers in reverse order, from closest to furthest
276
+			$proxies = array_reverse($proxies);
277
+
278
+			// By default, we have trust, because the first in the chain is now REMOTE_ADDR, which is hardest to spoof.
279
+			$trust = true;
280
+
281
+			/**
282
+			 * @var int    $index     The zero-based index of the proxy.
283
+			 * @var string $proxyData The proxy IP address (although possibly not!)
284
+			 */
285
+			foreach ($proxies as $index => $proxyData) {
286
+				$proxyAddress = trim($proxyData);
287
+				$requestProxyData[$proxyIndex]['ip'] = $proxyAddress;
288
+
289
+				// get data on this IP.
290
+				$thisProxyIsTrusted = $this->getXffTrustProvider()->isTrusted($proxyAddress);
291
+
292
+				$proxyIsInPrivateRange = $this->getXffTrustProvider()
293
+					->ipInRange(self::$rfc1918ips, $proxyAddress);
294
+
295
+				if (!$proxyIsInPrivateRange) {
296
+					$proxyReverseDns = $this->getRdnsProvider()->getReverseDNS($proxyAddress);
297
+					$proxyLocation = $this->getLocationProvider()->getIpLocation($proxyAddress);
298
+				}
299
+				else {
300
+					// this is going to fail, so why bother trying?
301
+					$proxyReverseDns = false;
302
+					$proxyLocation = false;
303
+				}
304
+
305
+				// current trust chain status BEFORE this link
306
+				$preLinkTrust = $trust;
307
+
308
+				// is *this* link trusted? Note, this will be true even if there is an untrusted link before this!
309
+				$requestProxyData[$proxyIndex]['trustedlink'] = $thisProxyIsTrusted;
310
+
311
+				// set the trust status of the chain to this point
312
+				$trust = $trust & $thisProxyIsTrusted;
313
+
314
+				// If this is the origin address, and the chain was trusted before this point, then we can trust
315
+				// the origin.
316
+				if ($preLinkTrust && $proxyAddress == $origin) {
317
+					// if this is the origin, then we are at the last point in the chain.
318
+					// @todo: this is probably the cause of some bugs when an IP appears twice - we're missing a check
319
+					// to see if this is *really* the last in the chain, rather than just the same IP as it.
320
+					$trust = true;
321
+				}
322
+
323
+				$requestProxyData[$proxyIndex]['trust'] = $trust;
324
+
325
+				$requestProxyData[$proxyIndex]['rdnsfailed'] = $proxyReverseDns === false;
326
+				$requestProxyData[$proxyIndex]['rdns'] = $proxyReverseDns;
327
+				$requestProxyData[$proxyIndex]['routable'] = !$proxyIsInPrivateRange;
328
+
329
+				$requestProxyData[$proxyIndex]['location'] = $proxyLocation;
330
+
331
+				if ($proxyReverseDns === $proxyAddress && $proxyIsInPrivateRange === false) {
332
+					$requestProxyData[$proxyIndex]['rdns'] = null;
333
+				}
334
+
335
+				$showLinks = (!$trust || $proxyAddress == $origin) && !$proxyIsInPrivateRange;
336
+				$requestProxyData[$proxyIndex]['showlinks'] = $showLinks;
337
+
338
+				$proxyIndex++;
339
+			}
340
+
341
+			$this->assign("requestProxyData", $requestProxyData);
342
+		}
343
+	}
344 344
 }
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -295,8 +295,7 @@
 block discarded – undo
295 295
                 if (!$proxyIsInPrivateRange) {
296 296
                     $proxyReverseDns = $this->getRdnsProvider()->getReverseDNS($proxyAddress);
297 297
                     $proxyLocation = $this->getLocationProvider()->getIpLocation($proxyAddress);
298
-                }
299
-                else {
298
+                } else {
300 299
                     // this is going to fail, so why bother trying?
301 300
                     $proxyReverseDns = false;
302 301
                     $proxyLocation = false;
Please login to merge, or discard this patch.
includes/Fragments/TemplateOutput.php 1 patch
Indentation   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -15,88 +15,88 @@
 block discarded – undo
15 15
 
16 16
 trait TemplateOutput
17 17
 {
18
-    /** @var Smarty */
19
-    private $smarty;
20
-    /** @var string Extra JavaScript to include at the end of the page's execution */
21
-    private $tailScript;
18
+	/** @var Smarty */
19
+	private $smarty;
20
+	/** @var string Extra JavaScript to include at the end of the page's execution */
21
+	private $tailScript;
22 22
 
23
-    /**
24
-     * @return SiteConfiguration
25
-     */
26
-    protected abstract function getSiteConfiguration();
23
+	/**
24
+	 * @return SiteConfiguration
25
+	 */
26
+	protected abstract function getSiteConfiguration();
27 27
 
28
-    /**
29
-     * Include extra JavaScript at the end of the page's execution
30
-     *
31
-     * @param $script string JavaScript to include at the end of the page
32
-     */
33
-    final protected function setTailScript($script)
34
-    {
35
-        $this->tailScript = $script;
36
-    }
28
+	/**
29
+	 * Include extra JavaScript at the end of the page's execution
30
+	 *
31
+	 * @param $script string JavaScript to include at the end of the page
32
+	 */
33
+	final protected function setTailScript($script)
34
+	{
35
+		$this->tailScript = $script;
36
+	}
37 37
 
38
-    /**
39
-     * Assigns a Smarty variable
40
-     *
41
-     * @param  array|string $name  the template variable name(s)
42
-     * @param  mixed        $value the value to assign
43
-     */
44
-    final protected function assign($name, $value)
45
-    {
46
-        $this->smarty->assign($name, $value);
47
-    }
38
+	/**
39
+	 * Assigns a Smarty variable
40
+	 *
41
+	 * @param  array|string $name  the template variable name(s)
42
+	 * @param  mixed        $value the value to assign
43
+	 */
44
+	final protected function assign($name, $value)
45
+	{
46
+		$this->smarty->assign($name, $value);
47
+	}
48 48
 
49
-    /**
50
-     * Sets up the variables used by the main Smarty base template.
51
-     *
52
-     * This list is getting kinda long.
53
-     */
54
-    final protected function setUpSmarty()
55
-    {
56
-        $this->smarty = new Smarty();
57
-        $this->smarty->addPluginsDir($this->getSiteConfiguration()->getFilePath() . '/smarty-plugins');
49
+	/**
50
+	 * Sets up the variables used by the main Smarty base template.
51
+	 *
52
+	 * This list is getting kinda long.
53
+	 */
54
+	final protected function setUpSmarty()
55
+	{
56
+		$this->smarty = new Smarty();
57
+		$this->smarty->addPluginsDir($this->getSiteConfiguration()->getFilePath() . '/smarty-plugins');
58 58
 
59
-        $this->assign('currentUser', User::getCommunity());
60
-        $this->assign('loggedIn', false);
61
-        $this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
62
-        $this->assign('mediawikiScriptPath', $this->getSiteConfiguration()->getMediawikiScriptPath());
59
+		$this->assign('currentUser', User::getCommunity());
60
+		$this->assign('loggedIn', false);
61
+		$this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
62
+		$this->assign('mediawikiScriptPath', $this->getSiteConfiguration()->getMediawikiScriptPath());
63 63
 
64
-        $this->assign('siteNoticeText', '');
65
-        $this->assign('toolversion', Environment::getToolVersion());
64
+		$this->assign('siteNoticeText', '');
65
+		$this->assign('toolversion', Environment::getToolVersion());
66 66
 
67
-        // default these
68
-        $this->assign('onlineusers', array());
69
-        $this->assign('typeAheadBlock', '');
70
-        $this->assign('extraJs', array());
71
-        $this->assign('extraCss', array());
67
+		// default these
68
+		$this->assign('onlineusers', array());
69
+		$this->assign('typeAheadBlock', '');
70
+		$this->assign('extraJs', array());
71
+		$this->assign('extraCss', array());
72 72
 
73
-        // nav menu access control
74
-        $this->assign('nav__canRequests', false);
75
-        $this->assign('nav__canLogs', false);
76
-        $this->assign('nav__canUsers', false);
77
-        $this->assign('nav__canSearch', false);
78
-        $this->assign('nav__canStats', false);
79
-        $this->assign('nav__canBan', false);
80
-        $this->assign('nav__canEmailMgmt', false);
81
-        $this->assign('nav__canWelcomeMgmt', false);
82
-        $this->assign('nav__canSiteNoticeMgmt', false);
83
-        $this->assign('nav__canUserMgmt', false);
84
-        $this->assign('nav__canViewRequest', false);
73
+		// nav menu access control
74
+		$this->assign('nav__canRequests', false);
75
+		$this->assign('nav__canLogs', false);
76
+		$this->assign('nav__canUsers', false);
77
+		$this->assign('nav__canSearch', false);
78
+		$this->assign('nav__canStats', false);
79
+		$this->assign('nav__canBan', false);
80
+		$this->assign('nav__canEmailMgmt', false);
81
+		$this->assign('nav__canWelcomeMgmt', false);
82
+		$this->assign('nav__canSiteNoticeMgmt', false);
83
+		$this->assign('nav__canUserMgmt', false);
84
+		$this->assign('nav__canViewRequest', false);
85 85
 
86
-        $this->assign('page', $this);
87
-    }
86
+		$this->assign('page', $this);
87
+	}
88 88
 
89
-    /**
90
-     * Fetches a rendered Smarty template
91
-     *
92
-     * @param $template string Template file path, relative to /templates/
93
-     *
94
-     * @return string Templated HTML
95
-     */
96
-    final protected function fetchTemplate($template)
97
-    {
98
-        $this->assign("tailScript", $this->tailScript);
89
+	/**
90
+	 * Fetches a rendered Smarty template
91
+	 *
92
+	 * @param $template string Template file path, relative to /templates/
93
+	 *
94
+	 * @return string Templated HTML
95
+	 */
96
+	final protected function fetchTemplate($template)
97
+	{
98
+		$this->assign("tailScript", $this->tailScript);
99 99
 
100
-        return $this->smarty->fetch($template);
101
-    }
100
+		return $this->smarty->fetch($template);
101
+	}
102 102
 }
Please login to merge, or discard this patch.
includes/Fragments/NavigationMenuAccessControl.php 1 patch
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -24,45 +24,45 @@
 block discarded – undo
24 24
 
25 25
 trait NavigationMenuAccessControl
26 26
 {
27
-    protected abstract function assign($name, $value);
27
+	protected abstract function assign($name, $value);
28 28
 
29
-    /**
30
-     * @return SecurityManager
31
-     */
32
-    protected abstract function getSecurityManager();
29
+	/**
30
+	 * @return SecurityManager
31
+	 */
32
+	protected abstract function getSecurityManager();
33 33
 
34
-    /**
35
-     * @param $currentUser
36
-     */
37
-    protected function setupNavMenuAccess($currentUser)
38
-    {
39
-        $this->assign('nav__canRequests', $this->getSecurityManager()
40
-                ->allows(PageMain::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
34
+	/**
35
+	 * @param $currentUser
36
+	 */
37
+	protected function setupNavMenuAccess($currentUser)
38
+	{
39
+		$this->assign('nav__canRequests', $this->getSecurityManager()
40
+				->allows(PageMain::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
41 41
 
42
-        $this->assign('nav__canLogs', $this->getSecurityManager()
43
-                ->allows(PageLog::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
44
-        $this->assign('nav__canUsers', $this->getSecurityManager()
45
-                ->allows(StatsUsers::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
46
-        $this->assign('nav__canSearch', $this->getSecurityManager()
47
-                ->allows(PageSearch::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
48
-        $this->assign('nav__canStats', $this->getSecurityManager()
49
-                ->allows(StatsMain::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
42
+		$this->assign('nav__canLogs', $this->getSecurityManager()
43
+				->allows(PageLog::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
44
+		$this->assign('nav__canUsers', $this->getSecurityManager()
45
+				->allows(StatsUsers::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
46
+		$this->assign('nav__canSearch', $this->getSecurityManager()
47
+				->allows(PageSearch::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
48
+		$this->assign('nav__canStats', $this->getSecurityManager()
49
+				->allows(StatsMain::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
50 50
 
51
-        $this->assign('nav__canBan', $this->getSecurityManager()
52
-                ->allows(PageBan::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
53
-        $this->assign('nav__canEmailMgmt', $this->getSecurityManager()
54
-                ->allows(PageEmailManagement::class, RoleConfiguration::MAIN,
55
-                    $currentUser) === SecurityManager::ALLOWED);
56
-        $this->assign('nav__canWelcomeMgmt', $this->getSecurityManager()
57
-                ->allows(PageWelcomeTemplateManagement::class, RoleConfiguration::MAIN,
58
-                    $currentUser) === SecurityManager::ALLOWED);
59
-        $this->assign('nav__canSiteNoticeMgmt', $this->getSecurityManager()
60
-                ->allows(PageSiteNotice::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
61
-        $this->assign('nav__canUserMgmt', $this->getSecurityManager()
62
-                ->allows(PageUserManagement::class, RoleConfiguration::MAIN,
63
-                    $currentUser) === SecurityManager::ALLOWED);
51
+		$this->assign('nav__canBan', $this->getSecurityManager()
52
+				->allows(PageBan::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
53
+		$this->assign('nav__canEmailMgmt', $this->getSecurityManager()
54
+				->allows(PageEmailManagement::class, RoleConfiguration::MAIN,
55
+					$currentUser) === SecurityManager::ALLOWED);
56
+		$this->assign('nav__canWelcomeMgmt', $this->getSecurityManager()
57
+				->allows(PageWelcomeTemplateManagement::class, RoleConfiguration::MAIN,
58
+					$currentUser) === SecurityManager::ALLOWED);
59
+		$this->assign('nav__canSiteNoticeMgmt', $this->getSecurityManager()
60
+				->allows(PageSiteNotice::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
61
+		$this->assign('nav__canUserMgmt', $this->getSecurityManager()
62
+				->allows(PageUserManagement::class, RoleConfiguration::MAIN,
63
+					$currentUser) === SecurityManager::ALLOWED);
64 64
 
65
-        $this->assign('nav__canViewRequest', $this->getSecurityManager()
66
-                ->allows(PageViewRequest::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
67
-    }
65
+		$this->assign('nav__canViewRequest', $this->getSecurityManager()
66
+				->allows(PageViewRequest::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
67
+	}
68 68
 }
69 69
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Validation/RequestValidationHelper.php 1 patch
Indentation   +284 added lines, -284 removed lines patch added patch discarded remove patch
@@ -22,288 +22,288 @@
 block discarded – undo
22 22
  */
23 23
 class RequestValidationHelper
24 24
 {
25
-    /** @var IBanHelper */
26
-    private $banHelper;
27
-    /** @var Request */
28
-    private $request;
29
-    private $emailConfirmation;
30
-    /** @var PdoDatabase */
31
-    private $database;
32
-    /** @var IAntiSpoofProvider */
33
-    private $antiSpoofProvider;
34
-    /** @var IXffTrustProvider */
35
-    private $xffTrustProvider;
36
-    /** @var HttpHelper */
37
-    private $httpHelper;
38
-    /**
39
-     * @var string
40
-     */
41
-    private $mediawikiApiEndpoint;
42
-    private $titleBlacklistEnabled;
43
-    /**
44
-     * @var TorExitProvider
45
-     */
46
-    private $torExitProvider;
47
-
48
-    /**
49
-     * Summary of __construct
50
-     *
51
-     * @param IBanHelper         $banHelper
52
-     * @param Request            $request
53
-     * @param string             $emailConfirmation
54
-     * @param PdoDatabase        $database
55
-     * @param IAntiSpoofProvider $antiSpoofProvider
56
-     * @param IXffTrustProvider  $xffTrustProvider
57
-     * @param HttpHelper         $httpHelper
58
-     * @param string             $mediawikiApiEndpoint
59
-     * @param boolean            $titleBlacklistEnabled
60
-     * @param TorExitProvider    $torExitProvider
61
-     */
62
-    public function __construct(
63
-        IBanHelper $banHelper,
64
-        Request $request,
65
-        $emailConfirmation,
66
-        PdoDatabase $database,
67
-        IAntiSpoofProvider $antiSpoofProvider,
68
-        IXffTrustProvider $xffTrustProvider,
69
-        HttpHelper $httpHelper,
70
-        $mediawikiApiEndpoint,
71
-        $titleBlacklistEnabled,
72
-        TorExitProvider $torExitProvider
73
-    ) {
74
-        $this->banHelper = $banHelper;
75
-        $this->request = $request;
76
-        $this->emailConfirmation = $emailConfirmation;
77
-        $this->database = $database;
78
-        $this->antiSpoofProvider = $antiSpoofProvider;
79
-        $this->xffTrustProvider = $xffTrustProvider;
80
-        $this->httpHelper = $httpHelper;
81
-        $this->mediawikiApiEndpoint = $mediawikiApiEndpoint;
82
-        $this->titleBlacklistEnabled = $titleBlacklistEnabled;
83
-        $this->torExitProvider = $torExitProvider;
84
-    }
85
-
86
-    /**
87
-     * Summary of validateName
88
-     * @return ValidationError[]
89
-     */
90
-    public function validateName()
91
-    {
92
-        $errorList = array();
93
-
94
-        // ERRORS
95
-        // name is empty
96
-        if (trim($this->request->getName()) == "") {
97
-            $errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_EMPTY);
98
-        }
99
-
100
-        // name is banned
101
-        $ban = $this->banHelper->nameIsBanned($this->request->getName());
102
-        if ($ban != false) {
103
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
104
-        }
105
-
106
-        // username already exists
107
-        if ($this->userExists()) {
108
-            $errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS);
109
-        }
110
-
111
-        // username part of SUL account
112
-        if ($this->userSulExists()) {
113
-            // using same error slot as name exists - it's the same sort of error, and we probably only want to show one.
114
-            $errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS_SUL);
115
-        }
116
-
117
-        // username is numbers
118
-        if (preg_match("/^[0-9]+$/", $this->request->getName()) === 1) {
119
-            $errorList[ValidationError::NAME_NUMONLY] = new ValidationError(ValidationError::NAME_NUMONLY);
120
-        }
121
-
122
-        // username can't contain #@/<>[]|{}
123
-        if (preg_match("/[" . preg_quote("#@/<>[]|{}", "/") . "]/", $this->request->getName()) === 1) {
124
-            $errorList[ValidationError::NAME_INVALIDCHAR] = new ValidationError(ValidationError::NAME_INVALIDCHAR);
125
-        }
126
-
127
-        // existing non-closed request for this name
128
-        if ($this->nameRequestExists()) {
129
-            $errorList[ValidationError::OPEN_REQUEST_NAME] = new ValidationError(ValidationError::OPEN_REQUEST_NAME);
130
-        }
131
-
132
-        return $errorList;
133
-    }
134
-
135
-    /**
136
-     * Summary of validateEmail
137
-     * @return ValidationError[]
138
-     */
139
-    public function validateEmail()
140
-    {
141
-        $errorList = array();
142
-
143
-        // ERRORS
144
-
145
-        // Email is banned
146
-        $ban = $this->banHelper->emailIsBanned($this->request->getEmail());
147
-        if ($ban != false) {
148
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
149
-        }
150
-
151
-        // email addresses must match
152
-        if ($this->request->getEmail() != $this->emailConfirmation) {
153
-            $errorList[ValidationError::EMAIL_MISMATCH] = new ValidationError(ValidationError::EMAIL_MISMATCH);
154
-        }
155
-
156
-        // email address must be validly formed
157
-        if (trim($this->request->getEmail()) == "") {
158
-            $errorList[ValidationError::EMAIL_EMPTY] = new ValidationError(ValidationError::EMAIL_EMPTY);
159
-        }
160
-
161
-        // email address must be validly formed
162
-        if (!filter_var($this->request->getEmail(), FILTER_VALIDATE_EMAIL)) {
163
-            if (trim($this->request->getEmail()) != "") {
164
-                $errorList[ValidationError::EMAIL_INVALID] = new ValidationError(ValidationError::EMAIL_INVALID);
165
-            }
166
-        }
167
-
168
-        // email address can't be wikimedia/wikipedia .com/org
169
-        if (preg_match('/.*@.*wiki(m.dia|p.dia)\.(org|com)/i', $this->request->getEmail()) === 1) {
170
-            $errorList[ValidationError::EMAIL_WIKIMEDIA] = new ValidationError(ValidationError::EMAIL_WIKIMEDIA);
171
-        }
172
-
173
-        // WARNINGS
174
-
175
-        return $errorList;
176
-    }
177
-
178
-    /**
179
-     * Summary of validateOther
180
-     * @return ValidationError[]
181
-     */
182
-    public function validateOther()
183
-    {
184
-        $errorList = array();
185
-
186
-        $trustedIp = $this->xffTrustProvider->getTrustedClientIp($this->request->getIp(),
187
-            $this->request->getForwardedIp());
188
-
189
-        // ERRORS
190
-
191
-        // TOR nodes
192
-        if ($this->torExitProvider->isTorExit($trustedIp)) {
193
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED_TOR);
194
-        }
195
-
196
-        // IP banned
197
-        $ban = $this->banHelper->ipIsBanned($trustedIp);
198
-        if ($ban != false) {
199
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
200
-        }
201
-
202
-        // WARNINGS
203
-
204
-        // Antispoof check
205
-        $this->checkAntiSpoof();
206
-
207
-        // Blacklist check
208
-        $this->checkTitleBlacklist();
209
-
210
-        return $errorList;
211
-    }
212
-
213
-    private function checkAntiSpoof()
214
-    {
215
-        try {
216
-            if (count($this->antiSpoofProvider->getSpoofs($this->request->getName())) > 0) {
217
-                // If there were spoofs an Admin should handle the request.
218
-                $this->request->setStatus("Flagged users");
219
-            }
220
-        }
221
-        catch (Exception $ex) {
222
-            // logme
223
-        }
224
-    }
225
-
226
-    private function checkTitleBlacklist()
227
-    {
228
-        if ($this->titleBlacklistEnabled == 1) {
229
-            $apiResult = $this->httpHelper->get(
230
-                $this->mediawikiApiEndpoint,
231
-                array(
232
-                    'action'       => 'titleblacklist',
233
-                    'tbtitle'      => $this->request->getName(),
234
-                    'tbaction'     => 'new-account',
235
-                    'tbnooverride' => true,
236
-                    'format'       => 'php',
237
-                )
238
-            );
239
-
240
-            $data = unserialize($apiResult);
241
-
242
-            $requestIsOk = $data['titleblacklist']['result'] == "ok";
243
-
244
-            if (!$requestIsOk) {
245
-                $this->request->setStatus("Flagged users");
246
-            }
247
-        }
248
-    }
249
-
250
-    private function userExists()
251
-    {
252
-        $userExists = $this->httpHelper->get(
253
-            $this->mediawikiApiEndpoint,
254
-            array(
255
-                'action'  => 'query',
256
-                'list'    => 'users',
257
-                'ususers' => $this->request->getName(),
258
-                'format'  => 'php',
259
-            )
260
-        );
261
-
262
-        $ue = unserialize($userExists);
263
-        if (!isset ($ue['query']['users']['0']['missing']) && isset ($ue['query']['users']['0']['userid'])) {
264
-            return true;
265
-        }
266
-
267
-        return false;
268
-    }
269
-
270
-    private function userSulExists()
271
-    {
272
-        $requestName = $this->request->getName();
273
-
274
-        $userExists = $this->httpHelper->get(
275
-            $this->mediawikiApiEndpoint,
276
-            array(
277
-                'action'  => 'query',
278
-                'meta'    => 'globaluserinfo',
279
-                'guiuser' => $requestName,
280
-                'format'  => 'php',
281
-            )
282
-        );
283
-
284
-        $ue = unserialize($userExists);
285
-        if (isset ($ue['query']['globaluserinfo']['id'])) {
286
-            return true;
287
-        }
288
-
289
-        return false;
290
-    }
291
-
292
-    /**
293
-     * Checks if a request with this name is currently open
294
-     *
295
-     * @return bool
296
-     */
297
-    private function nameRequestExists()
298
-    {
299
-        $query = "SELECT COUNT(id) FROM request WHERE status != 'Closed' AND name = :name;";
300
-        $statement = $this->database->prepare($query);
301
-        $statement->execute(array(':name' => $this->request->getName()));
302
-
303
-        if (!$statement) {
304
-            return false;
305
-        }
306
-
307
-        return $statement->fetchColumn() > 0;
308
-    }
25
+	/** @var IBanHelper */
26
+	private $banHelper;
27
+	/** @var Request */
28
+	private $request;
29
+	private $emailConfirmation;
30
+	/** @var PdoDatabase */
31
+	private $database;
32
+	/** @var IAntiSpoofProvider */
33
+	private $antiSpoofProvider;
34
+	/** @var IXffTrustProvider */
35
+	private $xffTrustProvider;
36
+	/** @var HttpHelper */
37
+	private $httpHelper;
38
+	/**
39
+	 * @var string
40
+	 */
41
+	private $mediawikiApiEndpoint;
42
+	private $titleBlacklistEnabled;
43
+	/**
44
+	 * @var TorExitProvider
45
+	 */
46
+	private $torExitProvider;
47
+
48
+	/**
49
+	 * Summary of __construct
50
+	 *
51
+	 * @param IBanHelper         $banHelper
52
+	 * @param Request            $request
53
+	 * @param string             $emailConfirmation
54
+	 * @param PdoDatabase        $database
55
+	 * @param IAntiSpoofProvider $antiSpoofProvider
56
+	 * @param IXffTrustProvider  $xffTrustProvider
57
+	 * @param HttpHelper         $httpHelper
58
+	 * @param string             $mediawikiApiEndpoint
59
+	 * @param boolean            $titleBlacklistEnabled
60
+	 * @param TorExitProvider    $torExitProvider
61
+	 */
62
+	public function __construct(
63
+		IBanHelper $banHelper,
64
+		Request $request,
65
+		$emailConfirmation,
66
+		PdoDatabase $database,
67
+		IAntiSpoofProvider $antiSpoofProvider,
68
+		IXffTrustProvider $xffTrustProvider,
69
+		HttpHelper $httpHelper,
70
+		$mediawikiApiEndpoint,
71
+		$titleBlacklistEnabled,
72
+		TorExitProvider $torExitProvider
73
+	) {
74
+		$this->banHelper = $banHelper;
75
+		$this->request = $request;
76
+		$this->emailConfirmation = $emailConfirmation;
77
+		$this->database = $database;
78
+		$this->antiSpoofProvider = $antiSpoofProvider;
79
+		$this->xffTrustProvider = $xffTrustProvider;
80
+		$this->httpHelper = $httpHelper;
81
+		$this->mediawikiApiEndpoint = $mediawikiApiEndpoint;
82
+		$this->titleBlacklistEnabled = $titleBlacklistEnabled;
83
+		$this->torExitProvider = $torExitProvider;
84
+	}
85
+
86
+	/**
87
+	 * Summary of validateName
88
+	 * @return ValidationError[]
89
+	 */
90
+	public function validateName()
91
+	{
92
+		$errorList = array();
93
+
94
+		// ERRORS
95
+		// name is empty
96
+		if (trim($this->request->getName()) == "") {
97
+			$errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_EMPTY);
98
+		}
99
+
100
+		// name is banned
101
+		$ban = $this->banHelper->nameIsBanned($this->request->getName());
102
+		if ($ban != false) {
103
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
104
+		}
105
+
106
+		// username already exists
107
+		if ($this->userExists()) {
108
+			$errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS);
109
+		}
110
+
111
+		// username part of SUL account
112
+		if ($this->userSulExists()) {
113
+			// using same error slot as name exists - it's the same sort of error, and we probably only want to show one.
114
+			$errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS_SUL);
115
+		}
116
+
117
+		// username is numbers
118
+		if (preg_match("/^[0-9]+$/", $this->request->getName()) === 1) {
119
+			$errorList[ValidationError::NAME_NUMONLY] = new ValidationError(ValidationError::NAME_NUMONLY);
120
+		}
121
+
122
+		// username can't contain #@/<>[]|{}
123
+		if (preg_match("/[" . preg_quote("#@/<>[]|{}", "/") . "]/", $this->request->getName()) === 1) {
124
+			$errorList[ValidationError::NAME_INVALIDCHAR] = new ValidationError(ValidationError::NAME_INVALIDCHAR);
125
+		}
126
+
127
+		// existing non-closed request for this name
128
+		if ($this->nameRequestExists()) {
129
+			$errorList[ValidationError::OPEN_REQUEST_NAME] = new ValidationError(ValidationError::OPEN_REQUEST_NAME);
130
+		}
131
+
132
+		return $errorList;
133
+	}
134
+
135
+	/**
136
+	 * Summary of validateEmail
137
+	 * @return ValidationError[]
138
+	 */
139
+	public function validateEmail()
140
+	{
141
+		$errorList = array();
142
+
143
+		// ERRORS
144
+
145
+		// Email is banned
146
+		$ban = $this->banHelper->emailIsBanned($this->request->getEmail());
147
+		if ($ban != false) {
148
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
149
+		}
150
+
151
+		// email addresses must match
152
+		if ($this->request->getEmail() != $this->emailConfirmation) {
153
+			$errorList[ValidationError::EMAIL_MISMATCH] = new ValidationError(ValidationError::EMAIL_MISMATCH);
154
+		}
155
+
156
+		// email address must be validly formed
157
+		if (trim($this->request->getEmail()) == "") {
158
+			$errorList[ValidationError::EMAIL_EMPTY] = new ValidationError(ValidationError::EMAIL_EMPTY);
159
+		}
160
+
161
+		// email address must be validly formed
162
+		if (!filter_var($this->request->getEmail(), FILTER_VALIDATE_EMAIL)) {
163
+			if (trim($this->request->getEmail()) != "") {
164
+				$errorList[ValidationError::EMAIL_INVALID] = new ValidationError(ValidationError::EMAIL_INVALID);
165
+			}
166
+		}
167
+
168
+		// email address can't be wikimedia/wikipedia .com/org
169
+		if (preg_match('/.*@.*wiki(m.dia|p.dia)\.(org|com)/i', $this->request->getEmail()) === 1) {
170
+			$errorList[ValidationError::EMAIL_WIKIMEDIA] = new ValidationError(ValidationError::EMAIL_WIKIMEDIA);
171
+		}
172
+
173
+		// WARNINGS
174
+
175
+		return $errorList;
176
+	}
177
+
178
+	/**
179
+	 * Summary of validateOther
180
+	 * @return ValidationError[]
181
+	 */
182
+	public function validateOther()
183
+	{
184
+		$errorList = array();
185
+
186
+		$trustedIp = $this->xffTrustProvider->getTrustedClientIp($this->request->getIp(),
187
+			$this->request->getForwardedIp());
188
+
189
+		// ERRORS
190
+
191
+		// TOR nodes
192
+		if ($this->torExitProvider->isTorExit($trustedIp)) {
193
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED_TOR);
194
+		}
195
+
196
+		// IP banned
197
+		$ban = $this->banHelper->ipIsBanned($trustedIp);
198
+		if ($ban != false) {
199
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
200
+		}
201
+
202
+		// WARNINGS
203
+
204
+		// Antispoof check
205
+		$this->checkAntiSpoof();
206
+
207
+		// Blacklist check
208
+		$this->checkTitleBlacklist();
209
+
210
+		return $errorList;
211
+	}
212
+
213
+	private function checkAntiSpoof()
214
+	{
215
+		try {
216
+			if (count($this->antiSpoofProvider->getSpoofs($this->request->getName())) > 0) {
217
+				// If there were spoofs an Admin should handle the request.
218
+				$this->request->setStatus("Flagged users");
219
+			}
220
+		}
221
+		catch (Exception $ex) {
222
+			// logme
223
+		}
224
+	}
225
+
226
+	private function checkTitleBlacklist()
227
+	{
228
+		if ($this->titleBlacklistEnabled == 1) {
229
+			$apiResult = $this->httpHelper->get(
230
+				$this->mediawikiApiEndpoint,
231
+				array(
232
+					'action'       => 'titleblacklist',
233
+					'tbtitle'      => $this->request->getName(),
234
+					'tbaction'     => 'new-account',
235
+					'tbnooverride' => true,
236
+					'format'       => 'php',
237
+				)
238
+			);
239
+
240
+			$data = unserialize($apiResult);
241
+
242
+			$requestIsOk = $data['titleblacklist']['result'] == "ok";
243
+
244
+			if (!$requestIsOk) {
245
+				$this->request->setStatus("Flagged users");
246
+			}
247
+		}
248
+	}
249
+
250
+	private function userExists()
251
+	{
252
+		$userExists = $this->httpHelper->get(
253
+			$this->mediawikiApiEndpoint,
254
+			array(
255
+				'action'  => 'query',
256
+				'list'    => 'users',
257
+				'ususers' => $this->request->getName(),
258
+				'format'  => 'php',
259
+			)
260
+		);
261
+
262
+		$ue = unserialize($userExists);
263
+		if (!isset ($ue['query']['users']['0']['missing']) && isset ($ue['query']['users']['0']['userid'])) {
264
+			return true;
265
+		}
266
+
267
+		return false;
268
+	}
269
+
270
+	private function userSulExists()
271
+	{
272
+		$requestName = $this->request->getName();
273
+
274
+		$userExists = $this->httpHelper->get(
275
+			$this->mediawikiApiEndpoint,
276
+			array(
277
+				'action'  => 'query',
278
+				'meta'    => 'globaluserinfo',
279
+				'guiuser' => $requestName,
280
+				'format'  => 'php',
281
+			)
282
+		);
283
+
284
+		$ue = unserialize($userExists);
285
+		if (isset ($ue['query']['globaluserinfo']['id'])) {
286
+			return true;
287
+		}
288
+
289
+		return false;
290
+	}
291
+
292
+	/**
293
+	 * Checks if a request with this name is currently open
294
+	 *
295
+	 * @return bool
296
+	 */
297
+	private function nameRequestExists()
298
+	{
299
+		$query = "SELECT COUNT(id) FROM request WHERE status != 'Closed' AND name = :name;";
300
+		$statement = $this->database->prepare($query);
301
+		$statement->execute(array(':name' => $this->request->getName()));
302
+
303
+		if (!$statement) {
304
+			return false;
305
+		}
306
+
307
+		return $statement->fetchColumn() > 0;
308
+	}
309 309
 }
Please login to merge, or discard this patch.
includes/Validation/ValidationError.php 1 patch
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -12,99 +12,99 @@
 block discarded – undo
12 12
 
13 13
 class ValidationError
14 14
 {
15
-    const NAME_EMPTY = "name_empty";
16
-    const NAME_EXISTS = "name_exists";
17
-    const NAME_EXISTS_SUL = "name_exists";
18
-    const NAME_NUMONLY = "name_numonly";
19
-    const NAME_INVALIDCHAR = "name_invalidchar";
20
-    const NAME_SANITISED = "name_sanitised";
21
-    const EMAIL_EMPTY = "email_empty";
22
-    const EMAIL_WIKIMEDIA = "email_wikimedia";
23
-    const EMAIL_INVALID = "email_invalid";
24
-    const EMAIL_MISMATCH = "email_mismatch";
25
-    const OPEN_REQUEST_NAME = "open_request_name";
26
-    const BANNED = "banned";
27
-    const BANNED_TOR = "banned_tor";
28
-    /**
29
-     * @var array Error text for the above
30
-     */
31
-    private static $errorText = array(
32
-        self::NAME_EMPTY        => 'You\'ve not chosen a username!',
33
-        self::NAME_EXISTS       => 'I\'m sorry, but the username you selected is already taken. Please try another. '
34
-            . 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
35
-            . '[[User:example]] would become [[User:Example]].',
36
-        self::NAME_EXISTS_SUL   => '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_NUMONLY      => 'The username you chose is invalid: it consists entirely of numbers. Please retry '
40
-            . 'with a valid username.',
41
-        self::NAME_INVALIDCHAR  => 'There appears to be an invalid character in your username. Please note that the '
42
-            . 'following characters are not allowed: <code># @ / &lt; &gt; [ ] | { }</code>',
43
-        self::NAME_SANITISED    => 'Your requested username has been automatically adjusted due to technical '
44
-            . 'restrictions. Underscores have been replaced with spaces, and the first character has been capitalised.',
45
-        self::EMAIL_EMPTY       => 'You need to supply an email address.',
46
-        self::EMAIL_WIKIMEDIA   => 'Please provide your email address here.',
47
-        self::EMAIL_INVALID     => 'Invalid E-mail address supplied. Please check you entered it correctly.',
48
-        self::EMAIL_MISMATCH    => 'The email addresses you entered do not match. Please try again.',
49
-        self::OPEN_REQUEST_NAME => 'There is already an open request with this name in this system.',
50
-        self::BANNED            => 'I\'m sorry, but you are currently banned from requesting accounts using this tool. '
51
-            . 'However, you can still send an email to [email protected] to request an account.',
52
-        self::BANNED_TOR        => 'Tor exit nodes are currently banned from using this tool due to excessive abuse. '
53
-            . 'Please note that Tor is also currently banned from editing Wikipedia.',
54
-    );
55
-    /**
56
-     * Summary of $errorCode
57
-     * @var string
58
-     */
59
-    private $errorCode;
60
-    /**
61
-     * Summary of $isError
62
-     * @var bool
63
-     */
64
-    private $isError;
15
+	const NAME_EMPTY = "name_empty";
16
+	const NAME_EXISTS = "name_exists";
17
+	const NAME_EXISTS_SUL = "name_exists";
18
+	const NAME_NUMONLY = "name_numonly";
19
+	const NAME_INVALIDCHAR = "name_invalidchar";
20
+	const NAME_SANITISED = "name_sanitised";
21
+	const EMAIL_EMPTY = "email_empty";
22
+	const EMAIL_WIKIMEDIA = "email_wikimedia";
23
+	const EMAIL_INVALID = "email_invalid";
24
+	const EMAIL_MISMATCH = "email_mismatch";
25
+	const OPEN_REQUEST_NAME = "open_request_name";
26
+	const BANNED = "banned";
27
+	const BANNED_TOR = "banned_tor";
28
+	/**
29
+	 * @var array Error text for the above
30
+	 */
31
+	private static $errorText = array(
32
+		self::NAME_EMPTY        => 'You\'ve not chosen a username!',
33
+		self::NAME_EXISTS       => 'I\'m sorry, but the username you selected is already taken. Please try another. '
34
+			. 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
35
+			. '[[User:example]] would become [[User:Example]].',
36
+		self::NAME_EXISTS_SUL   => '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_NUMONLY      => 'The username you chose is invalid: it consists entirely of numbers. Please retry '
40
+			. 'with a valid username.',
41
+		self::NAME_INVALIDCHAR  => 'There appears to be an invalid character in your username. Please note that the '
42
+			. 'following characters are not allowed: <code># @ / &lt; &gt; [ ] | { }</code>',
43
+		self::NAME_SANITISED    => 'Your requested username has been automatically adjusted due to technical '
44
+			. 'restrictions. Underscores have been replaced with spaces, and the first character has been capitalised.',
45
+		self::EMAIL_EMPTY       => 'You need to supply an email address.',
46
+		self::EMAIL_WIKIMEDIA   => 'Please provide your email address here.',
47
+		self::EMAIL_INVALID     => 'Invalid E-mail address supplied. Please check you entered it correctly.',
48
+		self::EMAIL_MISMATCH    => 'The email addresses you entered do not match. Please try again.',
49
+		self::OPEN_REQUEST_NAME => 'There is already an open request with this name in this system.',
50
+		self::BANNED            => 'I\'m sorry, but you are currently banned from requesting accounts using this tool. '
51
+			. 'However, you can still send an email to [email protected] to request an account.',
52
+		self::BANNED_TOR        => 'Tor exit nodes are currently banned from using this tool due to excessive abuse. '
53
+			. 'Please note that Tor is also currently banned from editing Wikipedia.',
54
+	);
55
+	/**
56
+	 * Summary of $errorCode
57
+	 * @var string
58
+	 */
59
+	private $errorCode;
60
+	/**
61
+	 * Summary of $isError
62
+	 * @var bool
63
+	 */
64
+	private $isError;
65 65
 
66
-    /**
67
-     * Summary of __construct
68
-     *
69
-     * @param string $errorCode
70
-     * @param bool   $isError
71
-     */
72
-    public function __construct($errorCode, $isError = true)
73
-    {
74
-        $this->errorCode = $errorCode;
75
-        $this->isError = $isError;
76
-    }
66
+	/**
67
+	 * Summary of __construct
68
+	 *
69
+	 * @param string $errorCode
70
+	 * @param bool   $isError
71
+	 */
72
+	public function __construct($errorCode, $isError = true)
73
+	{
74
+		$this->errorCode = $errorCode;
75
+		$this->isError = $isError;
76
+	}
77 77
 
78
-    /**
79
-     * Summary of getErrorCode
80
-     * @return string
81
-     */
82
-    public function getErrorCode()
83
-    {
84
-        return $this->errorCode;
85
-    }
78
+	/**
79
+	 * Summary of getErrorCode
80
+	 * @return string
81
+	 */
82
+	public function getErrorCode()
83
+	{
84
+		return $this->errorCode;
85
+	}
86 86
 
87
-    /**
88
-     * @return string
89
-     * @throws Exception
90
-     */
91
-    public function getErrorMessage()
92
-    {
93
-        $text = self::$errorText[$this->errorCode];
87
+	/**
88
+	 * @return string
89
+	 * @throws Exception
90
+	 */
91
+	public function getErrorMessage()
92
+	{
93
+		$text = self::$errorText[$this->errorCode];
94 94
 
95
-        if ($text == null) {
96
-            throw new Exception('Unknown validation error');
97
-        }
95
+		if ($text == null) {
96
+			throw new Exception('Unknown validation error');
97
+		}
98 98
 
99
-        return $text;
100
-    }
99
+		return $text;
100
+	}
101 101
 
102
-    /**
103
-     * Summary of isError
104
-     * @return bool
105
-     */
106
-    public function isError()
107
-    {
108
-        return $this->isError;
109
-    }
102
+	/**
103
+	 * Summary of isError
104
+	 * @return bool
105
+	 */
106
+	public function isError()
107
+	{
108
+		return $this->isError;
109
+	}
110 110
 }
Please login to merge, or discard this patch.