Failed Conditions
Push — newinternal-releasecandidate ( 327c61...a30d14 )
by Simon
15:28 queued 05:26
created
smarty-plugins/modifier.relativedate.php 2 patches
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.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
         try {
28 28
             $then = new DateTime($input);
29 29
         }
30
-        catch(Exception $ex) {
30
+        catch (Exception $ex) {
31 31
             return $input;
32 32
         }
33 33
     }
@@ -55,25 +55,25 @@  discard block
 block discarded – undo
55 55
         $pluralise = false;
56 56
     }
57 57
     elseif ($secs > 10 && $secs < $minuteCut) {
58
-        $output = round($secs / $second) . " second";
58
+        $output = round($secs / $second)." second";
59 59
     }
60 60
     elseif ($secs >= $minuteCut && $secs < $hourCut) {
61
-        $output = round($secs / $minute) . " minute";
61
+        $output = round($secs / $minute)." minute";
62 62
     }
63 63
     elseif ($secs >= $hourCut && $secs < $dayCut) {
64
-        $output = round($secs / $hour) . " hour";
64
+        $output = round($secs / $hour)." hour";
65 65
     }
66 66
     elseif ($secs >= $dayCut && $secs < $weekCut) {
67
-        $output = round($secs / $day) . " day";
67
+        $output = round($secs / $day)." day";
68 68
     }
69 69
     elseif ($secs >= $weekCut && $secs < $monthCut) {
70
-        $output = round($secs / $week) . " week";
70
+        $output = round($secs / $week)." week";
71 71
     }
72 72
     elseif ($secs >= $monthCut && $secs < $yearCut) {
73
-        $output = round($secs / $month) . " month";
73
+        $output = round($secs / $month)." month";
74 74
     }
75 75
     elseif ($secs >= $yearCut && $secs < $year * 10) {
76
-        $output = round($secs / $year) . " year";
76
+        $output = round($secs / $year)." year";
77 77
     }
78 78
     else {
79 79
         $output = "a long time ago";
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
     }
82 82
 
83 83
     if ($pluralise) {
84
-        $output = (substr($output, 0, 2) <> "1 ") ? $output . "s ago" : $output . " ago";
84
+        $output = (substr($output, 0, 2) <> "1 ") ? $output."s ago" : $output." ago";
85 85
     }
86 86
 
87 87
     return $output;
Please login to merge, or discard this patch.
includes/DataObjects/User.php 2 patches
Indentation   +567 added lines, -567 removed lines patch added patch discarded remove patch
@@ -21,160 +21,160 @@  discard block
 block discarded – undo
21 21
  */
22 22
 class User extends DataObject
23 23
 {
24
-    const STATUS_ACTIVE = 'Active';
25
-    const STATUS_SUSPENDED = 'Suspended';
26
-    const STATUS_DECLINED = 'Declined';
27
-    const STATUS_NEW = 'New';
28
-    const CREATION_MANUAL = 0;
29
-    const CREATION_OAUTH = 1;
30
-    const CREATION_BOT = 2;
31
-    private $username;
32
-    private $email;
33
-    private $status = self::STATUS_NEW;
34
-    private $onwikiname;
35
-    private $welcome_sig = "";
36
-    private $lastactive = "0000-00-00 00:00:00";
37
-    private $forcelogout = 0;
38
-    private $forceidentified = null;
39
-    private $welcome_template = 0;
40
-    private $abortpref = 0;
41
-    private $confirmationdiff = 0;
42
-    private $emailsig = "";
43
-    private $creationmode = 0;
44
-    private $skin = "main";
45
-    /** @var User Cache variable of the current user - it's never going to change in the middle of a request. */
46
-    private static $currentUser;
47
-    #region Object load methods
48
-
49
-    /**
50
-     * Gets the currently logged in user
51
-     *
52
-     * @param PdoDatabase $database
53
-     *
54
-     * @return User|CommunityUser
55
-     */
56
-    public static function getCurrent(PdoDatabase $database)
57
-    {
58
-        if (self::$currentUser === null) {
59
-            $sessionId = WebRequest::getSessionUserId();
60
-
61
-            if ($sessionId !== null) {
62
-                /** @var User $user */
63
-                $user = self::getById($sessionId, $database);
64
-
65
-                if ($user === false) {
66
-                    self::$currentUser = new CommunityUser();
67
-                }
68
-                else {
69
-                    self::$currentUser = $user;
70
-                }
71
-            }
72
-            else {
73
-                $anonymousCoward = new CommunityUser();
74
-
75
-                self::$currentUser = $anonymousCoward;
76
-            }
77
-        }
78
-
79
-        return self::$currentUser;
80
-    }
81
-
82
-    /**
83
-     * Gets a user by their user ID
84
-     *
85
-     * Pass -1 to get the community user.
86
-     *
87
-     * @param int|null    $id
88
-     * @param PdoDatabase $database
89
-     *
90
-     * @return User|false
91
-     */
92
-    public static function getById($id, PdoDatabase $database)
93
-    {
94
-        if ($id === null || $id == -1) {
95
-            return new CommunityUser();
96
-        }
97
-
98
-        /** @var User|false $user */
99
-        $user = parent::getById($id, $database);
100
-
101
-        return $user;
102
-    }
103
-
104
-    /**
105
-     * @return CommunityUser
106
-     */
107
-    public static function getCommunity()
108
-    {
109
-        return new CommunityUser();
110
-    }
111
-
112
-    /**
113
-     * Gets a user by their username
114
-     *
115
-     * @param  string      $username
116
-     * @param  PdoDatabase $database
117
-     *
118
-     * @return CommunityUser|User|false
119
-     */
120
-    public static function getByUsername($username, PdoDatabase $database)
121
-    {
122
-        global $communityUsername;
123
-        if ($username == $communityUsername) {
124
-            return new CommunityUser();
125
-        }
126
-
127
-        $statement = $database->prepare("SELECT * FROM user WHERE username = :id LIMIT 1;");
128
-        $statement->bindValue(":id", $username);
129
-
130
-        $statement->execute();
131
-
132
-        $resultObject = $statement->fetchObject(get_called_class());
133
-
134
-        if ($resultObject != false) {
135
-            $resultObject->setDatabase($database);
136
-        }
137
-
138
-        return $resultObject;
139
-    }
140
-
141
-    /**
142
-     * Gets a user by their on-wiki username.
143
-     *
144
-     * @param string      $username
145
-     * @param PdoDatabase $database
146
-     *
147
-     * @return User|false
148
-     */
149
-    public static function getByOnWikiUsername($username, PdoDatabase $database)
150
-    {
151
-        $statement = $database->prepare("SELECT * FROM user WHERE onwikiname = :id LIMIT 1;");
152
-        $statement->bindValue(":id", $username);
153
-        $statement->execute();
154
-
155
-        $resultObject = $statement->fetchObject(get_called_class());
156
-
157
-        if ($resultObject != false) {
158
-            $resultObject->setDatabase($database);
159
-
160
-            return $resultObject;
161
-        }
162
-
163
-        return false;
164
-    }
165
-
166
-    #endregion
167
-
168
-    /**
169
-     * Saves the current object
170
-     *
171
-     * @throws Exception
172
-     */
173
-    public function save()
174
-    {
175
-        if ($this->isNew()) {
176
-            // insert
177
-            $statement = $this->dbObject->prepare(<<<SQL
24
+	const STATUS_ACTIVE = 'Active';
25
+	const STATUS_SUSPENDED = 'Suspended';
26
+	const STATUS_DECLINED = 'Declined';
27
+	const STATUS_NEW = 'New';
28
+	const CREATION_MANUAL = 0;
29
+	const CREATION_OAUTH = 1;
30
+	const CREATION_BOT = 2;
31
+	private $username;
32
+	private $email;
33
+	private $status = self::STATUS_NEW;
34
+	private $onwikiname;
35
+	private $welcome_sig = "";
36
+	private $lastactive = "0000-00-00 00:00:00";
37
+	private $forcelogout = 0;
38
+	private $forceidentified = null;
39
+	private $welcome_template = 0;
40
+	private $abortpref = 0;
41
+	private $confirmationdiff = 0;
42
+	private $emailsig = "";
43
+	private $creationmode = 0;
44
+	private $skin = "main";
45
+	/** @var User Cache variable of the current user - it's never going to change in the middle of a request. */
46
+	private static $currentUser;
47
+	#region Object load methods
48
+
49
+	/**
50
+	 * Gets the currently logged in user
51
+	 *
52
+	 * @param PdoDatabase $database
53
+	 *
54
+	 * @return User|CommunityUser
55
+	 */
56
+	public static function getCurrent(PdoDatabase $database)
57
+	{
58
+		if (self::$currentUser === null) {
59
+			$sessionId = WebRequest::getSessionUserId();
60
+
61
+			if ($sessionId !== null) {
62
+				/** @var User $user */
63
+				$user = self::getById($sessionId, $database);
64
+
65
+				if ($user === false) {
66
+					self::$currentUser = new CommunityUser();
67
+				}
68
+				else {
69
+					self::$currentUser = $user;
70
+				}
71
+			}
72
+			else {
73
+				$anonymousCoward = new CommunityUser();
74
+
75
+				self::$currentUser = $anonymousCoward;
76
+			}
77
+		}
78
+
79
+		return self::$currentUser;
80
+	}
81
+
82
+	/**
83
+	 * Gets a user by their user ID
84
+	 *
85
+	 * Pass -1 to get the community user.
86
+	 *
87
+	 * @param int|null    $id
88
+	 * @param PdoDatabase $database
89
+	 *
90
+	 * @return User|false
91
+	 */
92
+	public static function getById($id, PdoDatabase $database)
93
+	{
94
+		if ($id === null || $id == -1) {
95
+			return new CommunityUser();
96
+		}
97
+
98
+		/** @var User|false $user */
99
+		$user = parent::getById($id, $database);
100
+
101
+		return $user;
102
+	}
103
+
104
+	/**
105
+	 * @return CommunityUser
106
+	 */
107
+	public static function getCommunity()
108
+	{
109
+		return new CommunityUser();
110
+	}
111
+
112
+	/**
113
+	 * Gets a user by their username
114
+	 *
115
+	 * @param  string      $username
116
+	 * @param  PdoDatabase $database
117
+	 *
118
+	 * @return CommunityUser|User|false
119
+	 */
120
+	public static function getByUsername($username, PdoDatabase $database)
121
+	{
122
+		global $communityUsername;
123
+		if ($username == $communityUsername) {
124
+			return new CommunityUser();
125
+		}
126
+
127
+		$statement = $database->prepare("SELECT * FROM user WHERE username = :id LIMIT 1;");
128
+		$statement->bindValue(":id", $username);
129
+
130
+		$statement->execute();
131
+
132
+		$resultObject = $statement->fetchObject(get_called_class());
133
+
134
+		if ($resultObject != false) {
135
+			$resultObject->setDatabase($database);
136
+		}
137
+
138
+		return $resultObject;
139
+	}
140
+
141
+	/**
142
+	 * Gets a user by their on-wiki username.
143
+	 *
144
+	 * @param string      $username
145
+	 * @param PdoDatabase $database
146
+	 *
147
+	 * @return User|false
148
+	 */
149
+	public static function getByOnWikiUsername($username, PdoDatabase $database)
150
+	{
151
+		$statement = $database->prepare("SELECT * FROM user WHERE onwikiname = :id LIMIT 1;");
152
+		$statement->bindValue(":id", $username);
153
+		$statement->execute();
154
+
155
+		$resultObject = $statement->fetchObject(get_called_class());
156
+
157
+		if ($resultObject != false) {
158
+			$resultObject->setDatabase($database);
159
+
160
+			return $resultObject;
161
+		}
162
+
163
+		return false;
164
+	}
165
+
166
+	#endregion
167
+
168
+	/**
169
+	 * Saves the current object
170
+	 *
171
+	 * @throws Exception
172
+	 */
173
+	public function save()
174
+	{
175
+		if ($this->isNew()) {
176
+			// insert
177
+			$statement = $this->dbObject->prepare(<<<SQL
178 178
 				INSERT INTO `user` ( 
179 179
 					username, email, status, onwikiname, welcome_sig, 
180 180
 					lastactive, forcelogout, forceidentified,
@@ -185,32 +185,32 @@  discard block
 block discarded – undo
185 185
 					:welcome_template, :abortpref, :confirmationdiff, :emailsig, :creationmode, :skin
186 186
 				);
187 187
 SQL
188
-            );
189
-            $statement->bindValue(":username", $this->username);
190
-            $statement->bindValue(":email", $this->email);
191
-            $statement->bindValue(":status", $this->status);
192
-            $statement->bindValue(":onwikiname", $this->onwikiname);
193
-            $statement->bindValue(":welcome_sig", $this->welcome_sig);
194
-            $statement->bindValue(":lastactive", $this->lastactive);
195
-            $statement->bindValue(":forcelogout", $this->forcelogout);
196
-            $statement->bindValue(":forceidentified", $this->forceidentified);
197
-            $statement->bindValue(":welcome_template", $this->welcome_template);
198
-            $statement->bindValue(":abortpref", $this->abortpref);
199
-            $statement->bindValue(":confirmationdiff", $this->confirmationdiff);
200
-            $statement->bindValue(":emailsig", $this->emailsig);
201
-            $statement->bindValue(":creationmode", $this->creationmode);
202
-            $statement->bindValue(":skin", $this->skin);
203
-
204
-            if ($statement->execute()) {
205
-                $this->id = (int)$this->dbObject->lastInsertId();
206
-            }
207
-            else {
208
-                throw new Exception($statement->errorInfo());
209
-            }
210
-        }
211
-        else {
212
-            // update
213
-            $statement = $this->dbObject->prepare(<<<SQL
188
+			);
189
+			$statement->bindValue(":username", $this->username);
190
+			$statement->bindValue(":email", $this->email);
191
+			$statement->bindValue(":status", $this->status);
192
+			$statement->bindValue(":onwikiname", $this->onwikiname);
193
+			$statement->bindValue(":welcome_sig", $this->welcome_sig);
194
+			$statement->bindValue(":lastactive", $this->lastactive);
195
+			$statement->bindValue(":forcelogout", $this->forcelogout);
196
+			$statement->bindValue(":forceidentified", $this->forceidentified);
197
+			$statement->bindValue(":welcome_template", $this->welcome_template);
198
+			$statement->bindValue(":abortpref", $this->abortpref);
199
+			$statement->bindValue(":confirmationdiff", $this->confirmationdiff);
200
+			$statement->bindValue(":emailsig", $this->emailsig);
201
+			$statement->bindValue(":creationmode", $this->creationmode);
202
+			$statement->bindValue(":skin", $this->skin);
203
+
204
+			if ($statement->execute()) {
205
+				$this->id = (int)$this->dbObject->lastInsertId();
206
+			}
207
+			else {
208
+				throw new Exception($statement->errorInfo());
209
+			}
210
+		}
211
+		else {
212
+			// update
213
+			$statement = $this->dbObject->prepare(<<<SQL
214 214
 				UPDATE `user` SET 
215 215
 					username = :username, email = :email, 
216 216
 					status = :status,
@@ -223,387 +223,387 @@  discard block
 block discarded – undo
223 223
                     updateversion = updateversion + 1
224 224
 				WHERE id = :id AND updateversion = :updateversion;
225 225
 SQL
226
-            );
227
-            $statement->bindValue(":forceidentified", $this->forceidentified);
228
-
229
-            $statement->bindValue(':id', $this->id);
230
-            $statement->bindValue(':updateversion', $this->updateversion);
231
-
232
-            $statement->bindValue(':username', $this->username);
233
-            $statement->bindValue(':email', $this->email);
234
-            $statement->bindValue(':status', $this->status);
235
-            $statement->bindValue(':onwikiname', $this->onwikiname);
236
-            $statement->bindValue(':welcome_sig', $this->welcome_sig);
237
-            $statement->bindValue(':lastactive', $this->lastactive);
238
-            $statement->bindValue(':forcelogout', $this->forcelogout);
239
-            $statement->bindValue(':forceidentified', $this->forceidentified);
240
-            $statement->bindValue(':welcome_template', $this->welcome_template);
241
-            $statement->bindValue(':abortpref', $this->abortpref);
242
-            $statement->bindValue(':confirmationdiff', $this->confirmationdiff);
243
-            $statement->bindValue(':emailsig', $this->emailsig);
244
-            $statement->bindValue(':creationmode', $this->creationmode);
245
-            $statement->bindValue(':skin', $this->skin);
246
-
247
-            if (!$statement->execute()) {
248
-                throw new Exception($statement->errorInfo());
249
-            }
250
-
251
-            if ($statement->rowCount() !== 1) {
252
-                throw new OptimisticLockFailedException();
253
-            }
254
-
255
-            $this->updateversion++;
256
-        }
257
-    }
258
-
259
-    #region properties
260
-
261
-    /**
262
-     * Gets the tool username
263
-     * @return string
264
-     */
265
-    public function getUsername()
266
-    {
267
-        return $this->username;
268
-    }
269
-
270
-    /**
271
-     * Sets the tool username
272
-     *
273
-     * @param string $username
274
-     */
275
-    public function setUsername($username)
276
-    {
277
-        $this->username = $username;
278
-
279
-        // If this isn't a brand new user, then it's a rename, force the logout
280
-        if (!$this->isNew()) {
281
-            $this->forcelogout = 1;
282
-        }
283
-    }
284
-
285
-    /**
286
-     * Gets the user's email address
287
-     * @return string
288
-     */
289
-    public function getEmail()
290
-    {
291
-        return $this->email;
292
-    }
293
-
294
-    /**
295
-     * Sets the user's email address
296
-     *
297
-     * @param string $email
298
-     */
299
-    public function setEmail($email)
300
-    {
301
-        $this->email = $email;
302
-    }
303
-
304
-    /**
305
-     * Gets the status (User, Admin, Suspended, etc - excludes checkuser) of the user.
306
-     * @return string
307
-     */
308
-    public function getStatus()
309
-    {
310
-        return $this->status;
311
-    }
312
-
313
-    /**
314
-     * @param string $status
315
-     */
316
-    public function setStatus($status)
317
-    {
318
-        $this->status = $status;
319
-    }
320
-
321
-    /**
322
-     * Gets the user's on-wiki name
323
-     * @return string
324
-     */
325
-    public function getOnWikiName()
326
-    {
327
-        return $this->onwikiname;
328
-    }
329
-
330
-    /**
331
-     * Sets the user's on-wiki name
332
-     *
333
-     * This can have interesting side-effects with OAuth.
334
-     *
335
-     * @param string $onWikiName
336
-     */
337
-    public function setOnWikiName($onWikiName)
338
-    {
339
-        $this->onwikiname = $onWikiName;
340
-    }
341
-
342
-    /**
343
-     * Gets the welcome signature
344
-     * @return string
345
-     */
346
-    public function getWelcomeSig()
347
-    {
348
-        return $this->welcome_sig;
349
-    }
350
-
351
-    /**
352
-     * Sets the welcome signature
353
-     *
354
-     * @param string $welcomeSig
355
-     */
356
-    public function setWelcomeSig($welcomeSig)
357
-    {
358
-        $this->welcome_sig = $welcomeSig;
359
-    }
360
-
361
-    /**
362
-     * Gets the last activity date for the user
363
-     *
364
-     * @return string
365
-     * @todo This should probably return an instance of DateTime
366
-     */
367
-    public function getLastActive()
368
-    {
369
-        return $this->lastactive;
370
-    }
371
-
372
-    /**
373
-     * Gets the user's forced logout status
374
-     *
375
-     * @return bool
376
-     */
377
-    public function getForceLogout()
378
-    {
379
-        return $this->forcelogout == 1;
380
-    }
381
-
382
-    /**
383
-     * Sets the user's forced logout status
384
-     *
385
-     * @param bool $forceLogout
386
-     */
387
-    public function setForceLogout($forceLogout)
388
-    {
389
-        $this->forcelogout = $forceLogout ? 1 : 0;
390
-    }
391
-
392
-    /**
393
-     * Returns the ID of the welcome template used.
394
-     * @return int
395
-     */
396
-    public function getWelcomeTemplate()
397
-    {
398
-        return $this->welcome_template;
399
-    }
400
-
401
-    /**
402
-     * Sets the ID of the welcome template used.
403
-     *
404
-     * @param int $welcomeTemplate
405
-     */
406
-    public function setWelcomeTemplate($welcomeTemplate)
407
-    {
408
-        $this->welcome_template = $welcomeTemplate;
409
-    }
410
-
411
-    /**
412
-     * Gets the user's abort preference
413
-     * @todo this is badly named too! Also a bool that's actually an int.
414
-     * @return int
415
-     */
416
-    public function getAbortPref()
417
-    {
418
-        return $this->abortpref;
419
-    }
420
-
421
-    /**
422
-     * Sets the user's abort preference
423
-     * @todo rename, retype, and re-comment.
424
-     *
425
-     * @param int $abortPreference
426
-     */
427
-    public function setAbortPref($abortPreference)
428
-    {
429
-        $this->abortpref = $abortPreference;
430
-    }
431
-
432
-    /**
433
-     * Gets the user's confirmation diff. Unused if OAuth is in use.
434
-     * @return int the diff ID
435
-     */
436
-    public function getConfirmationDiff()
437
-    {
438
-        return $this->confirmationdiff;
439
-    }
440
-
441
-    /**
442
-     * Sets the user's confirmation diff.
443
-     *
444
-     * @param int $confirmationDiff
445
-     */
446
-    public function setConfirmationDiff($confirmationDiff)
447
-    {
448
-        $this->confirmationdiff = $confirmationDiff;
449
-    }
450
-
451
-    /**
452
-     * Gets the users' email signature used on outbound mail.
453
-     * @todo rename me!
454
-     * @return string
455
-     */
456
-    public function getEmailSig()
457
-    {
458
-        return $this->emailsig;
459
-    }
460
-
461
-    /**
462
-     * Sets the user's email signature for outbound mail.
463
-     *
464
-     * @param string $emailSignature
465
-     */
466
-    public function setEmailSig($emailSignature)
467
-    {
468
-        $this->emailsig = $emailSignature;
469
-    }
470
-
471
-    /**
472
-     * @return int
473
-     */
474
-    public function getCreationMode()
475
-    {
476
-        return $this->creationmode;
477
-    }
478
-
479
-    /**
480
-     * @param $creationMode int
481
-     */
482
-    public function setCreationMode($creationMode)
483
-    {
484
-        $this->creationmode = $creationMode;
485
-    }
486
-
487
-    /**
488
-     * @return boolean
489
-     */
490
-    public function getUseAlternateSkin()
491
-    {
492
-        return $this->skin === 'alt';
493
-    }
494
-
495
-    /**
496
-     * @return string
497
-     */
498
-    public function getSkin()
499
-    {
500
-        return $this->skin;
501
-    }
502
-
503
-    /**
504
-     * @param $skin string
505
-     */
506
-    public function setSkin($skin)
507
-    {
508
-        $this->skin = $skin;
509
-    }
510
-
511
-    #endregion
512
-
513
-    #region user access checks
514
-
515
-    public function isActive()
516
-    {
517
-        return $this->status == self::STATUS_ACTIVE;
518
-    }
519
-
520
-    /**
521
-     * Tests if the user is identified
522
-     *
523
-     * @param IdentificationVerifier $iv
524
-     *
525
-     * @return bool
526
-     * @todo     Figure out what on earth is going on with PDO's typecasting here.  Apparently, it returns string("0") for
527
-     *       the force-unidentified case, and int(1) for the identified case?!  This is quite ugly, but probably needed
528
-     *       to play it safe for now.
529
-     * @category Security-Critical
530
-     */
531
-    public function isIdentified(IdentificationVerifier $iv)
532
-    {
533
-        if ($this->forceidentified === 0 || $this->forceidentified === "0") {
534
-            // User forced to unidentified in the database.
535
-            return false;
536
-        }
537
-        elseif ($this->forceidentified === 1 || $this->forceidentified === "1") {
538
-            // User forced to identified in the database.
539
-            return true;
540
-        }
541
-        else {
542
-            // User not forced to any particular identified status; consult IdentificationVerifier
543
-            return $iv->isUserIdentified($this->getOnWikiName());
544
-        }
545
-    }
546
-
547
-    /**
548
-     * DO NOT USE FOR TESTING IDENTIFICATION STATUS.
549
-     *
550
-     * @return bool|null
551
-     */
552
-    public function getForceIdentified() {
553
-        return $this->forceidentified;
554
-    }
555
-
556
-    /**
557
-     * Tests if the user is suspended
558
-     * @return bool
559
-     * @category Security-Critical
560
-     */
561
-    public function isSuspended()
562
-    {
563
-        return $this->status == self::STATUS_SUSPENDED;
564
-    }
565
-
566
-    /**
567
-     * Tests if the user is new
568
-     * @return bool
569
-     * @category Security-Critical
570
-     */
571
-    public function isNewUser()
572
-    {
573
-        return $this->status == self::STATUS_NEW;
574
-    }
575
-
576
-    /**
577
-     * Tests if the user has been declined access to the tool
578
-     * @return bool
579
-     * @category Security-Critical
580
-     */
581
-    public function isDeclined()
582
-    {
583
-        return $this->status == self::STATUS_DECLINED;
584
-    }
585
-
586
-    /**
587
-     * Tests if the user is the community user
588
-     *
589
-     * @todo     decide if this means logged out. I think it usually does.
590
-     * @return bool
591
-     * @category Security-Critical
592
-     */
593
-    public function isCommunityUser()
594
-    {
595
-        return false;
596
-    }
597
-
598
-    #endregion 
599
-
600
-    /**
601
-     * Gets the approval date of the user
602
-     * @return DateTime|false
603
-     */
604
-    public function getApprovalDate()
605
-    {
606
-        $query = $this->dbObject->prepare(<<<SQL
226
+			);
227
+			$statement->bindValue(":forceidentified", $this->forceidentified);
228
+
229
+			$statement->bindValue(':id', $this->id);
230
+			$statement->bindValue(':updateversion', $this->updateversion);
231
+
232
+			$statement->bindValue(':username', $this->username);
233
+			$statement->bindValue(':email', $this->email);
234
+			$statement->bindValue(':status', $this->status);
235
+			$statement->bindValue(':onwikiname', $this->onwikiname);
236
+			$statement->bindValue(':welcome_sig', $this->welcome_sig);
237
+			$statement->bindValue(':lastactive', $this->lastactive);
238
+			$statement->bindValue(':forcelogout', $this->forcelogout);
239
+			$statement->bindValue(':forceidentified', $this->forceidentified);
240
+			$statement->bindValue(':welcome_template', $this->welcome_template);
241
+			$statement->bindValue(':abortpref', $this->abortpref);
242
+			$statement->bindValue(':confirmationdiff', $this->confirmationdiff);
243
+			$statement->bindValue(':emailsig', $this->emailsig);
244
+			$statement->bindValue(':creationmode', $this->creationmode);
245
+			$statement->bindValue(':skin', $this->skin);
246
+
247
+			if (!$statement->execute()) {
248
+				throw new Exception($statement->errorInfo());
249
+			}
250
+
251
+			if ($statement->rowCount() !== 1) {
252
+				throw new OptimisticLockFailedException();
253
+			}
254
+
255
+			$this->updateversion++;
256
+		}
257
+	}
258
+
259
+	#region properties
260
+
261
+	/**
262
+	 * Gets the tool username
263
+	 * @return string
264
+	 */
265
+	public function getUsername()
266
+	{
267
+		return $this->username;
268
+	}
269
+
270
+	/**
271
+	 * Sets the tool username
272
+	 *
273
+	 * @param string $username
274
+	 */
275
+	public function setUsername($username)
276
+	{
277
+		$this->username = $username;
278
+
279
+		// If this isn't a brand new user, then it's a rename, force the logout
280
+		if (!$this->isNew()) {
281
+			$this->forcelogout = 1;
282
+		}
283
+	}
284
+
285
+	/**
286
+	 * Gets the user's email address
287
+	 * @return string
288
+	 */
289
+	public function getEmail()
290
+	{
291
+		return $this->email;
292
+	}
293
+
294
+	/**
295
+	 * Sets the user's email address
296
+	 *
297
+	 * @param string $email
298
+	 */
299
+	public function setEmail($email)
300
+	{
301
+		$this->email = $email;
302
+	}
303
+
304
+	/**
305
+	 * Gets the status (User, Admin, Suspended, etc - excludes checkuser) of the user.
306
+	 * @return string
307
+	 */
308
+	public function getStatus()
309
+	{
310
+		return $this->status;
311
+	}
312
+
313
+	/**
314
+	 * @param string $status
315
+	 */
316
+	public function setStatus($status)
317
+	{
318
+		$this->status = $status;
319
+	}
320
+
321
+	/**
322
+	 * Gets the user's on-wiki name
323
+	 * @return string
324
+	 */
325
+	public function getOnWikiName()
326
+	{
327
+		return $this->onwikiname;
328
+	}
329
+
330
+	/**
331
+	 * Sets the user's on-wiki name
332
+	 *
333
+	 * This can have interesting side-effects with OAuth.
334
+	 *
335
+	 * @param string $onWikiName
336
+	 */
337
+	public function setOnWikiName($onWikiName)
338
+	{
339
+		$this->onwikiname = $onWikiName;
340
+	}
341
+
342
+	/**
343
+	 * Gets the welcome signature
344
+	 * @return string
345
+	 */
346
+	public function getWelcomeSig()
347
+	{
348
+		return $this->welcome_sig;
349
+	}
350
+
351
+	/**
352
+	 * Sets the welcome signature
353
+	 *
354
+	 * @param string $welcomeSig
355
+	 */
356
+	public function setWelcomeSig($welcomeSig)
357
+	{
358
+		$this->welcome_sig = $welcomeSig;
359
+	}
360
+
361
+	/**
362
+	 * Gets the last activity date for the user
363
+	 *
364
+	 * @return string
365
+	 * @todo This should probably return an instance of DateTime
366
+	 */
367
+	public function getLastActive()
368
+	{
369
+		return $this->lastactive;
370
+	}
371
+
372
+	/**
373
+	 * Gets the user's forced logout status
374
+	 *
375
+	 * @return bool
376
+	 */
377
+	public function getForceLogout()
378
+	{
379
+		return $this->forcelogout == 1;
380
+	}
381
+
382
+	/**
383
+	 * Sets the user's forced logout status
384
+	 *
385
+	 * @param bool $forceLogout
386
+	 */
387
+	public function setForceLogout($forceLogout)
388
+	{
389
+		$this->forcelogout = $forceLogout ? 1 : 0;
390
+	}
391
+
392
+	/**
393
+	 * Returns the ID of the welcome template used.
394
+	 * @return int
395
+	 */
396
+	public function getWelcomeTemplate()
397
+	{
398
+		return $this->welcome_template;
399
+	}
400
+
401
+	/**
402
+	 * Sets the ID of the welcome template used.
403
+	 *
404
+	 * @param int $welcomeTemplate
405
+	 */
406
+	public function setWelcomeTemplate($welcomeTemplate)
407
+	{
408
+		$this->welcome_template = $welcomeTemplate;
409
+	}
410
+
411
+	/**
412
+	 * Gets the user's abort preference
413
+	 * @todo this is badly named too! Also a bool that's actually an int.
414
+	 * @return int
415
+	 */
416
+	public function getAbortPref()
417
+	{
418
+		return $this->abortpref;
419
+	}
420
+
421
+	/**
422
+	 * Sets the user's abort preference
423
+	 * @todo rename, retype, and re-comment.
424
+	 *
425
+	 * @param int $abortPreference
426
+	 */
427
+	public function setAbortPref($abortPreference)
428
+	{
429
+		$this->abortpref = $abortPreference;
430
+	}
431
+
432
+	/**
433
+	 * Gets the user's confirmation diff. Unused if OAuth is in use.
434
+	 * @return int the diff ID
435
+	 */
436
+	public function getConfirmationDiff()
437
+	{
438
+		return $this->confirmationdiff;
439
+	}
440
+
441
+	/**
442
+	 * Sets the user's confirmation diff.
443
+	 *
444
+	 * @param int $confirmationDiff
445
+	 */
446
+	public function setConfirmationDiff($confirmationDiff)
447
+	{
448
+		$this->confirmationdiff = $confirmationDiff;
449
+	}
450
+
451
+	/**
452
+	 * Gets the users' email signature used on outbound mail.
453
+	 * @todo rename me!
454
+	 * @return string
455
+	 */
456
+	public function getEmailSig()
457
+	{
458
+		return $this->emailsig;
459
+	}
460
+
461
+	/**
462
+	 * Sets the user's email signature for outbound mail.
463
+	 *
464
+	 * @param string $emailSignature
465
+	 */
466
+	public function setEmailSig($emailSignature)
467
+	{
468
+		$this->emailsig = $emailSignature;
469
+	}
470
+
471
+	/**
472
+	 * @return int
473
+	 */
474
+	public function getCreationMode()
475
+	{
476
+		return $this->creationmode;
477
+	}
478
+
479
+	/**
480
+	 * @param $creationMode int
481
+	 */
482
+	public function setCreationMode($creationMode)
483
+	{
484
+		$this->creationmode = $creationMode;
485
+	}
486
+
487
+	/**
488
+	 * @return boolean
489
+	 */
490
+	public function getUseAlternateSkin()
491
+	{
492
+		return $this->skin === 'alt';
493
+	}
494
+
495
+	/**
496
+	 * @return string
497
+	 */
498
+	public function getSkin()
499
+	{
500
+		return $this->skin;
501
+	}
502
+
503
+	/**
504
+	 * @param $skin string
505
+	 */
506
+	public function setSkin($skin)
507
+	{
508
+		$this->skin = $skin;
509
+	}
510
+
511
+	#endregion
512
+
513
+	#region user access checks
514
+
515
+	public function isActive()
516
+	{
517
+		return $this->status == self::STATUS_ACTIVE;
518
+	}
519
+
520
+	/**
521
+	 * Tests if the user is identified
522
+	 *
523
+	 * @param IdentificationVerifier $iv
524
+	 *
525
+	 * @return bool
526
+	 * @todo     Figure out what on earth is going on with PDO's typecasting here.  Apparently, it returns string("0") for
527
+	 *       the force-unidentified case, and int(1) for the identified case?!  This is quite ugly, but probably needed
528
+	 *       to play it safe for now.
529
+	 * @category Security-Critical
530
+	 */
531
+	public function isIdentified(IdentificationVerifier $iv)
532
+	{
533
+		if ($this->forceidentified === 0 || $this->forceidentified === "0") {
534
+			// User forced to unidentified in the database.
535
+			return false;
536
+		}
537
+		elseif ($this->forceidentified === 1 || $this->forceidentified === "1") {
538
+			// User forced to identified in the database.
539
+			return true;
540
+		}
541
+		else {
542
+			// User not forced to any particular identified status; consult IdentificationVerifier
543
+			return $iv->isUserIdentified($this->getOnWikiName());
544
+		}
545
+	}
546
+
547
+	/**
548
+	 * DO NOT USE FOR TESTING IDENTIFICATION STATUS.
549
+	 *
550
+	 * @return bool|null
551
+	 */
552
+	public function getForceIdentified() {
553
+		return $this->forceidentified;
554
+	}
555
+
556
+	/**
557
+	 * Tests if the user is suspended
558
+	 * @return bool
559
+	 * @category Security-Critical
560
+	 */
561
+	public function isSuspended()
562
+	{
563
+		return $this->status == self::STATUS_SUSPENDED;
564
+	}
565
+
566
+	/**
567
+	 * Tests if the user is new
568
+	 * @return bool
569
+	 * @category Security-Critical
570
+	 */
571
+	public function isNewUser()
572
+	{
573
+		return $this->status == self::STATUS_NEW;
574
+	}
575
+
576
+	/**
577
+	 * Tests if the user has been declined access to the tool
578
+	 * @return bool
579
+	 * @category Security-Critical
580
+	 */
581
+	public function isDeclined()
582
+	{
583
+		return $this->status == self::STATUS_DECLINED;
584
+	}
585
+
586
+	/**
587
+	 * Tests if the user is the community user
588
+	 *
589
+	 * @todo     decide if this means logged out. I think it usually does.
590
+	 * @return bool
591
+	 * @category Security-Critical
592
+	 */
593
+	public function isCommunityUser()
594
+	{
595
+		return false;
596
+	}
597
+
598
+	#endregion 
599
+
600
+	/**
601
+	 * Gets the approval date of the user
602
+	 * @return DateTime|false
603
+	 */
604
+	public function getApprovalDate()
605
+	{
606
+		$query = $this->dbObject->prepare(<<<SQL
607 607
 			SELECT timestamp 
608 608
 			FROM log 
609 609
 			WHERE objectid = :userid
@@ -612,12 +612,12 @@  discard block
 block discarded – undo
612 612
 			ORDER BY id DESC 
613 613
 			LIMIT 1;
614 614
 SQL
615
-        );
616
-        $query->execute(array(":userid" => $this->id));
615
+		);
616
+		$query->execute(array(":userid" => $this->id));
617 617
 
618
-        $data = DateTime::createFromFormat("Y-m-d H:i:s", $query->fetchColumn());
619
-        $query->closeCursor();
618
+		$data = DateTime::createFromFormat("Y-m-d H:i:s", $query->fetchColumn());
619
+		$query->closeCursor();
620 620
 
621
-        return $data;
622
-    }
621
+		return $data;
622
+	}
623 623
 }
Please login to merge, or discard this patch.
Braces   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -549,7 +549,8 @@
 block discarded – undo
549 549
      *
550 550
      * @return bool|null
551 551
      */
552
-    public function getForceIdentified() {
552
+    public function getForceIdentified()
553
+    {
553 554
         return $this->forceidentified;
554 555
     }
555 556
 
Please login to merge, or discard this patch.
includes/Background/BackgroundTaskBase.php 2 patches
Indentation   +263 added lines, -263 removed lines patch added patch discarded remove patch
@@ -23,267 +23,267 @@
 block discarded – undo
23 23
 
24 24
 abstract class BackgroundTaskBase
25 25
 {
26
-    /** @var JobQueue */
27
-    private $job;
28
-    /** @var PdoDatabase */
29
-    private $database;
30
-    /** @var IOAuthProtocolHelper */
31
-    private $oauthProtocolHelper;
32
-    /** @var SiteConfiguration */
33
-    private $siteConfiguration;
34
-    /** @var IEmailHelper */
35
-    private $emailHelper;
36
-    /** @var HttpHelper */
37
-    private $httpHelper;
38
-    /** @var IrcNotificationHelper */
39
-    private $notificationHelper;
40
-    /** @var User */
41
-    private $triggerUser;
42
-    /** @var Request */
43
-    private $request;
44
-    /** @var EmailTemplate */
45
-    private $emailTemplate = null;
46
-    /** @var mixed */
47
-    private $parameters;
48
-
49
-    /**
50
-     * @return JobQueue
51
-     */
52
-    public function getJob()
53
-    {
54
-        return $this->job;
55
-    }
56
-
57
-    /**
58
-     * @param JobQueue $job
59
-     */
60
-    public function setJob(JobQueue $job)
61
-    {
62
-        $this->job = $job;
63
-    }
64
-
65
-    /**
66
-     * @return PdoDatabase
67
-     */
68
-    public function getDatabase()
69
-    {
70
-        return $this->database;
71
-    }
72
-
73
-    /**
74
-     * @param PdoDatabase $database
75
-     */
76
-    public function setDatabase(PdoDatabase $database)
77
-    {
78
-        $this->database = $database;
79
-    }
80
-
81
-    /**
82
-     * @return IOAuthProtocolHelper
83
-     */
84
-    public function getOauthProtocolHelper()
85
-    {
86
-        return $this->oauthProtocolHelper;
87
-    }
88
-
89
-    /**
90
-     * @param IOAuthProtocolHelper $oauthProtocolHelper
91
-     */
92
-    public function setOauthProtocolHelper(IOAuthProtocolHelper $oauthProtocolHelper)
93
-    {
94
-        $this->oauthProtocolHelper = $oauthProtocolHelper;
95
-    }
96
-
97
-    /**
98
-     * @return SiteConfiguration
99
-     */
100
-    public function getSiteConfiguration()
101
-    {
102
-        return $this->siteConfiguration;
103
-    }
104
-
105
-    /**
106
-     * @param SiteConfiguration $siteConfiguration
107
-     */
108
-    public function setSiteConfiguration(SiteConfiguration $siteConfiguration)
109
-    {
110
-        $this->siteConfiguration = $siteConfiguration;
111
-    }
112
-
113
-    /**
114
-     * @return HttpHelper
115
-     */
116
-    public function getHttpHelper()
117
-    {
118
-        return $this->httpHelper;
119
-    }
120
-
121
-    /**
122
-     * @param HttpHelper $httpHelper
123
-     */
124
-    public function setHttpHelper(HttpHelper $httpHelper)
125
-    {
126
-        $this->httpHelper = $httpHelper;
127
-    }
128
-
129
-    /**
130
-     * @return IEmailHelper
131
-     */
132
-    public function getEmailHelper()
133
-    {
134
-        return $this->emailHelper;
135
-    }
136
-
137
-    /**
138
-     * @param IEmailHelper $emailHelper
139
-     */
140
-    public function setEmailHelper(IEmailHelper $emailHelper)
141
-    {
142
-        $this->emailHelper = $emailHelper;
143
-    }
144
-
145
-    /**
146
-     * @return IrcNotificationHelper
147
-     */
148
-    public function getNotificationHelper()
149
-    {
150
-        return $this->notificationHelper;
151
-    }
152
-
153
-    /**
154
-     * @param IrcNotificationHelper $notificationHelper
155
-     */
156
-    public function setNotificationHelper($notificationHelper)
157
-    {
158
-        $this->notificationHelper = $notificationHelper;
159
-    }
160
-
161
-    /**
162
-     * @return void
163
-     */
164
-    protected abstract function execute();
165
-
166
-    public function run()
167
-    {
168
-        $this->triggerUser = User::getById($this->job->getTriggerUserId(), $this->getDatabase());
169
-
170
-        if ($this->triggerUser === false) {
171
-            throw new ApplicationLogicException('Cannot locate trigger user');
172
-        }
173
-
174
-        $this->request = Request::getById($this->job->getRequest(), $this->getDatabase());
175
-
176
-        if ($this->request === false) {
177
-            throw new ApplicationLogicException('Cannot locate request');
178
-        }
179
-
180
-        if($this->job->getEmailTemplate() !== null){
181
-            $this->emailTemplate = EmailTemplate::getById($this->job->getEmailTemplate(), $this->getDatabase());
182
-
183
-            if ($this->emailTemplate === false) {
184
-                throw new ApplicationLogicException('Cannot locate email template');
185
-            }
186
-        }
187
-
188
-        if($this->job->getParameters() !== null) {
189
-            $this->parameters = json_decode($this->job->getParameters());
190
-
191
-            if (json_last_error() !== JSON_ERROR_NONE) {
192
-                throw new ApplicationLogicException('JSON decode: ' . json_last_error_msg());
193
-            }
194
-        }
195
-
196
-        // Should we wait for a parent job?
197
-        if($this->job->getParent() !== null) {
198
-            /** @var JobQueue $parentJob */
199
-            $parentJob = JobQueue::getById($this->job->getParent(), $this->getDatabase());
200
-
201
-            if($parentJob === false) {
202
-                $this->markFailed("Parent job could not be found");
203
-                return;
204
-            }
205
-
206
-            switch ($parentJob->getStatus()) {
207
-                case JobQueue::STATUS_CANCELLED:
208
-                case JobQueue::STATUS_FAILED:
209
-                    $this->markCancelled('Parent job failed/cancelled');
210
-                    return;
211
-                case JobQueue::STATUS_WAITING:
212
-                case JobQueue::STATUS_READY:
213
-                case JobQueue::STATUS_RUNNING:
214
-                case JobQueue::STATUS_HELD:
215
-                    // Defer to next execution
216
-                    $this->job->setStatus(JobQueue::STATUS_READY);
217
-                    $this->job->save();
218
-                    return;
219
-                case JobQueue::STATUS_COMPLETE:
220
-                    // do nothing
221
-                    break;
222
-            }
223
-        }
224
-
225
-        $this->execute();
226
-    }
227
-
228
-    protected function markComplete()
229
-    {
230
-        $this->job->setStatus(JobQueue::STATUS_COMPLETE);
231
-        $this->job->setError(null);
232
-        $this->job->setAcknowledged(null);
233
-        $this->job->save();
234
-
235
-        Logger::backgroundJobComplete($this->getDatabase(), $this->getJob());
236
-    }
237
-
238
-    protected function markCancelled($reason = null)
239
-    {
240
-        $this->job->setStatus(JobQueue::STATUS_CANCELLED);
241
-        $this->job->setError($reason);
242
-        $this->job->setAcknowledged(null);
243
-        $this->job->save();
244
-
245
-        Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
246
-    }
247
-
248
-    protected function markFailed($reason = null)
249
-    {
250
-        $this->job->setStatus(JobQueue::STATUS_FAILED);
251
-        $this->job->setError($reason);
252
-        $this->job->setAcknowledged(0);
253
-        $this->job->save();
254
-
255
-        Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
256
-    }
257
-
258
-    /**
259
-     * @return User
260
-     */
261
-    public function getTriggerUser()
262
-    {
263
-        return $this->triggerUser;
264
-    }
265
-
266
-    /**
267
-     * @return Request
268
-     */
269
-    public function getRequest()
270
-    {
271
-        return $this->request;
272
-    }
273
-
274
-    /**
275
-     * @return EmailTemplate
276
-     */
277
-    public function getEmailTemplate()
278
-    {
279
-        return $this->emailTemplate;
280
-    }
281
-
282
-    /**
283
-     * @return mixed
284
-     */
285
-    public function getParameters()
286
-    {
287
-        return $this->parameters;
288
-    }
26
+	/** @var JobQueue */
27
+	private $job;
28
+	/** @var PdoDatabase */
29
+	private $database;
30
+	/** @var IOAuthProtocolHelper */
31
+	private $oauthProtocolHelper;
32
+	/** @var SiteConfiguration */
33
+	private $siteConfiguration;
34
+	/** @var IEmailHelper */
35
+	private $emailHelper;
36
+	/** @var HttpHelper */
37
+	private $httpHelper;
38
+	/** @var IrcNotificationHelper */
39
+	private $notificationHelper;
40
+	/** @var User */
41
+	private $triggerUser;
42
+	/** @var Request */
43
+	private $request;
44
+	/** @var EmailTemplate */
45
+	private $emailTemplate = null;
46
+	/** @var mixed */
47
+	private $parameters;
48
+
49
+	/**
50
+	 * @return JobQueue
51
+	 */
52
+	public function getJob()
53
+	{
54
+		return $this->job;
55
+	}
56
+
57
+	/**
58
+	 * @param JobQueue $job
59
+	 */
60
+	public function setJob(JobQueue $job)
61
+	{
62
+		$this->job = $job;
63
+	}
64
+
65
+	/**
66
+	 * @return PdoDatabase
67
+	 */
68
+	public function getDatabase()
69
+	{
70
+		return $this->database;
71
+	}
72
+
73
+	/**
74
+	 * @param PdoDatabase $database
75
+	 */
76
+	public function setDatabase(PdoDatabase $database)
77
+	{
78
+		$this->database = $database;
79
+	}
80
+
81
+	/**
82
+	 * @return IOAuthProtocolHelper
83
+	 */
84
+	public function getOauthProtocolHelper()
85
+	{
86
+		return $this->oauthProtocolHelper;
87
+	}
88
+
89
+	/**
90
+	 * @param IOAuthProtocolHelper $oauthProtocolHelper
91
+	 */
92
+	public function setOauthProtocolHelper(IOAuthProtocolHelper $oauthProtocolHelper)
93
+	{
94
+		$this->oauthProtocolHelper = $oauthProtocolHelper;
95
+	}
96
+
97
+	/**
98
+	 * @return SiteConfiguration
99
+	 */
100
+	public function getSiteConfiguration()
101
+	{
102
+		return $this->siteConfiguration;
103
+	}
104
+
105
+	/**
106
+	 * @param SiteConfiguration $siteConfiguration
107
+	 */
108
+	public function setSiteConfiguration(SiteConfiguration $siteConfiguration)
109
+	{
110
+		$this->siteConfiguration = $siteConfiguration;
111
+	}
112
+
113
+	/**
114
+	 * @return HttpHelper
115
+	 */
116
+	public function getHttpHelper()
117
+	{
118
+		return $this->httpHelper;
119
+	}
120
+
121
+	/**
122
+	 * @param HttpHelper $httpHelper
123
+	 */
124
+	public function setHttpHelper(HttpHelper $httpHelper)
125
+	{
126
+		$this->httpHelper = $httpHelper;
127
+	}
128
+
129
+	/**
130
+	 * @return IEmailHelper
131
+	 */
132
+	public function getEmailHelper()
133
+	{
134
+		return $this->emailHelper;
135
+	}
136
+
137
+	/**
138
+	 * @param IEmailHelper $emailHelper
139
+	 */
140
+	public function setEmailHelper(IEmailHelper $emailHelper)
141
+	{
142
+		$this->emailHelper = $emailHelper;
143
+	}
144
+
145
+	/**
146
+	 * @return IrcNotificationHelper
147
+	 */
148
+	public function getNotificationHelper()
149
+	{
150
+		return $this->notificationHelper;
151
+	}
152
+
153
+	/**
154
+	 * @param IrcNotificationHelper $notificationHelper
155
+	 */
156
+	public function setNotificationHelper($notificationHelper)
157
+	{
158
+		$this->notificationHelper = $notificationHelper;
159
+	}
160
+
161
+	/**
162
+	 * @return void
163
+	 */
164
+	protected abstract function execute();
165
+
166
+	public function run()
167
+	{
168
+		$this->triggerUser = User::getById($this->job->getTriggerUserId(), $this->getDatabase());
169
+
170
+		if ($this->triggerUser === false) {
171
+			throw new ApplicationLogicException('Cannot locate trigger user');
172
+		}
173
+
174
+		$this->request = Request::getById($this->job->getRequest(), $this->getDatabase());
175
+
176
+		if ($this->request === false) {
177
+			throw new ApplicationLogicException('Cannot locate request');
178
+		}
179
+
180
+		if($this->job->getEmailTemplate() !== null){
181
+			$this->emailTemplate = EmailTemplate::getById($this->job->getEmailTemplate(), $this->getDatabase());
182
+
183
+			if ($this->emailTemplate === false) {
184
+				throw new ApplicationLogicException('Cannot locate email template');
185
+			}
186
+		}
187
+
188
+		if($this->job->getParameters() !== null) {
189
+			$this->parameters = json_decode($this->job->getParameters());
190
+
191
+			if (json_last_error() !== JSON_ERROR_NONE) {
192
+				throw new ApplicationLogicException('JSON decode: ' . json_last_error_msg());
193
+			}
194
+		}
195
+
196
+		// Should we wait for a parent job?
197
+		if($this->job->getParent() !== null) {
198
+			/** @var JobQueue $parentJob */
199
+			$parentJob = JobQueue::getById($this->job->getParent(), $this->getDatabase());
200
+
201
+			if($parentJob === false) {
202
+				$this->markFailed("Parent job could not be found");
203
+				return;
204
+			}
205
+
206
+			switch ($parentJob->getStatus()) {
207
+				case JobQueue::STATUS_CANCELLED:
208
+				case JobQueue::STATUS_FAILED:
209
+					$this->markCancelled('Parent job failed/cancelled');
210
+					return;
211
+				case JobQueue::STATUS_WAITING:
212
+				case JobQueue::STATUS_READY:
213
+				case JobQueue::STATUS_RUNNING:
214
+				case JobQueue::STATUS_HELD:
215
+					// Defer to next execution
216
+					$this->job->setStatus(JobQueue::STATUS_READY);
217
+					$this->job->save();
218
+					return;
219
+				case JobQueue::STATUS_COMPLETE:
220
+					// do nothing
221
+					break;
222
+			}
223
+		}
224
+
225
+		$this->execute();
226
+	}
227
+
228
+	protected function markComplete()
229
+	{
230
+		$this->job->setStatus(JobQueue::STATUS_COMPLETE);
231
+		$this->job->setError(null);
232
+		$this->job->setAcknowledged(null);
233
+		$this->job->save();
234
+
235
+		Logger::backgroundJobComplete($this->getDatabase(), $this->getJob());
236
+	}
237
+
238
+	protected function markCancelled($reason = null)
239
+	{
240
+		$this->job->setStatus(JobQueue::STATUS_CANCELLED);
241
+		$this->job->setError($reason);
242
+		$this->job->setAcknowledged(null);
243
+		$this->job->save();
244
+
245
+		Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
246
+	}
247
+
248
+	protected function markFailed($reason = null)
249
+	{
250
+		$this->job->setStatus(JobQueue::STATUS_FAILED);
251
+		$this->job->setError($reason);
252
+		$this->job->setAcknowledged(0);
253
+		$this->job->save();
254
+
255
+		Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
256
+	}
257
+
258
+	/**
259
+	 * @return User
260
+	 */
261
+	public function getTriggerUser()
262
+	{
263
+		return $this->triggerUser;
264
+	}
265
+
266
+	/**
267
+	 * @return Request
268
+	 */
269
+	public function getRequest()
270
+	{
271
+		return $this->request;
272
+	}
273
+
274
+	/**
275
+	 * @return EmailTemplate
276
+	 */
277
+	public function getEmailTemplate()
278
+	{
279
+		return $this->emailTemplate;
280
+	}
281
+
282
+	/**
283
+	 * @return mixed
284
+	 */
285
+	public function getParameters()
286
+	{
287
+		return $this->parameters;
288
+	}
289 289
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
             throw new ApplicationLogicException('Cannot locate request');
178 178
         }
179 179
 
180
-        if($this->job->getEmailTemplate() !== null){
180
+        if ($this->job->getEmailTemplate() !== null) {
181 181
             $this->emailTemplate = EmailTemplate::getById($this->job->getEmailTemplate(), $this->getDatabase());
182 182
 
183 183
             if ($this->emailTemplate === false) {
@@ -185,20 +185,20 @@  discard block
 block discarded – undo
185 185
             }
186 186
         }
187 187
 
188
-        if($this->job->getParameters() !== null) {
188
+        if ($this->job->getParameters() !== null) {
189 189
             $this->parameters = json_decode($this->job->getParameters());
190 190
 
191 191
             if (json_last_error() !== JSON_ERROR_NONE) {
192
-                throw new ApplicationLogicException('JSON decode: ' . json_last_error_msg());
192
+                throw new ApplicationLogicException('JSON decode: '.json_last_error_msg());
193 193
             }
194 194
         }
195 195
 
196 196
         // Should we wait for a parent job?
197
-        if($this->job->getParent() !== null) {
197
+        if ($this->job->getParent() !== null) {
198 198
             /** @var JobQueue $parentJob */
199 199
             $parentJob = JobQueue::getById($this->job->getParent(), $this->getDatabase());
200 200
 
201
-            if($parentJob === false) {
201
+            if ($parentJob === false) {
202 202
                 $this->markFailed("Parent job could not be found");
203 203
                 return;
204 204
             }
Please login to merge, or discard this patch.
includes/Pages/Statistics/StatsUsers.php 3 patches
Indentation   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -23,13 +23,13 @@  discard block
 block discarded – undo
23 23
 
24 24
 class StatsUsers extends InternalPageBase
25 25
 {
26
-    public function main()
27
-    {
28
-        $this->setHtmlTitle('Users :: Statistics');
26
+	public function main()
27
+	{
28
+		$this->setHtmlTitle('Users :: Statistics');
29 29
 
30
-        $database = $this->getDatabase();
30
+		$database = $this->getDatabase();
31 31
 
32
-        $query = <<<SQL
32
+		$query = <<<SQL
33 33
 SELECT
34 34
     u.id
35 35
     , u.username
@@ -45,34 +45,34 @@  discard block
 block discarded – undo
45 45
 WHERE u.status = 'Active'
46 46
 SQL;
47 47
 
48
-        $users = $database->query($query)->fetchAll(PDO::FETCH_ASSOC);
49
-        $this->assign('users', $users);
48
+		$users = $database->query($query)->fetchAll(PDO::FETCH_ASSOC);
49
+		$this->assign('users', $users);
50 50
 
51
-        $this->assign('statsPageTitle', 'Account Creation Tool users');
52
-        $this->setTemplate("statistics/users.tpl");
53
-    }
51
+		$this->assign('statsPageTitle', 'Account Creation Tool users');
52
+		$this->setTemplate("statistics/users.tpl");
53
+	}
54 54
 
55
-    /**
56
-     * Entry point for the detail action.
57
-     *
58
-     * @throws ApplicationLogicException
59
-     */
60
-    protected function detail()
61
-    {
62
-        $userId = WebRequest::getInt('user');
63
-        if ($userId === null) {
64
-            throw new ApplicationLogicException("User not found");
65
-        }
55
+	/**
56
+	 * Entry point for the detail action.
57
+	 *
58
+	 * @throws ApplicationLogicException
59
+	 */
60
+	protected function detail()
61
+	{
62
+		$userId = WebRequest::getInt('user');
63
+		if ($userId === null) {
64
+			throw new ApplicationLogicException("User not found");
65
+		}
66 66
 
67
-        $database = $this->getDatabase();
67
+		$database = $this->getDatabase();
68 68
 
69
-        $user = User::getById($userId, $database);
70
-        if ($user == false) {
71
-            throw new ApplicationLogicException('User not found');
72
-        }
69
+		$user = User::getById($userId, $database);
70
+		if ($user == false) {
71
+			throw new ApplicationLogicException('User not found');
72
+		}
73 73
 
74 74
 
75
-        $activitySummary = $database->prepare(<<<SQL
75
+		$activitySummary = $database->prepare(<<<SQL
76 76
 SELECT COALESCE(closes.mail_desc, log.action) AS action, COUNT(*) AS count
77 77
 FROM log
78 78
 INNER JOIN user ON log.user = user.id
@@ -80,14 +80,14 @@  discard block
 block discarded – undo
80 80
 WHERE user.username = :username
81 81
 GROUP BY action;
82 82
 SQL
83
-        );
84
-        $activitySummary->execute(array(":username" => $user->getUsername()));
85
-        $activitySummaryData = $activitySummary->fetchAll(PDO::FETCH_ASSOC);
83
+		);
84
+		$activitySummary->execute(array(":username" => $user->getUsername()));
85
+		$activitySummaryData = $activitySummary->fetchAll(PDO::FETCH_ASSOC);
86 86
 
87
-        $this->assign("user", $user);
88
-        $this->assign("activity", $activitySummaryData);
87
+		$this->assign("user", $user);
88
+		$this->assign("activity", $activitySummaryData);
89 89
 
90
-        $usersCreatedQuery = $database->prepare(<<<SQL
90
+		$usersCreatedQuery = $database->prepare(<<<SQL
91 91
 SELECT log.timestamp time, request.name name, request.id id
92 92
 FROM log
93 93
 INNER JOIN request ON (request.id = log.objectid AND log.objecttype = 'Request')
@@ -98,12 +98,12 @@  discard block
 block discarded – undo
98 98
     AND (emailtemplate.oncreated = '1' OR log.action = 'Closed custom-y')
99 99
 ORDER BY log.timestamp;
100 100
 SQL
101
-        );
102
-        $usersCreatedQuery->execute(array(":username" => $user->getUsername()));
103
-        $usersCreated = $usersCreatedQuery->fetchAll(PDO::FETCH_ASSOC);
104
-        $this->assign("created", $usersCreated);
101
+		);
102
+		$usersCreatedQuery->execute(array(":username" => $user->getUsername()));
103
+		$usersCreated = $usersCreatedQuery->fetchAll(PDO::FETCH_ASSOC);
104
+		$this->assign("created", $usersCreated);
105 105
 
106
-        $usersNotCreatedQuery = $database->prepare(<<<SQL
106
+		$usersNotCreatedQuery = $database->prepare(<<<SQL
107 107
 SELECT log.timestamp time, request.name name, request.id id
108 108
 FROM log
109 109
 JOIN request ON request.id = log.objectid AND log.objecttype = 'Request'
@@ -114,54 +114,54 @@  discard block
 block discarded – undo
114 114
     AND (emailtemplate.oncreated = '0' OR log.action = 'Closed custom-n' OR log.action = 'Closed 0')
115 115
 ORDER BY log.timestamp;
116 116
 SQL
117
-        );
118
-        $usersNotCreatedQuery->execute(array(":username" => $user->getUsername()));
119
-        $usersNotCreated = $usersNotCreatedQuery->fetchAll(PDO::FETCH_ASSOC);
120
-        $this->assign("notcreated", $usersNotCreated);
121
-
122
-        /** @var Log[] $logs */
123
-        $logs = LogSearchHelper::get($database)
124
-            ->byObjectType('User')
125
-            ->byObjectId($user->getId())
126
-            ->getRecordCount($logCount)
127
-            ->fetch();
128
-
129
-        if ($logCount === 0) {
130
-            $this->assign('accountlog', array());
131
-        }
132
-        else {
133
-            list($users, $logData) = LogHelper::prepareLogsForTemplate($logs, $database, $this->getSiteConfiguration());
134
-
135
-            $this->assign("accountlog", $logData);
136
-            $this->assign("users", $users);
137
-        }
138
-
139
-        $currentUser = User::getCurrent($database);
140
-        $this->assign('canApprove', $this->barrierTest('approve', $currentUser, PageUserManagement::class));
141
-        $this->assign('canDecline', $this->barrierTest('decline', $currentUser, PageUserManagement::class));
142
-        $this->assign('canRename', $this->barrierTest('rename', $currentUser, PageUserManagement::class));
143
-        $this->assign('canEditUser', $this->barrierTest('editUser', $currentUser, PageUserManagement::class));
144
-        $this->assign('canSuspend', $this->barrierTest('suspend', $currentUser, PageUserManagement::class));
145
-        $this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser, PageUserManagement::class));
146
-
147
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
148
-        $this->assign('oauth', $oauth);
149
-
150
-        if($user->getForceIdentified() === null) {
151
-            $idVerifier = new IdentificationVerifier($this->getHttpHelper(), $this->getSiteConfiguration(), $this->getDatabase());
152
-            $this->assign('identificationStatus', $idVerifier->isUserIdentified($user->getOnWikiName()) ? 'detected' : 'missing');
153
-        } else {
154
-            $this->assign('identificationStatus', $user->getForceIdentified() == 1 ? 'forced-on' : 'forced-off');
155
-        }
156
-
157
-        if ($oauth->isFullyLinked()) {
158
-            $this->assign('identity', $oauth->getIdentity(true));
159
-            $this->assign('identityExpired', $oauth->identityExpired());
160
-        }
161
-
162
-        $this->assign('statsPageTitle', 'Account Creation Tool users');
163
-
164
-        $this->setHtmlTitle('{$user->getUsername()|escape} :: Users :: Statistics');
165
-        $this->setTemplate("statistics/userdetail.tpl");
166
-    }
117
+		);
118
+		$usersNotCreatedQuery->execute(array(":username" => $user->getUsername()));
119
+		$usersNotCreated = $usersNotCreatedQuery->fetchAll(PDO::FETCH_ASSOC);
120
+		$this->assign("notcreated", $usersNotCreated);
121
+
122
+		/** @var Log[] $logs */
123
+		$logs = LogSearchHelper::get($database)
124
+			->byObjectType('User')
125
+			->byObjectId($user->getId())
126
+			->getRecordCount($logCount)
127
+			->fetch();
128
+
129
+		if ($logCount === 0) {
130
+			$this->assign('accountlog', array());
131
+		}
132
+		else {
133
+			list($users, $logData) = LogHelper::prepareLogsForTemplate($logs, $database, $this->getSiteConfiguration());
134
+
135
+			$this->assign("accountlog", $logData);
136
+			$this->assign("users", $users);
137
+		}
138
+
139
+		$currentUser = User::getCurrent($database);
140
+		$this->assign('canApprove', $this->barrierTest('approve', $currentUser, PageUserManagement::class));
141
+		$this->assign('canDecline', $this->barrierTest('decline', $currentUser, PageUserManagement::class));
142
+		$this->assign('canRename', $this->barrierTest('rename', $currentUser, PageUserManagement::class));
143
+		$this->assign('canEditUser', $this->barrierTest('editUser', $currentUser, PageUserManagement::class));
144
+		$this->assign('canSuspend', $this->barrierTest('suspend', $currentUser, PageUserManagement::class));
145
+		$this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser, PageUserManagement::class));
146
+
147
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
148
+		$this->assign('oauth', $oauth);
149
+
150
+		if($user->getForceIdentified() === null) {
151
+			$idVerifier = new IdentificationVerifier($this->getHttpHelper(), $this->getSiteConfiguration(), $this->getDatabase());
152
+			$this->assign('identificationStatus', $idVerifier->isUserIdentified($user->getOnWikiName()) ? 'detected' : 'missing');
153
+		} else {
154
+			$this->assign('identificationStatus', $user->getForceIdentified() == 1 ? 'forced-on' : 'forced-off');
155
+		}
156
+
157
+		if ($oauth->isFullyLinked()) {
158
+			$this->assign('identity', $oauth->getIdentity(true));
159
+			$this->assign('identityExpired', $oauth->identityExpired());
160
+		}
161
+
162
+		$this->assign('statsPageTitle', 'Account Creation Tool users');
163
+
164
+		$this->setHtmlTitle('{$user->getUsername()|escape} :: Users :: Statistics');
165
+		$this->setTemplate("statistics/userdetail.tpl");
166
+	}
167 167
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -147,7 +147,7 @@
 block discarded – undo
147 147
         $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
148 148
         $this->assign('oauth', $oauth);
149 149
 
150
-        if($user->getForceIdentified() === null) {
150
+        if ($user->getForceIdentified() === null) {
151 151
             $idVerifier = new IdentificationVerifier($this->getHttpHelper(), $this->getSiteConfiguration(), $this->getDatabase());
152 152
             $this->assign('identificationStatus', $idVerifier->isUserIdentified($user->getOnWikiName()) ? 'detected' : 'missing');
153 153
         } else {
Please login to merge, or discard this patch.
Braces   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -150,7 +150,8 @@
 block discarded – undo
150 150
         if($user->getForceIdentified() === null) {
151 151
             $idVerifier = new IdentificationVerifier($this->getHttpHelper(), $this->getSiteConfiguration(), $this->getDatabase());
152 152
             $this->assign('identificationStatus', $idVerifier->isUserIdentified($user->getOnWikiName()) ? 'detected' : 'missing');
153
-        } else {
153
+        }
154
+        else {
154 155
             $this->assign('identificationStatus', $user->getForceIdentified() == 1 ? 'forced-on' : 'forced-off');
155 156
         }
156 157
 
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageCreateRequest.php 1 patch
Indentation   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -33,151 +33,151 @@
 block discarded – undo
33 33
  */
34 34
 class PageCreateRequest extends RequestActionBase
35 35
 {
36
-    /**
37
-     * Main function for this page, when no specific actions are called.
38
-     * @return void
39
-     * @throws AccessDeniedException
40
-     * @throws ApplicationLogicException
41
-     */
42
-    protected function main()
43
-    {
44
-        $this->checkPosted();
45
-
46
-        $database = $this->getDatabase();
47
-
48
-        $request = $this->getRequest($database);
49
-        $template = $this->getTemplate($database);
50
-        $creationMode = $this->getCreationMode();
51
-        $user = User::getCurrent($database);
52
-
53
-        $secMgr = $this->getSecurityManager();
54
-        if ($secMgr->allows('RequestCreation', User::CREATION_BOT, $user) !== SecurityManager::ALLOWED
55
-            && $creationMode === 'bot'
56
-        ) {
57
-            throw new AccessDeniedException($secMgr);
58
-        }
59
-        elseif ($secMgr->allows('RequestCreation', User::CREATION_OAUTH, $user) !== SecurityManager::ALLOWED
60
-            && $creationMode === 'oauth'
61
-        ) {
62
-            throw new AccessDeniedException($secMgr);
63
-        }
64
-
65
-        if ($request->getEmailSent()) {
66
-            throw new ApplicationLogicException('This requester has already had an email sent to them. Please fall back to manual creation');
67
-        }
68
-
69
-        $request->setStatus(RequestStatus::JOBQUEUE);
70
-        $request->setReserved(null);
71
-        $request->save();
72
-
73
-        Logger::enqueuedJobQueue($database, $request);
74
-
75
-        $creationTaskId = $this->enqueueCreationTask($creationMode, $request, $template, $user, $database);
76
-
77
-        if ($user->getWelcomeTemplate() !== null && !WebRequest::postBoolean('skipAutoWelcome')) {
78
-            $this->enqueueWelcomeTask($request, $creationTaskId, $user, $database);
79
-        }
80
-
81
-        SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
82
-
83
-        $this->redirect();
84
-    }
85
-
86
-    protected function getCreationMode()
87
-    {
88
-        $creationMode = WebRequest::postString('mode');
89
-        if ($creationMode !== 'oauth' && $creationMode !== 'bot') {
90
-            throw new ApplicationLogicException('Unknown creation mode');
91
-        }
92
-
93
-        return $creationMode;
94
-    }
95
-
96
-    /**
97
-     * @param PdoDatabase $database
98
-     *
99
-     * @return EmailTemplate
100
-     * @throws ApplicationLogicException
101
-     */
102
-    protected function getTemplate(PdoDatabase $database)
103
-    {
104
-        $templateId = WebRequest::postInt('template');
105
-        if ($templateId === null) {
106
-            throw new ApplicationLogicException('No template specified');
107
-        }
108
-
109
-        /** @var EmailTemplate $template */
110
-        $template = EmailTemplate::getById($templateId, $database);
111
-        if ($template === false || !$template->getActive()) {
112
-            throw new ApplicationLogicException('Invalid or inactive template specified');
113
-        }
114
-
115
-        if ($template->getDefaultAction() !== EmailTemplate::CREATED) {
116
-            throw new ApplicationLogicException('Specified template is not a creation template!');
117
-        }
118
-
119
-        return $template;
120
-    }
121
-
122
-    /**
123
-     * @param PdoDatabase $database
124
-     *
125
-     * @return Request
126
-     * @throws ApplicationLogicException
127
-     */
128
-    protected function getRequest(PdoDatabase $database)
129
-    {
130
-        $request = parent::getRequest($database);
131
-
132
-        if ($request->getStatus() == RequestStatus::CLOSED) {
133
-            throw new ApplicationLogicException('Request is already closed');
134
-        }
135
-
136
-        return $request;
137
-    }
138
-
139
-    /**
140
-     * @param               $creationMode
141
-     * @param Request       $request
142
-     * @param EmailTemplate $template
143
-     * @param User          $user
144
-     *
145
-     * @param PdoDatabase   $database
146
-     *
147
-     * @return int
148
-     * @throws ApplicationLogicException
149
-     */
150
-    protected function enqueueCreationTask(
151
-        $creationMode,
152
-        Request $request,
153
-        EmailTemplate $template,
154
-        User $user,
155
-        PdoDatabase $database
156
-    ) {
157
-        $creationTaskClass = null;
158
-
159
-        if ($creationMode == "oauth") {
160
-            $creationTaskClass = UserCreationTask::class;
161
-        }
162
-
163
-        if ($creationMode == "bot") {
164
-            $creationTaskClass = BotCreationTask::class;
165
-        }
166
-
167
-        if ($creationTaskClass === null) {
168
-            throw new ApplicationLogicException('Cannot determine creation mode');
169
-        }
170
-
171
-        $creationTask = new JobQueue();
172
-        $creationTask->setTask($creationTaskClass);
173
-        $creationTask->setRequest($request->getId());
174
-        $creationTask->setEmailTemplate($template->getId());
175
-        $creationTask->setTriggerUserId($user->getId());
176
-        $creationTask->setDatabase($database);
177
-        $creationTask->save();
178
-
179
-        $creationTaskId = $creationTask->getId();
180
-
181
-        return $creationTaskId;
182
-    }
36
+	/**
37
+	 * Main function for this page, when no specific actions are called.
38
+	 * @return void
39
+	 * @throws AccessDeniedException
40
+	 * @throws ApplicationLogicException
41
+	 */
42
+	protected function main()
43
+	{
44
+		$this->checkPosted();
45
+
46
+		$database = $this->getDatabase();
47
+
48
+		$request = $this->getRequest($database);
49
+		$template = $this->getTemplate($database);
50
+		$creationMode = $this->getCreationMode();
51
+		$user = User::getCurrent($database);
52
+
53
+		$secMgr = $this->getSecurityManager();
54
+		if ($secMgr->allows('RequestCreation', User::CREATION_BOT, $user) !== SecurityManager::ALLOWED
55
+			&& $creationMode === 'bot'
56
+		) {
57
+			throw new AccessDeniedException($secMgr);
58
+		}
59
+		elseif ($secMgr->allows('RequestCreation', User::CREATION_OAUTH, $user) !== SecurityManager::ALLOWED
60
+			&& $creationMode === 'oauth'
61
+		) {
62
+			throw new AccessDeniedException($secMgr);
63
+		}
64
+
65
+		if ($request->getEmailSent()) {
66
+			throw new ApplicationLogicException('This requester has already had an email sent to them. Please fall back to manual creation');
67
+		}
68
+
69
+		$request->setStatus(RequestStatus::JOBQUEUE);
70
+		$request->setReserved(null);
71
+		$request->save();
72
+
73
+		Logger::enqueuedJobQueue($database, $request);
74
+
75
+		$creationTaskId = $this->enqueueCreationTask($creationMode, $request, $template, $user, $database);
76
+
77
+		if ($user->getWelcomeTemplate() !== null && !WebRequest::postBoolean('skipAutoWelcome')) {
78
+			$this->enqueueWelcomeTask($request, $creationTaskId, $user, $database);
79
+		}
80
+
81
+		SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
82
+
83
+		$this->redirect();
84
+	}
85
+
86
+	protected function getCreationMode()
87
+	{
88
+		$creationMode = WebRequest::postString('mode');
89
+		if ($creationMode !== 'oauth' && $creationMode !== 'bot') {
90
+			throw new ApplicationLogicException('Unknown creation mode');
91
+		}
92
+
93
+		return $creationMode;
94
+	}
95
+
96
+	/**
97
+	 * @param PdoDatabase $database
98
+	 *
99
+	 * @return EmailTemplate
100
+	 * @throws ApplicationLogicException
101
+	 */
102
+	protected function getTemplate(PdoDatabase $database)
103
+	{
104
+		$templateId = WebRequest::postInt('template');
105
+		if ($templateId === null) {
106
+			throw new ApplicationLogicException('No template specified');
107
+		}
108
+
109
+		/** @var EmailTemplate $template */
110
+		$template = EmailTemplate::getById($templateId, $database);
111
+		if ($template === false || !$template->getActive()) {
112
+			throw new ApplicationLogicException('Invalid or inactive template specified');
113
+		}
114
+
115
+		if ($template->getDefaultAction() !== EmailTemplate::CREATED) {
116
+			throw new ApplicationLogicException('Specified template is not a creation template!');
117
+		}
118
+
119
+		return $template;
120
+	}
121
+
122
+	/**
123
+	 * @param PdoDatabase $database
124
+	 *
125
+	 * @return Request
126
+	 * @throws ApplicationLogicException
127
+	 */
128
+	protected function getRequest(PdoDatabase $database)
129
+	{
130
+		$request = parent::getRequest($database);
131
+
132
+		if ($request->getStatus() == RequestStatus::CLOSED) {
133
+			throw new ApplicationLogicException('Request is already closed');
134
+		}
135
+
136
+		return $request;
137
+	}
138
+
139
+	/**
140
+	 * @param               $creationMode
141
+	 * @param Request       $request
142
+	 * @param EmailTemplate $template
143
+	 * @param User          $user
144
+	 *
145
+	 * @param PdoDatabase   $database
146
+	 *
147
+	 * @return int
148
+	 * @throws ApplicationLogicException
149
+	 */
150
+	protected function enqueueCreationTask(
151
+		$creationMode,
152
+		Request $request,
153
+		EmailTemplate $template,
154
+		User $user,
155
+		PdoDatabase $database
156
+	) {
157
+		$creationTaskClass = null;
158
+
159
+		if ($creationMode == "oauth") {
160
+			$creationTaskClass = UserCreationTask::class;
161
+		}
162
+
163
+		if ($creationMode == "bot") {
164
+			$creationTaskClass = BotCreationTask::class;
165
+		}
166
+
167
+		if ($creationTaskClass === null) {
168
+			throw new ApplicationLogicException('Cannot determine creation mode');
169
+		}
170
+
171
+		$creationTask = new JobQueue();
172
+		$creationTask->setTask($creationTaskClass);
173
+		$creationTask->setRequest($request->getId());
174
+		$creationTask->setEmailTemplate($template->getId());
175
+		$creationTask->setTriggerUserId($user->getId());
176
+		$creationTask->setDatabase($database);
177
+		$creationTask->save();
178
+
179
+		$creationTaskId = $creationTask->getId();
180
+
181
+		return $creationTaskId;
182
+	}
183 183
 }
Please login to merge, or discard this patch.
includes/Pages/PageUserManagement.php 1 patch
Indentation   +552 added lines, -552 removed lines patch added patch discarded remove patch
@@ -24,556 +24,556 @@
 block discarded – undo
24 24
  */
25 25
 class PageUserManagement extends InternalPageBase
26 26
 {
27
-    /** @var string */
28
-    private $adminMailingList = '[email protected]';
29
-
30
-    /**
31
-     * Main function for this page, when no specific actions are called.
32
-     */
33
-    protected function main()
34
-    {
35
-        $this->setHtmlTitle('User Management');
36
-
37
-        $database = $this->getDatabase();
38
-        $currentUser = User::getCurrent($database);
39
-
40
-        $userSearchRequest = WebRequest::getString('usersearch');
41
-        if ($userSearchRequest !== null) {
42
-            $searchedUser = User::getByUsername($userSearchRequest, $database);
43
-            if($searchedUser !== false) {
44
-                $this->redirect('statistics/users', 'detail', ['user' => $searchedUser->getId()]);
45
-                return;
46
-            }
47
-        }
48
-
49
-        // A bit hacky, but it's better than my last solution of creating an object for each user and passing that to
50
-        // the template. I still don't have a particularly good way of handling this.
51
-        OAuthUserHelper::prepareTokenCountStatement($database);
52
-
53
-        if (WebRequest::getBoolean("showAll")) {
54
-            $this->assign("showAll", true);
55
-
56
-            $suspendedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_SUSPENDED)->fetch();
57
-            $this->assign("suspendedUsers", $suspendedUsers);
58
-
59
-            $declinedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_DECLINED)->fetch();
60
-            $this->assign("declinedUsers", $declinedUsers);
61
-
62
-            UserSearchHelper::get($database)->getRoleMap($roleMap);
63
-        }
64
-        else {
65
-            $this->assign("showAll", false);
66
-            $this->assign("suspendedUsers", array());
67
-            $this->assign("declinedUsers", array());
68
-
69
-            UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
70
-        }
71
-
72
-        $newUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch();
73
-        $normalUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch();
74
-        $adminUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch();
75
-        $checkUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch();
76
-        $toolRoots = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch();
77
-        $this->assign('newUsers', $newUsers);
78
-        $this->assign('normalUsers', $normalUsers);
79
-        $this->assign('adminUsers', $adminUsers);
80
-        $this->assign('checkUsers', $checkUsers);
81
-        $this->assign('toolRoots', $toolRoots);
82
-
83
-        $this->assign('roles', $roleMap);
84
-
85
-        $this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
86
-
87
-        $this->assign('canApprove', $this->barrierTest('approve', $currentUser));
88
-        $this->assign('canDecline', $this->barrierTest('decline', $currentUser));
89
-        $this->assign('canRename', $this->barrierTest('rename', $currentUser));
90
-        $this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
91
-        $this->assign('canSuspend', $this->barrierTest('suspend', $currentUser));
92
-        $this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
93
-
94
-        $this->setTemplate("usermanagement/main.tpl");
95
-    }
96
-
97
-    #region Access control
98
-
99
-    /**
100
-     * Action target for editing the roles assigned to a user
101
-     */
102
-    protected function editRoles()
103
-    {
104
-        $this->setHtmlTitle('User Management');
105
-        $database = $this->getDatabase();
106
-        $userId = WebRequest::getInt('user');
107
-
108
-        /** @var User $user */
109
-        $user = User::getById($userId, $database);
110
-
111
-        if ($user === false) {
112
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
113
-        }
114
-
115
-        $roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database));
116
-
117
-        // Dual-mode action
118
-        if (WebRequest::wasPosted()) {
119
-            $this->validateCSRFToken();
120
-
121
-            $reason = WebRequest::postString('reason');
122
-            if ($reason === false || trim($reason) === '') {
123
-                throw new ApplicationLogicException('No reason specified for roles change');
124
-            }
125
-
126
-            /** @var UserRole[] $delete */
127
-            $delete = array();
128
-            /** @var string[] $delete */
129
-            $add = array();
130
-
131
-            foreach ($roleData as $name => $r) {
132
-                if ($r['allowEdit'] !== 1) {
133
-                    // not allowed, to touch this, so ignore it
134
-                    continue;
135
-                }
136
-
137
-                $newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
138
-                if ($newValue !== $r['active']) {
139
-                    if ($newValue === 0) {
140
-                        $delete[] = $r['object'];
141
-                    }
142
-
143
-                    if ($newValue === 1) {
144
-                        $add[] = $name;
145
-                    }
146
-                }
147
-            }
148
-
149
-            // Check there's something to do
150
-            if ((count($add) + count($delete)) === 0) {
151
-                $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
152
-                SessionAlert::warning('No changes made to roles.');
153
-
154
-                return;
155
-            }
156
-
157
-            $removed = array();
158
-
159
-            /** @var UserRole $d */
160
-            foreach ($delete as $d) {
161
-                $removed[] = $d->getRole();
162
-                $d->delete();
163
-            }
164
-
165
-            foreach ($add as $x) {
166
-                $a = new UserRole();
167
-                $a->setUser($user->getId());
168
-                $a->setRole($x);
169
-                $a->setDatabase($database);
170
-                $a->save();
171
-            }
172
-
173
-            Logger::userRolesEdited($database, $user, $reason, $add, $removed);
174
-
175
-            // dummy save for optimistic locking. If this fails, the entire txn will roll back.
176
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
177
-            $user->save();
178
-
179
-            $this->getNotificationHelper()->userRolesEdited($user, $reason);
180
-            SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
181
-
182
-            $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
183
-
184
-            return;
185
-        }
186
-        else {
187
-            $this->assignCSRFToken();
188
-            $this->setTemplate('usermanagement/roleedit.tpl');
189
-            $this->assign('user', $user);
190
-            $this->assign('roleData', $roleData);
191
-        }
192
-    }
193
-
194
-    /**
195
-     * Action target for suspending users
196
-     *
197
-     * @throws ApplicationLogicException
198
-     */
199
-    protected function suspend()
200
-    {
201
-        $this->setHtmlTitle('User Management');
202
-
203
-        $database = $this->getDatabase();
204
-
205
-        $userId = WebRequest::getInt('user');
206
-
207
-        /** @var User $user */
208
-        $user = User::getById($userId, $database);
209
-
210
-        if ($user === false) {
211
-            throw new ApplicationLogicException('Sorry, the user you are trying to suspend could not be found.');
212
-        }
213
-
214
-        if ($user->isSuspended()) {
215
-            throw new ApplicationLogicException('Sorry, the user you are trying to suspend is already suspended.');
216
-        }
217
-
218
-        // Dual-mode action
219
-        if (WebRequest::wasPosted()) {
220
-            $this->validateCSRFToken();
221
-            $reason = WebRequest::postString('reason');
222
-
223
-            if ($reason === null || trim($reason) === "") {
224
-                throw new ApplicationLogicException('No reason provided');
225
-            }
226
-
227
-            $user->setStatus(User::STATUS_SUSPENDED);
228
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
229
-            $user->save();
230
-            Logger::suspendedUser($database, $user, $reason);
231
-
232
-            $this->getNotificationHelper()->userSuspended($user, $reason);
233
-            SessionAlert::quick('Suspended user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
234
-
235
-            // send email
236
-            $this->sendStatusChangeEmail(
237
-                'Your WP:ACC account has been suspended',
238
-                'usermanagement/emails/suspended.tpl',
239
-                $reason,
240
-                $user,
241
-                User::getCurrent($database)->getUsername()
242
-            );
243
-
244
-            $this->redirect('userManagement');
245
-
246
-            return;
247
-        }
248
-        else {
249
-            $this->assignCSRFToken();
250
-            $this->setTemplate('usermanagement/changelevel-reason.tpl');
251
-            $this->assign('user', $user);
252
-            $this->assign('status', 'Suspended');
253
-            $this->assign("showReason", true);
254
-
255
-            if (WebRequest::getString('preload')) {
256
-                $this->assign('preload', WebRequest::getString('preload'));
257
-            }
258
-        }
259
-    }
260
-
261
-    /**
262
-     * Entry point for the decline action
263
-     *
264
-     * @throws ApplicationLogicException
265
-     */
266
-    protected function decline()
267
-    {
268
-        $this->setHtmlTitle('User Management');
269
-
270
-        $database = $this->getDatabase();
271
-
272
-        $userId = WebRequest::getInt('user');
273
-        $user = User::getById($userId, $database);
274
-
275
-        if ($user === false) {
276
-            throw new ApplicationLogicException('Sorry, the user you are trying to decline could not be found.');
277
-        }
278
-
279
-        if (!$user->isNewUser()) {
280
-            throw new ApplicationLogicException('Sorry, the user you are trying to decline is not new.');
281
-        }
282
-
283
-        // Dual-mode action
284
-        if (WebRequest::wasPosted()) {
285
-            $this->validateCSRFToken();
286
-            $reason = WebRequest::postString('reason');
287
-
288
-            if ($reason === null || trim($reason) === "") {
289
-                throw new ApplicationLogicException('No reason provided');
290
-            }
291
-
292
-            $user->setStatus(User::STATUS_DECLINED);
293
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
294
-            $user->save();
295
-            Logger::declinedUser($database, $user, $reason);
296
-
297
-            $this->getNotificationHelper()->userDeclined($user, $reason);
298
-            SessionAlert::quick('Declined user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
299
-
300
-            // send email
301
-            $this->sendStatusChangeEmail(
302
-                'Your WP:ACC account has been declined',
303
-                'usermanagement/emails/declined.tpl',
304
-                $reason,
305
-                $user,
306
-                User::getCurrent($database)->getUsername()
307
-            );
308
-
309
-            $this->redirect('userManagement');
310
-
311
-            return;
312
-        }
313
-        else {
314
-            $this->assignCSRFToken();
315
-            $this->setTemplate('usermanagement/changelevel-reason.tpl');
316
-            $this->assign('user', $user);
317
-            $this->assign('status', 'Declined');
318
-            $this->assign("showReason", true);
319
-        }
320
-    }
321
-
322
-    /**
323
-     * Entry point for the approve action
324
-     *
325
-     * @throws ApplicationLogicException
326
-     */
327
-    protected function approve()
328
-    {
329
-        $this->setHtmlTitle('User Management');
330
-
331
-        $database = $this->getDatabase();
332
-
333
-        $userId = WebRequest::getInt('user');
334
-        $user = User::getById($userId, $database);
335
-
336
-        if ($user === false) {
337
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
338
-        }
339
-
340
-        if ($user->isActive()) {
341
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
342
-        }
343
-
344
-        // Dual-mode action
345
-        if (WebRequest::wasPosted()) {
346
-            $this->validateCSRFToken();
347
-            $user->setStatus(User::STATUS_ACTIVE);
348
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
349
-            $user->save();
350
-            Logger::approvedUser($database, $user);
351
-
352
-            $this->getNotificationHelper()->userApproved($user);
353
-            SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
354
-
355
-            // send email
356
-            $this->sendStatusChangeEmail(
357
-                'Your WP:ACC account has been approved',
358
-                'usermanagement/emails/approved.tpl',
359
-                null,
360
-                $user,
361
-                User::getCurrent($database)->getUsername()
362
-            );
363
-
364
-            $this->redirect("userManagement");
365
-
366
-            return;
367
-        }
368
-        else {
369
-            $this->assignCSRFToken();
370
-            $this->setTemplate("usermanagement/changelevel-reason.tpl");
371
-            $this->assign("user", $user);
372
-            $this->assign("status", "Active");
373
-            $this->assign("showReason", false);
374
-        }
375
-    }
376
-
377
-    #endregion
378
-
379
-    #region Renaming / Editing
380
-
381
-    /**
382
-     * Entry point for the rename action
383
-     *
384
-     * @throws ApplicationLogicException
385
-     */
386
-    protected function rename()
387
-    {
388
-        $this->setHtmlTitle('User Management');
389
-
390
-        $database = $this->getDatabase();
391
-
392
-        $userId = WebRequest::getInt('user');
393
-        $user = User::getById($userId, $database);
394
-
395
-        if ($user === false) {
396
-            throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
397
-        }
398
-
399
-        // Dual-mode action
400
-        if (WebRequest::wasPosted()) {
401
-            $this->validateCSRFToken();
402
-            $newUsername = WebRequest::postString('newname');
403
-
404
-            if ($newUsername === null || trim($newUsername) === "") {
405
-                throw new ApplicationLogicException('The new username cannot be empty');
406
-            }
407
-
408
-            if (User::getByUsername($newUsername, $database) != false) {
409
-                throw new ApplicationLogicException('The new username already exists');
410
-            }
411
-
412
-            $oldUsername = $user->getUsername();
413
-            $user->setUsername($newUsername);
414
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
415
-
416
-            $user->save();
417
-
418
-            $logEntryData = serialize(array(
419
-                'old' => $oldUsername,
420
-                'new' => $newUsername,
421
-            ));
422
-
423
-            Logger::renamedUser($database, $user, $logEntryData);
424
-
425
-            SessionAlert::quick("Changed User "
426
-                . htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
427
-                . " name to "
428
-                . htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
429
-
430
-            $this->getNotificationHelper()->userRenamed($user, $oldUsername);
431
-
432
-            // send an email to the user.
433
-            $this->assign('targetUsername', $user->getUsername());
434
-            $this->assign('toolAdmin', User::getCurrent($database)->getUsername());
435
-            $this->assign('oldUsername', $oldUsername);
436
-            $this->assign('mailingList', $this->adminMailingList);
437
-
438
-            $this->getEmailHelper()->sendMail(
439
-                $user->getEmail(),
440
-                'Your username on WP:ACC has been changed',
441
-                $this->fetchTemplate('usermanagement/emails/renamed.tpl'),
442
-                array('Reply-To' => $this->adminMailingList)
443
-            );
444
-
445
-            $this->redirect("userManagement");
446
-
447
-            return;
448
-        }
449
-        else {
450
-            $this->assignCSRFToken();
451
-            $this->setTemplate('usermanagement/renameuser.tpl');
452
-            $this->assign('user', $user);
453
-        }
454
-    }
455
-
456
-    /**
457
-     * Entry point for the edit action
458
-     *
459
-     * @throws ApplicationLogicException
460
-     */
461
-    protected function editUser()
462
-    {
463
-        $this->setHtmlTitle('User Management');
464
-
465
-        $database = $this->getDatabase();
466
-
467
-        $userId = WebRequest::getInt('user');
468
-        $user = User::getById($userId, $database);
469
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
470
-
471
-        if ($user === false) {
472
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
473
-        }
474
-
475
-        // Dual-mode action
476
-        if (WebRequest::wasPosted()) {
477
-            $this->validateCSRFToken();
478
-            $newEmail = WebRequest::postEmail('user_email');
479
-            $newOnWikiName = WebRequest::postString('user_onwikiname');
480
-
481
-            if ($newEmail === null) {
482
-                throw new ApplicationLogicException('Invalid email address');
483
-            }
484
-
485
-            if (!$oauth->isFullyLinked()) {
486
-                if (trim($newOnWikiName) == "") {
487
-                    throw new ApplicationLogicException('New on-wiki username cannot be blank');
488
-                }
489
-
490
-                $user->setOnWikiName($newOnWikiName);
491
-            }
492
-
493
-            $user->setEmail($newEmail);
494
-
495
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
496
-
497
-            $user->save();
498
-
499
-            Logger::userPreferencesChange($database, $user);
500
-            $this->getNotificationHelper()->userPrefChange($user);
501
-            SessionAlert::quick('Changes to user\'s preferences have been saved');
502
-
503
-            $this->redirect("userManagement");
504
-
505
-            return;
506
-        }
507
-        else {
508
-            $this->assignCSRFToken();
509
-            $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
510
-                $this->getSiteConfiguration());
511
-            $this->setTemplate('usermanagement/edituser.tpl');
512
-            $this->assign('user', $user);
513
-            $this->assign('oauth', $oauth);
514
-        }
515
-    }
516
-
517
-    #endregion
518
-
519
-    /**
520
-     * Sends a status change email to the user.
521
-     *
522
-     * @param string      $subject           The subject of the email
523
-     * @param string      $template          The smarty template to use
524
-     * @param string|null $reason            The reason for performing the status change
525
-     * @param User        $user              The user affected
526
-     * @param string      $toolAdminUsername The tool admin's username who is making the edit
527
-     */
528
-    private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
529
-    {
530
-        $this->assign('targetUsername', $user->getUsername());
531
-        $this->assign('toolAdmin', $toolAdminUsername);
532
-        $this->assign('actionReason', $reason);
533
-        $this->assign('mailingList', $this->adminMailingList);
534
-
535
-        $this->getEmailHelper()->sendMail(
536
-            $user->getEmail(),
537
-            $subject,
538
-            $this->fetchTemplate($template),
539
-            array('Reply-To' => $this->adminMailingList)
540
-        );
541
-    }
542
-
543
-    /**
544
-     * @param UserRole[] $activeRoles
545
-     *
546
-     * @return array
547
-     */
548
-    private function getRoleData($activeRoles)
549
-    {
550
-        $availableRoles = $this->getSecurityManager()->getRoleConfiguration()->getAvailableRoles();
551
-
552
-        $currentUser = User::getCurrent($this->getDatabase());
553
-        $this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
554
-
555
-        $initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
556
-
557
-        $roleData = array();
558
-        foreach ($availableRoles as $role => $data) {
559
-            $intersection = array_intersect($data['editableBy'], $userRoles);
560
-
561
-            $roleData[$role] = $initialValue;
562
-            $roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
563
-            $roleData[$role]['description'] = $data['description'];
564
-        }
565
-
566
-        foreach ($activeRoles as $role) {
567
-            if (!isset($roleData[$role->getRole()])) {
568
-                // This value is no longer available in the configuration, allow changing (aka removing) it.
569
-                $roleData[$role->getRole()] = $initialValue;
570
-                $roleData[$role->getRole()]['allowEdit'] = 1;
571
-            }
572
-
573
-            $roleData[$role->getRole()]['object'] = $role;
574
-            $roleData[$role->getRole()]['active'] = 1;
575
-        }
576
-
577
-        return $roleData;
578
-    }
27
+	/** @var string */
28
+	private $adminMailingList = '[email protected]';
29
+
30
+	/**
31
+	 * Main function for this page, when no specific actions are called.
32
+	 */
33
+	protected function main()
34
+	{
35
+		$this->setHtmlTitle('User Management');
36
+
37
+		$database = $this->getDatabase();
38
+		$currentUser = User::getCurrent($database);
39
+
40
+		$userSearchRequest = WebRequest::getString('usersearch');
41
+		if ($userSearchRequest !== null) {
42
+			$searchedUser = User::getByUsername($userSearchRequest, $database);
43
+			if($searchedUser !== false) {
44
+				$this->redirect('statistics/users', 'detail', ['user' => $searchedUser->getId()]);
45
+				return;
46
+			}
47
+		}
48
+
49
+		// A bit hacky, but it's better than my last solution of creating an object for each user and passing that to
50
+		// the template. I still don't have a particularly good way of handling this.
51
+		OAuthUserHelper::prepareTokenCountStatement($database);
52
+
53
+		if (WebRequest::getBoolean("showAll")) {
54
+			$this->assign("showAll", true);
55
+
56
+			$suspendedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_SUSPENDED)->fetch();
57
+			$this->assign("suspendedUsers", $suspendedUsers);
58
+
59
+			$declinedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_DECLINED)->fetch();
60
+			$this->assign("declinedUsers", $declinedUsers);
61
+
62
+			UserSearchHelper::get($database)->getRoleMap($roleMap);
63
+		}
64
+		else {
65
+			$this->assign("showAll", false);
66
+			$this->assign("suspendedUsers", array());
67
+			$this->assign("declinedUsers", array());
68
+
69
+			UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
70
+		}
71
+
72
+		$newUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch();
73
+		$normalUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch();
74
+		$adminUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch();
75
+		$checkUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch();
76
+		$toolRoots = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch();
77
+		$this->assign('newUsers', $newUsers);
78
+		$this->assign('normalUsers', $normalUsers);
79
+		$this->assign('adminUsers', $adminUsers);
80
+		$this->assign('checkUsers', $checkUsers);
81
+		$this->assign('toolRoots', $toolRoots);
82
+
83
+		$this->assign('roles', $roleMap);
84
+
85
+		$this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
86
+
87
+		$this->assign('canApprove', $this->barrierTest('approve', $currentUser));
88
+		$this->assign('canDecline', $this->barrierTest('decline', $currentUser));
89
+		$this->assign('canRename', $this->barrierTest('rename', $currentUser));
90
+		$this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
91
+		$this->assign('canSuspend', $this->barrierTest('suspend', $currentUser));
92
+		$this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
93
+
94
+		$this->setTemplate("usermanagement/main.tpl");
95
+	}
96
+
97
+	#region Access control
98
+
99
+	/**
100
+	 * Action target for editing the roles assigned to a user
101
+	 */
102
+	protected function editRoles()
103
+	{
104
+		$this->setHtmlTitle('User Management');
105
+		$database = $this->getDatabase();
106
+		$userId = WebRequest::getInt('user');
107
+
108
+		/** @var User $user */
109
+		$user = User::getById($userId, $database);
110
+
111
+		if ($user === false) {
112
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
113
+		}
114
+
115
+		$roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database));
116
+
117
+		// Dual-mode action
118
+		if (WebRequest::wasPosted()) {
119
+			$this->validateCSRFToken();
120
+
121
+			$reason = WebRequest::postString('reason');
122
+			if ($reason === false || trim($reason) === '') {
123
+				throw new ApplicationLogicException('No reason specified for roles change');
124
+			}
125
+
126
+			/** @var UserRole[] $delete */
127
+			$delete = array();
128
+			/** @var string[] $delete */
129
+			$add = array();
130
+
131
+			foreach ($roleData as $name => $r) {
132
+				if ($r['allowEdit'] !== 1) {
133
+					// not allowed, to touch this, so ignore it
134
+					continue;
135
+				}
136
+
137
+				$newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
138
+				if ($newValue !== $r['active']) {
139
+					if ($newValue === 0) {
140
+						$delete[] = $r['object'];
141
+					}
142
+
143
+					if ($newValue === 1) {
144
+						$add[] = $name;
145
+					}
146
+				}
147
+			}
148
+
149
+			// Check there's something to do
150
+			if ((count($add) + count($delete)) === 0) {
151
+				$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
152
+				SessionAlert::warning('No changes made to roles.');
153
+
154
+				return;
155
+			}
156
+
157
+			$removed = array();
158
+
159
+			/** @var UserRole $d */
160
+			foreach ($delete as $d) {
161
+				$removed[] = $d->getRole();
162
+				$d->delete();
163
+			}
164
+
165
+			foreach ($add as $x) {
166
+				$a = new UserRole();
167
+				$a->setUser($user->getId());
168
+				$a->setRole($x);
169
+				$a->setDatabase($database);
170
+				$a->save();
171
+			}
172
+
173
+			Logger::userRolesEdited($database, $user, $reason, $add, $removed);
174
+
175
+			// dummy save for optimistic locking. If this fails, the entire txn will roll back.
176
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
177
+			$user->save();
178
+
179
+			$this->getNotificationHelper()->userRolesEdited($user, $reason);
180
+			SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
181
+
182
+			$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
183
+
184
+			return;
185
+		}
186
+		else {
187
+			$this->assignCSRFToken();
188
+			$this->setTemplate('usermanagement/roleedit.tpl');
189
+			$this->assign('user', $user);
190
+			$this->assign('roleData', $roleData);
191
+		}
192
+	}
193
+
194
+	/**
195
+	 * Action target for suspending users
196
+	 *
197
+	 * @throws ApplicationLogicException
198
+	 */
199
+	protected function suspend()
200
+	{
201
+		$this->setHtmlTitle('User Management');
202
+
203
+		$database = $this->getDatabase();
204
+
205
+		$userId = WebRequest::getInt('user');
206
+
207
+		/** @var User $user */
208
+		$user = User::getById($userId, $database);
209
+
210
+		if ($user === false) {
211
+			throw new ApplicationLogicException('Sorry, the user you are trying to suspend could not be found.');
212
+		}
213
+
214
+		if ($user->isSuspended()) {
215
+			throw new ApplicationLogicException('Sorry, the user you are trying to suspend is already suspended.');
216
+		}
217
+
218
+		// Dual-mode action
219
+		if (WebRequest::wasPosted()) {
220
+			$this->validateCSRFToken();
221
+			$reason = WebRequest::postString('reason');
222
+
223
+			if ($reason === null || trim($reason) === "") {
224
+				throw new ApplicationLogicException('No reason provided');
225
+			}
226
+
227
+			$user->setStatus(User::STATUS_SUSPENDED);
228
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
229
+			$user->save();
230
+			Logger::suspendedUser($database, $user, $reason);
231
+
232
+			$this->getNotificationHelper()->userSuspended($user, $reason);
233
+			SessionAlert::quick('Suspended user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
234
+
235
+			// send email
236
+			$this->sendStatusChangeEmail(
237
+				'Your WP:ACC account has been suspended',
238
+				'usermanagement/emails/suspended.tpl',
239
+				$reason,
240
+				$user,
241
+				User::getCurrent($database)->getUsername()
242
+			);
243
+
244
+			$this->redirect('userManagement');
245
+
246
+			return;
247
+		}
248
+		else {
249
+			$this->assignCSRFToken();
250
+			$this->setTemplate('usermanagement/changelevel-reason.tpl');
251
+			$this->assign('user', $user);
252
+			$this->assign('status', 'Suspended');
253
+			$this->assign("showReason", true);
254
+
255
+			if (WebRequest::getString('preload')) {
256
+				$this->assign('preload', WebRequest::getString('preload'));
257
+			}
258
+		}
259
+	}
260
+
261
+	/**
262
+	 * Entry point for the decline action
263
+	 *
264
+	 * @throws ApplicationLogicException
265
+	 */
266
+	protected function decline()
267
+	{
268
+		$this->setHtmlTitle('User Management');
269
+
270
+		$database = $this->getDatabase();
271
+
272
+		$userId = WebRequest::getInt('user');
273
+		$user = User::getById($userId, $database);
274
+
275
+		if ($user === false) {
276
+			throw new ApplicationLogicException('Sorry, the user you are trying to decline could not be found.');
277
+		}
278
+
279
+		if (!$user->isNewUser()) {
280
+			throw new ApplicationLogicException('Sorry, the user you are trying to decline is not new.');
281
+		}
282
+
283
+		// Dual-mode action
284
+		if (WebRequest::wasPosted()) {
285
+			$this->validateCSRFToken();
286
+			$reason = WebRequest::postString('reason');
287
+
288
+			if ($reason === null || trim($reason) === "") {
289
+				throw new ApplicationLogicException('No reason provided');
290
+			}
291
+
292
+			$user->setStatus(User::STATUS_DECLINED);
293
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
294
+			$user->save();
295
+			Logger::declinedUser($database, $user, $reason);
296
+
297
+			$this->getNotificationHelper()->userDeclined($user, $reason);
298
+			SessionAlert::quick('Declined user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
299
+
300
+			// send email
301
+			$this->sendStatusChangeEmail(
302
+				'Your WP:ACC account has been declined',
303
+				'usermanagement/emails/declined.tpl',
304
+				$reason,
305
+				$user,
306
+				User::getCurrent($database)->getUsername()
307
+			);
308
+
309
+			$this->redirect('userManagement');
310
+
311
+			return;
312
+		}
313
+		else {
314
+			$this->assignCSRFToken();
315
+			$this->setTemplate('usermanagement/changelevel-reason.tpl');
316
+			$this->assign('user', $user);
317
+			$this->assign('status', 'Declined');
318
+			$this->assign("showReason", true);
319
+		}
320
+	}
321
+
322
+	/**
323
+	 * Entry point for the approve action
324
+	 *
325
+	 * @throws ApplicationLogicException
326
+	 */
327
+	protected function approve()
328
+	{
329
+		$this->setHtmlTitle('User Management');
330
+
331
+		$database = $this->getDatabase();
332
+
333
+		$userId = WebRequest::getInt('user');
334
+		$user = User::getById($userId, $database);
335
+
336
+		if ($user === false) {
337
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
338
+		}
339
+
340
+		if ($user->isActive()) {
341
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
342
+		}
343
+
344
+		// Dual-mode action
345
+		if (WebRequest::wasPosted()) {
346
+			$this->validateCSRFToken();
347
+			$user->setStatus(User::STATUS_ACTIVE);
348
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
349
+			$user->save();
350
+			Logger::approvedUser($database, $user);
351
+
352
+			$this->getNotificationHelper()->userApproved($user);
353
+			SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
354
+
355
+			// send email
356
+			$this->sendStatusChangeEmail(
357
+				'Your WP:ACC account has been approved',
358
+				'usermanagement/emails/approved.tpl',
359
+				null,
360
+				$user,
361
+				User::getCurrent($database)->getUsername()
362
+			);
363
+
364
+			$this->redirect("userManagement");
365
+
366
+			return;
367
+		}
368
+		else {
369
+			$this->assignCSRFToken();
370
+			$this->setTemplate("usermanagement/changelevel-reason.tpl");
371
+			$this->assign("user", $user);
372
+			$this->assign("status", "Active");
373
+			$this->assign("showReason", false);
374
+		}
375
+	}
376
+
377
+	#endregion
378
+
379
+	#region Renaming / Editing
380
+
381
+	/**
382
+	 * Entry point for the rename action
383
+	 *
384
+	 * @throws ApplicationLogicException
385
+	 */
386
+	protected function rename()
387
+	{
388
+		$this->setHtmlTitle('User Management');
389
+
390
+		$database = $this->getDatabase();
391
+
392
+		$userId = WebRequest::getInt('user');
393
+		$user = User::getById($userId, $database);
394
+
395
+		if ($user === false) {
396
+			throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
397
+		}
398
+
399
+		// Dual-mode action
400
+		if (WebRequest::wasPosted()) {
401
+			$this->validateCSRFToken();
402
+			$newUsername = WebRequest::postString('newname');
403
+
404
+			if ($newUsername === null || trim($newUsername) === "") {
405
+				throw new ApplicationLogicException('The new username cannot be empty');
406
+			}
407
+
408
+			if (User::getByUsername($newUsername, $database) != false) {
409
+				throw new ApplicationLogicException('The new username already exists');
410
+			}
411
+
412
+			$oldUsername = $user->getUsername();
413
+			$user->setUsername($newUsername);
414
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
415
+
416
+			$user->save();
417
+
418
+			$logEntryData = serialize(array(
419
+				'old' => $oldUsername,
420
+				'new' => $newUsername,
421
+			));
422
+
423
+			Logger::renamedUser($database, $user, $logEntryData);
424
+
425
+			SessionAlert::quick("Changed User "
426
+				. htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
427
+				. " name to "
428
+				. htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
429
+
430
+			$this->getNotificationHelper()->userRenamed($user, $oldUsername);
431
+
432
+			// send an email to the user.
433
+			$this->assign('targetUsername', $user->getUsername());
434
+			$this->assign('toolAdmin', User::getCurrent($database)->getUsername());
435
+			$this->assign('oldUsername', $oldUsername);
436
+			$this->assign('mailingList', $this->adminMailingList);
437
+
438
+			$this->getEmailHelper()->sendMail(
439
+				$user->getEmail(),
440
+				'Your username on WP:ACC has been changed',
441
+				$this->fetchTemplate('usermanagement/emails/renamed.tpl'),
442
+				array('Reply-To' => $this->adminMailingList)
443
+			);
444
+
445
+			$this->redirect("userManagement");
446
+
447
+			return;
448
+		}
449
+		else {
450
+			$this->assignCSRFToken();
451
+			$this->setTemplate('usermanagement/renameuser.tpl');
452
+			$this->assign('user', $user);
453
+		}
454
+	}
455
+
456
+	/**
457
+	 * Entry point for the edit action
458
+	 *
459
+	 * @throws ApplicationLogicException
460
+	 */
461
+	protected function editUser()
462
+	{
463
+		$this->setHtmlTitle('User Management');
464
+
465
+		$database = $this->getDatabase();
466
+
467
+		$userId = WebRequest::getInt('user');
468
+		$user = User::getById($userId, $database);
469
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
470
+
471
+		if ($user === false) {
472
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
473
+		}
474
+
475
+		// Dual-mode action
476
+		if (WebRequest::wasPosted()) {
477
+			$this->validateCSRFToken();
478
+			$newEmail = WebRequest::postEmail('user_email');
479
+			$newOnWikiName = WebRequest::postString('user_onwikiname');
480
+
481
+			if ($newEmail === null) {
482
+				throw new ApplicationLogicException('Invalid email address');
483
+			}
484
+
485
+			if (!$oauth->isFullyLinked()) {
486
+				if (trim($newOnWikiName) == "") {
487
+					throw new ApplicationLogicException('New on-wiki username cannot be blank');
488
+				}
489
+
490
+				$user->setOnWikiName($newOnWikiName);
491
+			}
492
+
493
+			$user->setEmail($newEmail);
494
+
495
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
496
+
497
+			$user->save();
498
+
499
+			Logger::userPreferencesChange($database, $user);
500
+			$this->getNotificationHelper()->userPrefChange($user);
501
+			SessionAlert::quick('Changes to user\'s preferences have been saved');
502
+
503
+			$this->redirect("userManagement");
504
+
505
+			return;
506
+		}
507
+		else {
508
+			$this->assignCSRFToken();
509
+			$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
510
+				$this->getSiteConfiguration());
511
+			$this->setTemplate('usermanagement/edituser.tpl');
512
+			$this->assign('user', $user);
513
+			$this->assign('oauth', $oauth);
514
+		}
515
+	}
516
+
517
+	#endregion
518
+
519
+	/**
520
+	 * Sends a status change email to the user.
521
+	 *
522
+	 * @param string      $subject           The subject of the email
523
+	 * @param string      $template          The smarty template to use
524
+	 * @param string|null $reason            The reason for performing the status change
525
+	 * @param User        $user              The user affected
526
+	 * @param string      $toolAdminUsername The tool admin's username who is making the edit
527
+	 */
528
+	private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
529
+	{
530
+		$this->assign('targetUsername', $user->getUsername());
531
+		$this->assign('toolAdmin', $toolAdminUsername);
532
+		$this->assign('actionReason', $reason);
533
+		$this->assign('mailingList', $this->adminMailingList);
534
+
535
+		$this->getEmailHelper()->sendMail(
536
+			$user->getEmail(),
537
+			$subject,
538
+			$this->fetchTemplate($template),
539
+			array('Reply-To' => $this->adminMailingList)
540
+		);
541
+	}
542
+
543
+	/**
544
+	 * @param UserRole[] $activeRoles
545
+	 *
546
+	 * @return array
547
+	 */
548
+	private function getRoleData($activeRoles)
549
+	{
550
+		$availableRoles = $this->getSecurityManager()->getRoleConfiguration()->getAvailableRoles();
551
+
552
+		$currentUser = User::getCurrent($this->getDatabase());
553
+		$this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
554
+
555
+		$initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
556
+
557
+		$roleData = array();
558
+		foreach ($availableRoles as $role => $data) {
559
+			$intersection = array_intersect($data['editableBy'], $userRoles);
560
+
561
+			$roleData[$role] = $initialValue;
562
+			$roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
563
+			$roleData[$role]['description'] = $data['description'];
564
+		}
565
+
566
+		foreach ($activeRoles as $role) {
567
+			if (!isset($roleData[$role->getRole()])) {
568
+				// This value is no longer available in the configuration, allow changing (aka removing) it.
569
+				$roleData[$role->getRole()] = $initialValue;
570
+				$roleData[$role->getRole()]['allowEdit'] = 1;
571
+			}
572
+
573
+			$roleData[$role->getRole()]['object'] = $role;
574
+			$roleData[$role->getRole()]['active'] = 1;
575
+		}
576
+
577
+		return $roleData;
578
+	}
579 579
 }
Please login to merge, or discard this patch.
includes/Pages/UserAuth/PageLogout.php 2 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -14,22 +14,22 @@
 block discarded – undo
14 14
 
15 15
 class PageLogout extends InternalPageBase
16 16
 {
17
-    /**
18
-     * Main function for this page, when no specific actions are called.
19
-     */
20
-    protected function main()
21
-    {
22
-        if(WebRequest::wasPosted()) {
23
-            Session::destroy();
24
-            $this->redirect("login");
25
-            return;
26
-        }
17
+	/**
18
+	 * Main function for this page, when no specific actions are called.
19
+	 */
20
+	protected function main()
21
+	{
22
+		if(WebRequest::wasPosted()) {
23
+			Session::destroy();
24
+			$this->redirect("login");
25
+			return;
26
+		}
27 27
 
28
-        $this->redirect();
29
-    }
28
+		$this->redirect();
29
+	}
30 30
 
31
-    protected function isProtectedPage()
32
-    {
33
-        return false;
34
-    }
31
+	protected function isProtectedPage()
32
+	{
33
+		return false;
34
+	}
35 35
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@
 block discarded – undo
19 19
      */
20 20
     protected function main()
21 21
     {
22
-        if(WebRequest::wasPosted()) {
22
+        if (WebRequest::wasPosted()) {
23 23
             Session::destroy();
24 24
             $this->redirect("login");
25 25
             return;
Please login to merge, or discard this patch.
includes/WebStart.php 1 patch
Indentation   +221 added lines, -221 removed lines patch added patch discarded remove patch
@@ -32,225 +32,225 @@
 block discarded – undo
32 32
  */
33 33
 class WebStart extends ApplicationBase
34 34
 {
35
-    /**
36
-     * @var IRequestRouter $requestRouter The request router to use. Note that different entry points have different
37
-     *                                    routers and hence different URL mappings
38
-     */
39
-    private $requestRouter;
40
-    /**
41
-     * @var bool $isPublic Determines whether to use public interface objects or internal interface objects
42
-     */
43
-    private $isPublic = false;
44
-
45
-    /**
46
-     * WebStart constructor.
47
-     *
48
-     * @param SiteConfiguration $configuration The site configuration
49
-     * @param IRequestRouter    $router        The request router to use
50
-     */
51
-    public function __construct(SiteConfiguration $configuration, IRequestRouter $router)
52
-    {
53
-        parent::__construct($configuration);
54
-
55
-        $this->requestRouter = $router;
56
-    }
57
-
58
-    /**
59
-     * @param ITask             $page
60
-     * @param SiteConfiguration $siteConfiguration
61
-     * @param PdoDatabase       $database
62
-     * @param PdoDatabase       $notificationsDatabase
63
-     *
64
-     * @return void
65
-     */
66
-    protected function setupHelpers(
67
-        ITask $page,
68
-        SiteConfiguration $siteConfiguration,
69
-        PdoDatabase $database,
70
-        PdoDatabase $notificationsDatabase = null
71
-    ) {
72
-        parent::setupHelpers($page, $siteConfiguration, $database, $notificationsDatabase);
73
-
74
-        if ($page instanceof PageBase) {
75
-            $page->setTokenManager(new TokenManager());
76
-            $page->setCspManager(new ContentSecurityPolicyManager($siteConfiguration));
77
-
78
-            if ($page instanceof InternalPageBase) {
79
-                $page->setTypeAheadHelper(new TypeAheadHelper());
80
-
81
-                $identificationVerifier = new IdentificationVerifier($page->getHttpHelper(), $siteConfiguration,
82
-                    $database);
83
-                $page->setIdentificationVerifier($identificationVerifier);
84
-
85
-                $page->setSecurityManager(new SecurityManager($identificationVerifier, new RoleConfiguration()));
86
-
87
-                if ($siteConfiguration->getTitleBlacklistEnabled()) {
88
-                    $page->setBlacklistHelper(new FakeBlacklistHelper());
89
-                }
90
-                else {
91
-                    $page->setBlacklistHelper(new BlacklistHelper($page->getHttpHelper(),
92
-                        $siteConfiguration->getMediawikiWebServiceEndpoint()));
93
-                }
94
-            }
95
-        }
96
-    }
97
-
98
-    /**
99
-     * Application entry point.
100
-     *
101
-     * Sets up the environment and runs the application, performing any global cleanup operations when done.
102
-     */
103
-    public function run()
104
-    {
105
-        try {
106
-            if ($this->setupEnvironment()) {
107
-                $this->main();
108
-            }
109
-        }
110
-        catch (EnvironmentException $ex) {
111
-            ob_end_clean();
112
-            print Offline::getOfflineMessage($this->isPublic(), $ex->getMessage());
113
-        }
114
-        catch (ReadableException $ex) {
115
-            ob_end_clean();
116
-            print $ex->getReadableError();
117
-        }
118
-        finally {
119
-            $this->cleanupEnvironment();
120
-        }
121
-    }
122
-
123
-    /**
124
-     * Environment setup
125
-     *
126
-     * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
127
-     * and shut down prematurely.
128
-     *
129
-     * @return bool
130
-     * @throws EnvironmentException
131
-     */
132
-    protected function setupEnvironment()
133
-    {
134
-        // initialise global exception handler
135
-        set_exception_handler(array(ExceptionHandler::class, 'exceptionHandler'));
136
-        set_error_handler(array(ExceptionHandler::class, 'errorHandler'), E_RECOVERABLE_ERROR);
137
-
138
-        // start output buffering if necessary
139
-        if (ob_get_level() === 0) {
140
-            ob_start();
141
-        }
142
-
143
-        // initialise super-global providers
144
-        WebRequest::setGlobalStateProvider(new GlobalStateProvider());
145
-
146
-        if (Offline::isOffline()) {
147
-            print Offline::getOfflineMessage($this->isPublic());
148
-            ob_end_flush();
149
-
150
-            return false;
151
-        }
152
-
153
-        // Call parent setup
154
-        if (!parent::setupEnvironment()) {
155
-            return false;
156
-        }
157
-
158
-        // Start up sessions
159
-        Session::start();
160
-
161
-        // Check the user is allowed to be logged in still. This must be before we call any user-loading functions and
162
-        // get the current user cached.
163
-        // I'm not sure if this function call being here is particularly a good thing, but it's part of starting up a
164
-        // session I suppose.
165
-        $this->checkForceLogout();
166
-
167
-        // environment initialised!
168
-        return true;
169
-    }
170
-
171
-    /**
172
-     * Main application logic
173
-     */
174
-    protected function main()
175
-    {
176
-        // Get the right route for the request
177
-        $page = $this->requestRouter->route();
178
-
179
-        $siteConfiguration = $this->getConfiguration();
180
-        $database = PdoDatabase::getDatabaseConnection('acc');
181
-
182
-        if ($siteConfiguration->getIrcNotificationsEnabled()) {
183
-            $notificationsDatabase = PdoDatabase::getDatabaseConnection('notifications');
184
-        }
185
-        else {
186
-            // @todo federated table here?
187
-            $notificationsDatabase = $database;
188
-        }
189
-
190
-        $this->setupHelpers($page, $siteConfiguration, $database, $notificationsDatabase);
191
-
192
-        /* @todo Remove this global statement! It's here for User.php, which does far more than it should. */
193
-        global $oauthProtocolHelper;
194
-        $oauthProtocolHelper = $page->getOAuthProtocolHelper();
195
-
196
-        /* @todo Remove this global statement! It's here for Request.php, which does far more than it should. */
197
-        global $globalXffTrustProvider;
198
-        $globalXffTrustProvider = $page->getXffTrustProvider();
199
-
200
-        // run the route code for the request.
201
-        $page->execute();
202
-    }
203
-
204
-    /**
205
-     * Any cleanup tasks should go here
206
-     *
207
-     * Note that we need to be very careful here, as exceptions may have been thrown and handled.
208
-     * This should *only* be for cleaning up, no logic should go here.
209
-     */
210
-    protected function cleanupEnvironment()
211
-    {
212
-        // Clean up anything we splurged after sending the page.
213
-        if (ob_get_level() > 0) {
214
-            for ($i = ob_get_level(); $i > 0; $i--) {
215
-                ob_end_clean();
216
-            }
217
-        }
218
-    }
219
-
220
-    private function checkForceLogout()
221
-    {
222
-        $database = PdoDatabase::getDatabaseConnection('acc');
223
-
224
-        $sessionUserId = WebRequest::getSessionUserId();
225
-        iF ($sessionUserId === null) {
226
-            return;
227
-        }
228
-
229
-        // Note, User::getCurrent() caches it's result, which we *really* don't want to trigger.
230
-        $currentUser = User::getById($sessionUserId, $database);
231
-
232
-        if ($currentUser === false) {
233
-            // Umm... this user has a session cookie with a userId set, but no user exists...
234
-            Session::restart();
235
-
236
-            $currentUser = User::getCurrent($database);
237
-        }
238
-
239
-        if ($currentUser->getForceLogout()) {
240
-            Session::restart();
241
-
242
-            $currentUser->setForceLogout(false);
243
-            $currentUser->save();
244
-        }
245
-    }
246
-
247
-    public function isPublic()
248
-    {
249
-        return $this->isPublic;
250
-    }
251
-
252
-    public function setPublic($isPublic)
253
-    {
254
-        $this->isPublic = $isPublic;
255
-    }
35
+	/**
36
+	 * @var IRequestRouter $requestRouter The request router to use. Note that different entry points have different
37
+	 *                                    routers and hence different URL mappings
38
+	 */
39
+	private $requestRouter;
40
+	/**
41
+	 * @var bool $isPublic Determines whether to use public interface objects or internal interface objects
42
+	 */
43
+	private $isPublic = false;
44
+
45
+	/**
46
+	 * WebStart constructor.
47
+	 *
48
+	 * @param SiteConfiguration $configuration The site configuration
49
+	 * @param IRequestRouter    $router        The request router to use
50
+	 */
51
+	public function __construct(SiteConfiguration $configuration, IRequestRouter $router)
52
+	{
53
+		parent::__construct($configuration);
54
+
55
+		$this->requestRouter = $router;
56
+	}
57
+
58
+	/**
59
+	 * @param ITask             $page
60
+	 * @param SiteConfiguration $siteConfiguration
61
+	 * @param PdoDatabase       $database
62
+	 * @param PdoDatabase       $notificationsDatabase
63
+	 *
64
+	 * @return void
65
+	 */
66
+	protected function setupHelpers(
67
+		ITask $page,
68
+		SiteConfiguration $siteConfiguration,
69
+		PdoDatabase $database,
70
+		PdoDatabase $notificationsDatabase = null
71
+	) {
72
+		parent::setupHelpers($page, $siteConfiguration, $database, $notificationsDatabase);
73
+
74
+		if ($page instanceof PageBase) {
75
+			$page->setTokenManager(new TokenManager());
76
+			$page->setCspManager(new ContentSecurityPolicyManager($siteConfiguration));
77
+
78
+			if ($page instanceof InternalPageBase) {
79
+				$page->setTypeAheadHelper(new TypeAheadHelper());
80
+
81
+				$identificationVerifier = new IdentificationVerifier($page->getHttpHelper(), $siteConfiguration,
82
+					$database);
83
+				$page->setIdentificationVerifier($identificationVerifier);
84
+
85
+				$page->setSecurityManager(new SecurityManager($identificationVerifier, new RoleConfiguration()));
86
+
87
+				if ($siteConfiguration->getTitleBlacklistEnabled()) {
88
+					$page->setBlacklistHelper(new FakeBlacklistHelper());
89
+				}
90
+				else {
91
+					$page->setBlacklistHelper(new BlacklistHelper($page->getHttpHelper(),
92
+						$siteConfiguration->getMediawikiWebServiceEndpoint()));
93
+				}
94
+			}
95
+		}
96
+	}
97
+
98
+	/**
99
+	 * Application entry point.
100
+	 *
101
+	 * Sets up the environment and runs the application, performing any global cleanup operations when done.
102
+	 */
103
+	public function run()
104
+	{
105
+		try {
106
+			if ($this->setupEnvironment()) {
107
+				$this->main();
108
+			}
109
+		}
110
+		catch (EnvironmentException $ex) {
111
+			ob_end_clean();
112
+			print Offline::getOfflineMessage($this->isPublic(), $ex->getMessage());
113
+		}
114
+		catch (ReadableException $ex) {
115
+			ob_end_clean();
116
+			print $ex->getReadableError();
117
+		}
118
+		finally {
119
+			$this->cleanupEnvironment();
120
+		}
121
+	}
122
+
123
+	/**
124
+	 * Environment setup
125
+	 *
126
+	 * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
127
+	 * and shut down prematurely.
128
+	 *
129
+	 * @return bool
130
+	 * @throws EnvironmentException
131
+	 */
132
+	protected function setupEnvironment()
133
+	{
134
+		// initialise global exception handler
135
+		set_exception_handler(array(ExceptionHandler::class, 'exceptionHandler'));
136
+		set_error_handler(array(ExceptionHandler::class, 'errorHandler'), E_RECOVERABLE_ERROR);
137
+
138
+		// start output buffering if necessary
139
+		if (ob_get_level() === 0) {
140
+			ob_start();
141
+		}
142
+
143
+		// initialise super-global providers
144
+		WebRequest::setGlobalStateProvider(new GlobalStateProvider());
145
+
146
+		if (Offline::isOffline()) {
147
+			print Offline::getOfflineMessage($this->isPublic());
148
+			ob_end_flush();
149
+
150
+			return false;
151
+		}
152
+
153
+		// Call parent setup
154
+		if (!parent::setupEnvironment()) {
155
+			return false;
156
+		}
157
+
158
+		// Start up sessions
159
+		Session::start();
160
+
161
+		// Check the user is allowed to be logged in still. This must be before we call any user-loading functions and
162
+		// get the current user cached.
163
+		// I'm not sure if this function call being here is particularly a good thing, but it's part of starting up a
164
+		// session I suppose.
165
+		$this->checkForceLogout();
166
+
167
+		// environment initialised!
168
+		return true;
169
+	}
170
+
171
+	/**
172
+	 * Main application logic
173
+	 */
174
+	protected function main()
175
+	{
176
+		// Get the right route for the request
177
+		$page = $this->requestRouter->route();
178
+
179
+		$siteConfiguration = $this->getConfiguration();
180
+		$database = PdoDatabase::getDatabaseConnection('acc');
181
+
182
+		if ($siteConfiguration->getIrcNotificationsEnabled()) {
183
+			$notificationsDatabase = PdoDatabase::getDatabaseConnection('notifications');
184
+		}
185
+		else {
186
+			// @todo federated table here?
187
+			$notificationsDatabase = $database;
188
+		}
189
+
190
+		$this->setupHelpers($page, $siteConfiguration, $database, $notificationsDatabase);
191
+
192
+		/* @todo Remove this global statement! It's here for User.php, which does far more than it should. */
193
+		global $oauthProtocolHelper;
194
+		$oauthProtocolHelper = $page->getOAuthProtocolHelper();
195
+
196
+		/* @todo Remove this global statement! It's here for Request.php, which does far more than it should. */
197
+		global $globalXffTrustProvider;
198
+		$globalXffTrustProvider = $page->getXffTrustProvider();
199
+
200
+		// run the route code for the request.
201
+		$page->execute();
202
+	}
203
+
204
+	/**
205
+	 * Any cleanup tasks should go here
206
+	 *
207
+	 * Note that we need to be very careful here, as exceptions may have been thrown and handled.
208
+	 * This should *only* be for cleaning up, no logic should go here.
209
+	 */
210
+	protected function cleanupEnvironment()
211
+	{
212
+		// Clean up anything we splurged after sending the page.
213
+		if (ob_get_level() > 0) {
214
+			for ($i = ob_get_level(); $i > 0; $i--) {
215
+				ob_end_clean();
216
+			}
217
+		}
218
+	}
219
+
220
+	private function checkForceLogout()
221
+	{
222
+		$database = PdoDatabase::getDatabaseConnection('acc');
223
+
224
+		$sessionUserId = WebRequest::getSessionUserId();
225
+		iF ($sessionUserId === null) {
226
+			return;
227
+		}
228
+
229
+		// Note, User::getCurrent() caches it's result, which we *really* don't want to trigger.
230
+		$currentUser = User::getById($sessionUserId, $database);
231
+
232
+		if ($currentUser === false) {
233
+			// Umm... this user has a session cookie with a userId set, but no user exists...
234
+			Session::restart();
235
+
236
+			$currentUser = User::getCurrent($database);
237
+		}
238
+
239
+		if ($currentUser->getForceLogout()) {
240
+			Session::restart();
241
+
242
+			$currentUser->setForceLogout(false);
243
+			$currentUser->save();
244
+		}
245
+	}
246
+
247
+	public function isPublic()
248
+	{
249
+		return $this->isPublic;
250
+	}
251
+
252
+	public function setPublic($isPublic)
253
+	{
254
+		$this->isPublic = $isPublic;
255
+	}
256 256
 }
Please login to merge, or discard this patch.
includes/Helpers/RequestEmailHelper.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -14,50 +14,50 @@
 block discarded – undo
14 14
 
15 15
 class RequestEmailHelper
16 16
 {
17
-    /**
18
-     * @var IEmailHelper
19
-     */
20
-    private $emailHelper;
21
-
22
-    /**
23
-     * RequestEmailHelper constructor.
24
-     *
25
-     * @param IEmailHelper $emailHelper
26
-     */
27
-    public function __construct(IEmailHelper $emailHelper)
28
-    {
29
-        $this->emailHelper = $emailHelper;
30
-    }
31
-
32
-    /**
33
-     * @param Request $request
34
-     * @param string  $mailText
35
-     * @param User    $currentUser
36
-     * @param boolean $ccMailingList
37
-     */
38
-    public function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
39
-    {
40
-        $headers = array(
41
-            'X-ACC-Request' => $request->getId(),
42
-            'X-ACC-UserID'  => $currentUser->getId(),
43
-        );
44
-
45
-        if ($ccMailingList) {
46
-            $headers['Cc'] = '[email protected]';
47
-        }
48
-
49
-        $helper = $this->emailHelper;
50
-
51
-        $emailSig = $currentUser->getEmailSig();
52
-        if ($emailSig !== '' || $emailSig !== null) {
53
-            $emailSig = "\n\n" . $emailSig;
54
-        }
55
-
56
-        $subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
57
-        $content = $mailText . $emailSig;
58
-
59
-        $helper->sendMail($request->getEmail(), $subject, $content, $headers);
60
-
61
-        $request->setEmailSent(true);
62
-    }
17
+	/**
18
+	 * @var IEmailHelper
19
+	 */
20
+	private $emailHelper;
21
+
22
+	/**
23
+	 * RequestEmailHelper constructor.
24
+	 *
25
+	 * @param IEmailHelper $emailHelper
26
+	 */
27
+	public function __construct(IEmailHelper $emailHelper)
28
+	{
29
+		$this->emailHelper = $emailHelper;
30
+	}
31
+
32
+	/**
33
+	 * @param Request $request
34
+	 * @param string  $mailText
35
+	 * @param User    $currentUser
36
+	 * @param boolean $ccMailingList
37
+	 */
38
+	public function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
39
+	{
40
+		$headers = array(
41
+			'X-ACC-Request' => $request->getId(),
42
+			'X-ACC-UserID'  => $currentUser->getId(),
43
+		);
44
+
45
+		if ($ccMailingList) {
46
+			$headers['Cc'] = '[email protected]';
47
+		}
48
+
49
+		$helper = $this->emailHelper;
50
+
51
+		$emailSig = $currentUser->getEmailSig();
52
+		if ($emailSig !== '' || $emailSig !== null) {
53
+			$emailSig = "\n\n" . $emailSig;
54
+		}
55
+
56
+		$subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
57
+		$content = $mailText . $emailSig;
58
+
59
+		$helper->sendMail($request->getEmail(), $subject, $content, $headers);
60
+
61
+		$request->setEmailSent(true);
62
+	}
63 63
 }
Please login to merge, or discard this patch.