Completed
Pull Request — rbac (#493)
by
unknown
05:49
created
includes/Pages/PagePreferences.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -16,99 +16,99 @@
 block discarded – undo
16 16
 
17 17
 class PagePreferences extends InternalPageBase
18 18
 {
19
-    /**
20
-     * Main function for this page, when no specific actions are called.
21
-     * @return void
22
-     */
23
-    protected function main()
24
-    {
25
-        $this->setHtmlTitle('Preferences');
26
-
27
-        $enforceOAuth = $this->getSiteConfiguration()->getEnforceOAuth();
28
-
29
-        // Dual mode
30
-        if (WebRequest::wasPosted()) {
31
-            $this->validateCSRFToken();
32
-            $user = User::getCurrent($this->getDatabase());
33
-            $user->setWelcomeSig(WebRequest::postString('sig'));
34
-            $user->setEmailSig(WebRequest::postString('emailsig'));
35
-            $user->setAbortPref(WebRequest::getBoolean('sig') ? 1 : 0);
36
-
37
-            $email = WebRequest::postEmail('email');
38
-            if ($email !== null) {
39
-                $user->setEmail($email);
40
-            }
41
-
42
-            $user->save();
43
-            SessionAlert::success("Preferences updated!");
44
-
45
-            $this->redirect('');
46
-        }
47
-        else {
48
-            $this->assignCSRFToken();
49
-            $this->setTemplate('preferences/prefs.tpl');
50
-            $this->assign("enforceOAuth", $enforceOAuth);
51
-        }
52
-    }
53
-
54
-    protected function changePassword()
55
-    {
56
-        $this->setHtmlTitle('Change Password');
57
-
58
-        if (WebRequest::wasPosted()) {
59
-            $this->validateCSRFToken();
60
-            try {
61
-                $oldPassword = WebRequest::postString('oldpassword');
62
-                $newPassword = WebRequest::postString('newpassword');
63
-                $newPasswordConfirmation = WebRequest::postString('newpasswordconfirm');
64
-
65
-                $user = User::getCurrent($this->getDatabase());
66
-                if (!$user instanceof User) {
67
-                    throw new ApplicationLogicException('User not found');
68
-                }
69
-
70
-                $this->validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, $user);
71
-            }
72
-            catch (ApplicationLogicException $ex) {
73
-                SessionAlert::error($ex->getMessage());
74
-                $this->redirect('preferences', 'changePassword');
75
-
76
-                return;
77
-            }
78
-
79
-            $user->setPassword($newPassword);
80
-            $user->save();
81
-
82
-            SessionAlert::success('Password changed successfully!');
83
-
84
-            $this->redirect('preferences');
85
-        }
86
-        else {
87
-            // not allowed to GET this.
88
-            $this->redirect('preferences');
89
-        }
90
-    }
91
-
92
-    /**
93
-     * @param string $oldPassword
94
-     * @param string $newPassword
95
-     * @param string $newPasswordConfirmation
96
-     * @param User   $user
97
-     *
98
-     * @throws ApplicationLogicException
99
-     */
100
-    protected function validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, User $user)
101
-    {
102
-        if ($oldPassword === null || $newPassword === null || $newPasswordConfirmation === null) {
103
-            throw new ApplicationLogicException('All three fields must be completed to change your password');
104
-        }
105
-
106
-        if ($newPassword !== $newPasswordConfirmation) {
107
-            throw new ApplicationLogicException('Your new passwords did not match!');
108
-        }
109
-
110
-        if (!$user->authenticate($oldPassword)) {
111
-            throw new ApplicationLogicException('The password you entered was incorrect.');
112
-        }
113
-    }
19
+	/**
20
+	 * Main function for this page, when no specific actions are called.
21
+	 * @return void
22
+	 */
23
+	protected function main()
24
+	{
25
+		$this->setHtmlTitle('Preferences');
26
+
27
+		$enforceOAuth = $this->getSiteConfiguration()->getEnforceOAuth();
28
+
29
+		// Dual mode
30
+		if (WebRequest::wasPosted()) {
31
+			$this->validateCSRFToken();
32
+			$user = User::getCurrent($this->getDatabase());
33
+			$user->setWelcomeSig(WebRequest::postString('sig'));
34
+			$user->setEmailSig(WebRequest::postString('emailsig'));
35
+			$user->setAbortPref(WebRequest::getBoolean('sig') ? 1 : 0);
36
+
37
+			$email = WebRequest::postEmail('email');
38
+			if ($email !== null) {
39
+				$user->setEmail($email);
40
+			}
41
+
42
+			$user->save();
43
+			SessionAlert::success("Preferences updated!");
44
+
45
+			$this->redirect('');
46
+		}
47
+		else {
48
+			$this->assignCSRFToken();
49
+			$this->setTemplate('preferences/prefs.tpl');
50
+			$this->assign("enforceOAuth", $enforceOAuth);
51
+		}
52
+	}
53
+
54
+	protected function changePassword()
55
+	{
56
+		$this->setHtmlTitle('Change Password');
57
+
58
+		if (WebRequest::wasPosted()) {
59
+			$this->validateCSRFToken();
60
+			try {
61
+				$oldPassword = WebRequest::postString('oldpassword');
62
+				$newPassword = WebRequest::postString('newpassword');
63
+				$newPasswordConfirmation = WebRequest::postString('newpasswordconfirm');
64
+
65
+				$user = User::getCurrent($this->getDatabase());
66
+				if (!$user instanceof User) {
67
+					throw new ApplicationLogicException('User not found');
68
+				}
69
+
70
+				$this->validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, $user);
71
+			}
72
+			catch (ApplicationLogicException $ex) {
73
+				SessionAlert::error($ex->getMessage());
74
+				$this->redirect('preferences', 'changePassword');
75
+
76
+				return;
77
+			}
78
+
79
+			$user->setPassword($newPassword);
80
+			$user->save();
81
+
82
+			SessionAlert::success('Password changed successfully!');
83
+
84
+			$this->redirect('preferences');
85
+		}
86
+		else {
87
+			// not allowed to GET this.
88
+			$this->redirect('preferences');
89
+		}
90
+	}
91
+
92
+	/**
93
+	 * @param string $oldPassword
94
+	 * @param string $newPassword
95
+	 * @param string $newPasswordConfirmation
96
+	 * @param User   $user
97
+	 *
98
+	 * @throws ApplicationLogicException
99
+	 */
100
+	protected function validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, User $user)
101
+	{
102
+		if ($oldPassword === null || $newPassword === null || $newPasswordConfirmation === null) {
103
+			throw new ApplicationLogicException('All three fields must be completed to change your password');
104
+		}
105
+
106
+		if ($newPassword !== $newPasswordConfirmation) {
107
+			throw new ApplicationLogicException('Your new passwords did not match!');
108
+		}
109
+
110
+		if (!$user->authenticate($oldPassword)) {
111
+			throw new ApplicationLogicException('The password you entered was incorrect.');
112
+		}
113
+	}
114 114
 }
Please login to merge, or discard this patch.
includes/Pages/PageMain.php 1 patch
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -17,71 +17,71 @@  discard block
 block discarded – undo
17 17
 
18 18
 class PageMain extends InternalPageBase
19 19
 {
20
-    /**
21
-     * Main function for this page, when no actions are called.
22
-     */
23
-    protected function main()
24
-    {
25
-        $this->assignCSRFToken();
26
-
27
-        $config = $this->getSiteConfiguration();
28
-
29
-        $database = $this->getDatabase();
30
-
31
-        $requestSectionData = array();
32
-
33
-        if ($config->getEmailConfirmationEnabled()) {
34
-            $query = "SELECT * FROM request WHERE status = :type AND emailconfirm = 'Confirmed' LIMIT :lim;";
35
-            $totalQuery = "SELECT COUNT(id) FROM request WHERE status = :type AND emailconfirm = 'Confirmed';";
36
-        }
37
-        else {
38
-            $query = "SELECT * FROM request WHERE status = :type LIMIT :lim;";
39
-            $totalQuery = "SELECT COUNT(id) FROM request WHERE status = :type;";
40
-        }
41
-
42
-        $statement = $database->prepare($query);
43
-        $statement->bindValue(':lim', $config->getMiserModeLimit(), PDO::PARAM_INT);
44
-
45
-        $totalRequestsStatement = $database->prepare($totalQuery);
46
-
47
-        $this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
48
-
49
-        foreach ($config->getRequestStates() as $type => $v) {
50
-            $statement->bindValue(":type", $type);
51
-            $statement->execute();
52
-
53
-            $requests = $statement->fetchAll(PDO::FETCH_CLASS, Request::class);
54
-
55
-            /** @var Request $req */
56
-            foreach ($requests as $req) {
57
-                $req->setDatabase($database);
58
-            }
59
-
60
-            $totalRequestsStatement->bindValue(':type', $type);
61
-            $totalRequestsStatement->execute();
62
-            $totalRequests = $totalRequestsStatement->fetchColumn();
63
-            $totalRequestsStatement->closeCursor();
64
-
65
-            $userIds = array_map(
66
-                function(Request $entry) {
67
-                    return $entry->getReserved();
68
-                },
69
-                $requests);
70
-            $userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
71
-            $this->assign('userlist', $userList);
72
-
73
-            $requestSectionData[$v['header']] = array(
74
-                'requests' => $requests,
75
-                'total'    => $totalRequests,
76
-                'api'      => $v['api'],
77
-                'type'     => $type,
78
-                'userlist' => $userList,
79
-            );
80
-        }
81
-
82
-        $this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
83
-
84
-        $query = <<<SQL
20
+	/**
21
+	 * Main function for this page, when no actions are called.
22
+	 */
23
+	protected function main()
24
+	{
25
+		$this->assignCSRFToken();
26
+
27
+		$config = $this->getSiteConfiguration();
28
+
29
+		$database = $this->getDatabase();
30
+
31
+		$requestSectionData = array();
32
+
33
+		if ($config->getEmailConfirmationEnabled()) {
34
+			$query = "SELECT * FROM request WHERE status = :type AND emailconfirm = 'Confirmed' LIMIT :lim;";
35
+			$totalQuery = "SELECT COUNT(id) FROM request WHERE status = :type AND emailconfirm = 'Confirmed';";
36
+		}
37
+		else {
38
+			$query = "SELECT * FROM request WHERE status = :type LIMIT :lim;";
39
+			$totalQuery = "SELECT COUNT(id) FROM request WHERE status = :type;";
40
+		}
41
+
42
+		$statement = $database->prepare($query);
43
+		$statement->bindValue(':lim', $config->getMiserModeLimit(), PDO::PARAM_INT);
44
+
45
+		$totalRequestsStatement = $database->prepare($totalQuery);
46
+
47
+		$this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
48
+
49
+		foreach ($config->getRequestStates() as $type => $v) {
50
+			$statement->bindValue(":type", $type);
51
+			$statement->execute();
52
+
53
+			$requests = $statement->fetchAll(PDO::FETCH_CLASS, Request::class);
54
+
55
+			/** @var Request $req */
56
+			foreach ($requests as $req) {
57
+				$req->setDatabase($database);
58
+			}
59
+
60
+			$totalRequestsStatement->bindValue(':type', $type);
61
+			$totalRequestsStatement->execute();
62
+			$totalRequests = $totalRequestsStatement->fetchColumn();
63
+			$totalRequestsStatement->closeCursor();
64
+
65
+			$userIds = array_map(
66
+				function(Request $entry) {
67
+					return $entry->getReserved();
68
+				},
69
+				$requests);
70
+			$userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
71
+			$this->assign('userlist', $userList);
72
+
73
+			$requestSectionData[$v['header']] = array(
74
+				'requests' => $requests,
75
+				'total'    => $totalRequests,
76
+				'api'      => $v['api'],
77
+				'type'     => $type,
78
+				'userlist' => $userList,
79
+			);
80
+		}
81
+
82
+		$this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
83
+
84
+		$query = <<<SQL
85 85
 		SELECT request.id, request.name, request.updateversion
86 86
 		FROM request /* PageMain::main() */
87 87
 		JOIN log ON log.objectid = request.id AND log.objecttype = 'Request'
@@ -90,18 +90,18 @@  discard block
 block discarded – undo
90 90
 		LIMIT 5;
91 91
 SQL;
92 92
 
93
-        $statement = $database->prepare($query);
94
-        $statement->execute();
93
+		$statement = $database->prepare($query);
94
+		$statement->execute();
95 95
 
96
-        $last5result = $statement->fetchAll(PDO::FETCH_ASSOC);
96
+		$last5result = $statement->fetchAll(PDO::FETCH_ASSOC);
97 97
 
98
-        $this->assign('lastFive', $last5result);
99
-        $this->assign('requestSectionData', $requestSectionData);
98
+		$this->assign('lastFive', $last5result);
99
+		$this->assign('requestSectionData', $requestSectionData);
100 100
 
101
-        $currentUser = User::getCurrent($database);
102
-        $this->assign('canBan', $this->barrierTest('set', $currentUser, PageBan::class));
103
-        $this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
101
+		$currentUser = User::getCurrent($database);
102
+		$this->assign('canBan', $this->barrierTest('set', $currentUser, PageBan::class));
103
+		$this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
104 104
 
105
-        $this->setTemplate('mainpage/mainpage.tpl');
106
-    }
105
+		$this->setTemplate('mainpage/mainpage.tpl');
106
+	}
107 107
 }
Please login to merge, or discard this patch.
includes/Pages/PageSearch.php 2 patches
Indentation   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -20,156 +20,156 @@
 block discarded – undo
20 20
 
21 21
 class PageSearch extends InternalPageBase
22 22
 {
23
-    /**
24
-     * Main function for this page, when no specific actions are called.
25
-     */
26
-    protected function main()
27
-    {
28
-        $this->setHtmlTitle('Search');
29
-
30
-        // Dual-mode page
31
-        if (WebRequest::wasPosted()) {
32
-            $this->validateCSRFToken();
33
-
34
-            $searchType = WebRequest::postString('type');
35
-            $searchTerm = WebRequest::postString('term');
36
-
37
-            $validationError = "";
38
-            if (!$this->validateSearchParameters($searchType, $searchTerm, $validationError)) {
39
-                SessionAlert::error($validationError, "Search error");
40
-                $this->redirect("search");
41
-
42
-                return;
43
-            }
44
-
45
-            $results = array();
46
-
47
-            switch ($searchType) {
48
-                case 'name':
49
-                    $results = $this->getNameSearchResults($searchTerm);
50
-                    break;
51
-                case 'email':
52
-                    $results = $this->getEmailSearchResults($searchTerm);
53
-                    break;
54
-                case 'ip':
55
-                    $results = $this->getIpSearchResults($searchTerm);
56
-                    break;
57
-            }
58
-
59
-            // deal with results
60
-            $this->assign('requests', $results);
61
-            $this->assign('term', $searchTerm);
62
-            $this->assign('target', $searchType);
63
-
64
-            $userIds = array_map(
65
-                function(Request $entry) {
66
-                    return $entry->getReserved();
67
-                },
68
-                $results);
69
-            $userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
70
-            $this->assign('userlist', $userList);
71
-
72
-            $currentUser = User::getCurrent($this->getDatabase());
73
-            $this->assign('canBan', $this->barrierTest('set', $currentUser, PageBan::class));
74
-            $this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
75
-
76
-            $this->assignCSRFToken();
77
-            $this->setTemplate('search/searchResult.tpl');
78
-        }
79
-        else {
80
-            $this->assignCSRFToken();
81
-            $this->setTemplate('search/searchForm.tpl');
82
-        }
83
-    }
84
-
85
-    /**
86
-     * Gets search results by name
87
-     *
88
-     * @param string $searchTerm
89
-     *
90
-     * @returns Request[]
91
-     */
92
-    private function getNameSearchResults($searchTerm)
93
-    {
94
-        $padded = '%' . $searchTerm . '%';
95
-
96
-        /** @var Request[] $requests */
97
-        $requests = RequestSearchHelper::get($this->getDatabase())
98
-            ->byName($padded)
99
-            ->excludingPurgedData($this->getSiteConfiguration())
100
-            ->fetch();
101
-
102
-        return $requests;
103
-    }
104
-
105
-    /**
106
-     * Gets search results by email
107
-     *
108
-     * @param string $searchTerm
109
-     *
110
-     * @return Request[]
111
-     * @throws ApplicationLogicException
112
-     */
113
-    private function getEmailSearchResults($searchTerm)
114
-    {
115
-        if ($searchTerm === "@") {
116
-            throw new ApplicationLogicException('The search term "@" is not valid for email address searches!');
117
-        }
118
-
119
-        $padded = '%' . $searchTerm . '%';
120
-
121
-        /** @var Request[] $requests */
122
-        $requests = RequestSearchHelper::get($this->getDatabase())
123
-            ->byEmailAddress($padded)
124
-            ->excludingPurgedData($this->getSiteConfiguration())
125
-            ->fetch();
126
-
127
-        return $requests;
128
-    }
129
-
130
-    /**
131
-     * Gets search results by IP address or XFF IP address
132
-     *
133
-     * @param string $searchTerm
134
-     *
135
-     * @returns Request[]
136
-     */
137
-    private function getIpSearchResults($searchTerm)
138
-    {
139
-        /** @var Request[] $requests */
140
-        $requests = RequestSearchHelper::get($this->getDatabase())
141
-            ->byIp($searchTerm)
142
-            ->excludingPurgedData($this->getSiteConfiguration())
143
-            ->fetch();
144
-
145
-        return $requests;
146
-    }
147
-
148
-    /**
149
-     * @param string $searchType
150
-     * @param string $searchTerm
151
-     *
152
-     * @param string $errorMessage
153
-     *
154
-     * @return bool true if parameters are valid
155
-     * @throws ApplicationLogicException
156
-     */
157
-    protected function validateSearchParameters($searchType, $searchTerm, &$errorMessage)
158
-    {
159
-        if (!in_array($searchType, array('name', 'email', 'ip'))) {
160
-            $errorMessage = 'Unknown search type';
161
-
162
-            return false;
163
-        }
164
-
165
-        if ($searchTerm === '%' || $searchTerm === '' || $searchTerm === null) {
166
-            $errorMessage = 'No search term specified entered';
167
-
168
-            return false;
169
-        }
170
-
171
-        $errorMessage = "";
172
-
173
-        return true;
174
-    }
23
+	/**
24
+	 * Main function for this page, when no specific actions are called.
25
+	 */
26
+	protected function main()
27
+	{
28
+		$this->setHtmlTitle('Search');
29
+
30
+		// Dual-mode page
31
+		if (WebRequest::wasPosted()) {
32
+			$this->validateCSRFToken();
33
+
34
+			$searchType = WebRequest::postString('type');
35
+			$searchTerm = WebRequest::postString('term');
36
+
37
+			$validationError = "";
38
+			if (!$this->validateSearchParameters($searchType, $searchTerm, $validationError)) {
39
+				SessionAlert::error($validationError, "Search error");
40
+				$this->redirect("search");
41
+
42
+				return;
43
+			}
44
+
45
+			$results = array();
46
+
47
+			switch ($searchType) {
48
+				case 'name':
49
+					$results = $this->getNameSearchResults($searchTerm);
50
+					break;
51
+				case 'email':
52
+					$results = $this->getEmailSearchResults($searchTerm);
53
+					break;
54
+				case 'ip':
55
+					$results = $this->getIpSearchResults($searchTerm);
56
+					break;
57
+			}
58
+
59
+			// deal with results
60
+			$this->assign('requests', $results);
61
+			$this->assign('term', $searchTerm);
62
+			$this->assign('target', $searchType);
63
+
64
+			$userIds = array_map(
65
+				function(Request $entry) {
66
+					return $entry->getReserved();
67
+				},
68
+				$results);
69
+			$userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
70
+			$this->assign('userlist', $userList);
71
+
72
+			$currentUser = User::getCurrent($this->getDatabase());
73
+			$this->assign('canBan', $this->barrierTest('set', $currentUser, PageBan::class));
74
+			$this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
75
+
76
+			$this->assignCSRFToken();
77
+			$this->setTemplate('search/searchResult.tpl');
78
+		}
79
+		else {
80
+			$this->assignCSRFToken();
81
+			$this->setTemplate('search/searchForm.tpl');
82
+		}
83
+	}
84
+
85
+	/**
86
+	 * Gets search results by name
87
+	 *
88
+	 * @param string $searchTerm
89
+	 *
90
+	 * @returns Request[]
91
+	 */
92
+	private function getNameSearchResults($searchTerm)
93
+	{
94
+		$padded = '%' . $searchTerm . '%';
95
+
96
+		/** @var Request[] $requests */
97
+		$requests = RequestSearchHelper::get($this->getDatabase())
98
+			->byName($padded)
99
+			->excludingPurgedData($this->getSiteConfiguration())
100
+			->fetch();
101
+
102
+		return $requests;
103
+	}
104
+
105
+	/**
106
+	 * Gets search results by email
107
+	 *
108
+	 * @param string $searchTerm
109
+	 *
110
+	 * @return Request[]
111
+	 * @throws ApplicationLogicException
112
+	 */
113
+	private function getEmailSearchResults($searchTerm)
114
+	{
115
+		if ($searchTerm === "@") {
116
+			throw new ApplicationLogicException('The search term "@" is not valid for email address searches!');
117
+		}
118
+
119
+		$padded = '%' . $searchTerm . '%';
120
+
121
+		/** @var Request[] $requests */
122
+		$requests = RequestSearchHelper::get($this->getDatabase())
123
+			->byEmailAddress($padded)
124
+			->excludingPurgedData($this->getSiteConfiguration())
125
+			->fetch();
126
+
127
+		return $requests;
128
+	}
129
+
130
+	/**
131
+	 * Gets search results by IP address or XFF IP address
132
+	 *
133
+	 * @param string $searchTerm
134
+	 *
135
+	 * @returns Request[]
136
+	 */
137
+	private function getIpSearchResults($searchTerm)
138
+	{
139
+		/** @var Request[] $requests */
140
+		$requests = RequestSearchHelper::get($this->getDatabase())
141
+			->byIp($searchTerm)
142
+			->excludingPurgedData($this->getSiteConfiguration())
143
+			->fetch();
144
+
145
+		return $requests;
146
+	}
147
+
148
+	/**
149
+	 * @param string $searchType
150
+	 * @param string $searchTerm
151
+	 *
152
+	 * @param string $errorMessage
153
+	 *
154
+	 * @return bool true if parameters are valid
155
+	 * @throws ApplicationLogicException
156
+	 */
157
+	protected function validateSearchParameters($searchType, $searchTerm, &$errorMessage)
158
+	{
159
+		if (!in_array($searchType, array('name', 'email', 'ip'))) {
160
+			$errorMessage = 'Unknown search type';
161
+
162
+			return false;
163
+		}
164
+
165
+		if ($searchTerm === '%' || $searchTerm === '' || $searchTerm === null) {
166
+			$errorMessage = 'No search term specified entered';
167
+
168
+			return false;
169
+		}
170
+
171
+		$errorMessage = "";
172
+
173
+		return true;
174
+	}
175 175
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
      */
92 92
     private function getNameSearchResults($searchTerm)
93 93
     {
94
-        $padded = '%' . $searchTerm . '%';
94
+        $padded = '%'.$searchTerm.'%';
95 95
 
96 96
         /** @var Request[] $requests */
97 97
         $requests = RequestSearchHelper::get($this->getDatabase())
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
             throw new ApplicationLogicException('The search term "@" is not valid for email address searches!');
117 117
         }
118 118
 
119
-        $padded = '%' . $searchTerm . '%';
119
+        $padded = '%'.$searchTerm.'%';
120 120
 
121 121
         /** @var Request[] $requests */
122 122
         $requests = RequestSearchHelper::get($this->getDatabase())
Please login to merge, or discard this patch.
includes/Pages/PageBan.php 1 patch
Indentation   +306 added lines, -306 removed lines patch added patch discarded remove patch
@@ -21,310 +21,310 @@
 block discarded – undo
21 21
 
22 22
 class PageBan extends InternalPageBase
23 23
 {
24
-    /**
25
-     * Main function for this page, when no specific actions are called.
26
-     */
27
-    protected function main()
28
-    {
29
-        $this->assignCSRFToken();
30
-
31
-        $this->setHtmlTitle('Bans');
32
-
33
-        $bans = Ban::getActiveBans(null, $this->getDatabase());
34
-
35
-        $userIds = array_map(
36
-            function(Ban $entry) {
37
-                return $entry->getUser();
38
-            },
39
-            $bans);
40
-        $userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
41
-
42
-        $user = User::getCurrent($this->getDatabase());
43
-        $this->assign('canSet', $this->barrierTest('set', $user));
44
-        $this->assign('canRemove', $this->barrierTest('remove', $user));
45
-
46
-        $this->assign('usernames', $userList);
47
-        $this->assign('activebans', $bans);
48
-        $this->setTemplate('bans/banlist.tpl');
49
-    }
50
-
51
-    /**
52
-     * Entry point for the ban set action
53
-     */
54
-    protected function set()
55
-    {
56
-        $this->setHtmlTitle('Bans');
57
-
58
-        // dual-mode action
59
-        if (WebRequest::wasPosted()) {
60
-            try {
61
-                $this->handlePostMethodForSetBan();
62
-            }
63
-            catch (ApplicationLogicException $ex) {
64
-                SessionAlert::error($ex->getMessage());
65
-                $this->redirect("bans", "set");
66
-            }
67
-        }
68
-        else {
69
-            $this->handleGetMethodForSetBan();
70
-        }
71
-    }
72
-
73
-    /**
74
-     * Entry point for the ban remove action
75
-     */
76
-    protected function remove()
77
-    {
78
-        $this->setHtmlTitle('Bans');
79
-
80
-        $ban = $this->getBanForUnban();
81
-
82
-        // dual mode
83
-        if (WebRequest::wasPosted()) {
84
-            $this->validateCSRFToken();
85
-            $unbanReason = WebRequest::postString('unbanreason');
86
-
87
-            if ($unbanReason === null || trim($unbanReason) === "") {
88
-                SessionAlert::error('No unban reason specified');
89
-                $this->redirect("bans", "remove", array('id' => $ban->getId()));
90
-            }
91
-
92
-            // set optimistic locking from delete form page load
93
-            $updateVersion = WebRequest::postInt('updateversion');
94
-            $ban->setUpdateVersion($updateVersion);
95
-
96
-            $database = $this->getDatabase();
97
-            $ban->setActive(false);
98
-            $ban->save();
99
-
100
-            Logger::unbanned($database, $ban, $unbanReason);
101
-
102
-            SessionAlert::quick('Disabled ban.');
103
-            $this->getNotificationHelper()->unbanned($ban, $unbanReason);
104
-
105
-            $this->redirect('bans');
106
-        }
107
-        else {
108
-            $this->assignCSRFToken();
109
-            $this->assign('ban', $ban);
110
-            $this->setTemplate('bans/unban.tpl');
111
-        }
112
-    }
113
-
114
-    /**
115
-     * @throws ApplicationLogicException
116
-     */
117
-    private function getBanDuration()
118
-    {
119
-        $duration = WebRequest::postString('duration');
120
-        if ($duration === "other") {
121
-            $duration = strtotime(WebRequest::postString('otherduration'));
122
-
123
-            if (!$duration) {
124
-                throw new ApplicationLogicException('Invalid ban time');
125
-            }
126
-            elseif (time() > $duration) {
127
-                throw new ApplicationLogicException('Ban time has already expired!');
128
-            }
129
-
130
-            return $duration;
131
-        }
132
-        elseif ($duration === "-1") {
133
-            $duration = -1;
134
-
135
-            return $duration;
136
-        }
137
-        else {
138
-            $duration = WebRequest::postInt('duration') + time();
139
-
140
-            return $duration;
141
-        }
142
-    }
143
-
144
-    /**
145
-     * @param string $type
146
-     * @param string $target
147
-     *
148
-     * @throws ApplicationLogicException
149
-     */
150
-    private function validateBanType($type, $target)
151
-    {
152
-        switch ($type) {
153
-            case 'IP':
154
-                $this->validateIpBan($target);
155
-
156
-                return;
157
-            case 'Name':
158
-                // No validation needed here.
159
-                return;
160
-            case 'EMail':
161
-                $this->validateEmailBanTarget($target);
162
-
163
-                return;
164
-            default:
165
-                throw new ApplicationLogicException("Unknown ban type");
166
-        }
167
-    }
168
-
169
-    /**
170
-     * Handles the POST method on the set action
171
-     *
172
-     * @throws ApplicationLogicException
173
-     * @throws Exception
174
-     */
175
-    private function handlePostMethodForSetBan()
176
-    {
177
-        $this->validateCSRFToken();
178
-        $reason = WebRequest::postString('banreason');
179
-        $target = WebRequest::postString('target');
180
-
181
-        // Checks whether there is a reason entered for ban.
182
-        if ($reason === null || trim($reason) === "") {
183
-            throw new ApplicationLogicException('You must specify a ban reason');
184
-        }
185
-
186
-        // Checks whether there is a target entered to ban.
187
-        if ($target === null || trim($target) === "") {
188
-            throw new ApplicationLogicException('You must specify a target to be banned');
189
-        }
190
-
191
-        // Validate ban duration
192
-        $duration = $this->getBanDuration();
193
-
194
-        // Validate ban type & target for that type
195
-        $type = WebRequest::postString('type');
196
-        $this->validateBanType($type, $target);
197
-
198
-        $database = $this->getDatabase();
199
-
200
-        if (count(Ban::getActiveBans($target, $database)) > 0) {
201
-            throw new ApplicationLogicException('This target is already banned!');
202
-        }
203
-
204
-        $ban = new Ban();
205
-        $ban->setDatabase($database);
206
-        $ban->setActive(true);
207
-        $ban->setType($type);
208
-        $ban->setTarget($target);
209
-        $ban->setUser(User::getCurrent($database)->getId());
210
-        $ban->setReason($reason);
211
-        $ban->setDuration($duration);
212
-
213
-        $ban->save();
214
-
215
-        Logger::banned($database, $ban, $reason);
216
-
217
-        $this->getNotificationHelper()->banned($ban);
218
-        SessionAlert::quick('Ban has been set.');
219
-
220
-        $this->redirect('bans');
221
-    }
222
-
223
-    /**
224
-     * Handles the GET method on the set action
225
-     */
226
-    protected function handleGetMethodForSetBan()
227
-    {
228
-        $this->setTemplate('bans/banform.tpl');
229
-        $this->assignCSRFToken();
230
-
231
-        $banType = WebRequest::getString('type');
232
-        $banTarget = WebRequest::getInt('request');
233
-
234
-        $database = $this->getDatabase();
235
-
236
-        // if the parameters are null, skip loading a request.
237
-        if ($banType === null
238
-            || !in_array($banType, array('IP', 'Name', 'EMail'))
239
-            || $banTarget === null
240
-            || $banTarget === 0
241
-        ) {
242
-            $this->assign('bantarget', '');
243
-            $this->assign('bantype', '');
244
-
245
-            return;
246
-        }
247
-
248
-        // Set the ban type, which the user has indicated.
249
-        $this->assign('bantype', $banType);
250
-
251
-        // Attempt to resolve the correct target
252
-        /** @var Request $request */
253
-        $request = Request::getById($banTarget, $database);
254
-        if ($request === false) {
255
-            $this->assign('bantarget', '');
256
-
257
-            return;
258
-        }
259
-
260
-        $realTarget = '';
261
-        switch ($banType) {
262
-            case 'EMail':
263
-                $realTarget = $request->getEmail();
264
-                break;
265
-            case 'IP':
266
-                $xffProvider = $this->getXffTrustProvider();
267
-                $realTarget = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
268
-                break;
269
-            case 'Name':
270
-                $realTarget = $request->getName();
271
-                break;
272
-        }
273
-
274
-        $this->assign('bantarget', $realTarget);
275
-    }
276
-
277
-    /**
278
-     * Validates an IP ban target
279
-     *
280
-     * @param string $target
281
-     *
282
-     * @throws ApplicationLogicException
283
-     */
284
-    private function validateIpBan($target)
285
-    {
286
-        $squidIpList = $this->getSiteConfiguration()->getSquidList();
287
-
288
-        if (filter_var($target, FILTER_VALIDATE_IP) === false) {
289
-            throw new ApplicationLogicException('Invalid target - IP address expected.');
290
-        }
291
-
292
-        if (in_array($target, $squidIpList)) {
293
-            throw new ApplicationLogicException("This IP address is on the protected list of proxies, and cannot be banned.");
294
-        }
295
-    }
296
-
297
-    /**
298
-     * Validates an email address as a ban target
299
-     *
300
-     * @param string $target
301
-     *
302
-     * @throws ApplicationLogicException
303
-     */
304
-    private function validateEmailBanTarget($target)
305
-    {
306
-        if (filter_var($target, FILTER_VALIDATE_EMAIL) !== $target) {
307
-            throw new ApplicationLogicException('Invalid target - email address expected.');
308
-        }
309
-    }
310
-
311
-    /**
312
-     * @return Ban
313
-     * @throws ApplicationLogicException
314
-     */
315
-    private function getBanForUnban()
316
-    {
317
-        $banId = WebRequest::getInt('id');
318
-        if ($banId === null || $banId === 0) {
319
-            throw new ApplicationLogicException("The ban ID appears to be missing. This is probably a bug.");
320
-        }
321
-
322
-        $ban = Ban::getActiveId($banId, $this->getDatabase());
323
-
324
-        if ($ban === false) {
325
-            throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
326
-        }
327
-
328
-        return $ban;
329
-    }
24
+	/**
25
+	 * Main function for this page, when no specific actions are called.
26
+	 */
27
+	protected function main()
28
+	{
29
+		$this->assignCSRFToken();
30
+
31
+		$this->setHtmlTitle('Bans');
32
+
33
+		$bans = Ban::getActiveBans(null, $this->getDatabase());
34
+
35
+		$userIds = array_map(
36
+			function(Ban $entry) {
37
+				return $entry->getUser();
38
+			},
39
+			$bans);
40
+		$userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
41
+
42
+		$user = User::getCurrent($this->getDatabase());
43
+		$this->assign('canSet', $this->barrierTest('set', $user));
44
+		$this->assign('canRemove', $this->barrierTest('remove', $user));
45
+
46
+		$this->assign('usernames', $userList);
47
+		$this->assign('activebans', $bans);
48
+		$this->setTemplate('bans/banlist.tpl');
49
+	}
50
+
51
+	/**
52
+	 * Entry point for the ban set action
53
+	 */
54
+	protected function set()
55
+	{
56
+		$this->setHtmlTitle('Bans');
57
+
58
+		// dual-mode action
59
+		if (WebRequest::wasPosted()) {
60
+			try {
61
+				$this->handlePostMethodForSetBan();
62
+			}
63
+			catch (ApplicationLogicException $ex) {
64
+				SessionAlert::error($ex->getMessage());
65
+				$this->redirect("bans", "set");
66
+			}
67
+		}
68
+		else {
69
+			$this->handleGetMethodForSetBan();
70
+		}
71
+	}
72
+
73
+	/**
74
+	 * Entry point for the ban remove action
75
+	 */
76
+	protected function remove()
77
+	{
78
+		$this->setHtmlTitle('Bans');
79
+
80
+		$ban = $this->getBanForUnban();
81
+
82
+		// dual mode
83
+		if (WebRequest::wasPosted()) {
84
+			$this->validateCSRFToken();
85
+			$unbanReason = WebRequest::postString('unbanreason');
86
+
87
+			if ($unbanReason === null || trim($unbanReason) === "") {
88
+				SessionAlert::error('No unban reason specified');
89
+				$this->redirect("bans", "remove", array('id' => $ban->getId()));
90
+			}
91
+
92
+			// set optimistic locking from delete form page load
93
+			$updateVersion = WebRequest::postInt('updateversion');
94
+			$ban->setUpdateVersion($updateVersion);
95
+
96
+			$database = $this->getDatabase();
97
+			$ban->setActive(false);
98
+			$ban->save();
99
+
100
+			Logger::unbanned($database, $ban, $unbanReason);
101
+
102
+			SessionAlert::quick('Disabled ban.');
103
+			$this->getNotificationHelper()->unbanned($ban, $unbanReason);
104
+
105
+			$this->redirect('bans');
106
+		}
107
+		else {
108
+			$this->assignCSRFToken();
109
+			$this->assign('ban', $ban);
110
+			$this->setTemplate('bans/unban.tpl');
111
+		}
112
+	}
113
+
114
+	/**
115
+	 * @throws ApplicationLogicException
116
+	 */
117
+	private function getBanDuration()
118
+	{
119
+		$duration = WebRequest::postString('duration');
120
+		if ($duration === "other") {
121
+			$duration = strtotime(WebRequest::postString('otherduration'));
122
+
123
+			if (!$duration) {
124
+				throw new ApplicationLogicException('Invalid ban time');
125
+			}
126
+			elseif (time() > $duration) {
127
+				throw new ApplicationLogicException('Ban time has already expired!');
128
+			}
129
+
130
+			return $duration;
131
+		}
132
+		elseif ($duration === "-1") {
133
+			$duration = -1;
134
+
135
+			return $duration;
136
+		}
137
+		else {
138
+			$duration = WebRequest::postInt('duration') + time();
139
+
140
+			return $duration;
141
+		}
142
+	}
143
+
144
+	/**
145
+	 * @param string $type
146
+	 * @param string $target
147
+	 *
148
+	 * @throws ApplicationLogicException
149
+	 */
150
+	private function validateBanType($type, $target)
151
+	{
152
+		switch ($type) {
153
+			case 'IP':
154
+				$this->validateIpBan($target);
155
+
156
+				return;
157
+			case 'Name':
158
+				// No validation needed here.
159
+				return;
160
+			case 'EMail':
161
+				$this->validateEmailBanTarget($target);
162
+
163
+				return;
164
+			default:
165
+				throw new ApplicationLogicException("Unknown ban type");
166
+		}
167
+	}
168
+
169
+	/**
170
+	 * Handles the POST method on the set action
171
+	 *
172
+	 * @throws ApplicationLogicException
173
+	 * @throws Exception
174
+	 */
175
+	private function handlePostMethodForSetBan()
176
+	{
177
+		$this->validateCSRFToken();
178
+		$reason = WebRequest::postString('banreason');
179
+		$target = WebRequest::postString('target');
180
+
181
+		// Checks whether there is a reason entered for ban.
182
+		if ($reason === null || trim($reason) === "") {
183
+			throw new ApplicationLogicException('You must specify a ban reason');
184
+		}
185
+
186
+		// Checks whether there is a target entered to ban.
187
+		if ($target === null || trim($target) === "") {
188
+			throw new ApplicationLogicException('You must specify a target to be banned');
189
+		}
190
+
191
+		// Validate ban duration
192
+		$duration = $this->getBanDuration();
193
+
194
+		// Validate ban type & target for that type
195
+		$type = WebRequest::postString('type');
196
+		$this->validateBanType($type, $target);
197
+
198
+		$database = $this->getDatabase();
199
+
200
+		if (count(Ban::getActiveBans($target, $database)) > 0) {
201
+			throw new ApplicationLogicException('This target is already banned!');
202
+		}
203
+
204
+		$ban = new Ban();
205
+		$ban->setDatabase($database);
206
+		$ban->setActive(true);
207
+		$ban->setType($type);
208
+		$ban->setTarget($target);
209
+		$ban->setUser(User::getCurrent($database)->getId());
210
+		$ban->setReason($reason);
211
+		$ban->setDuration($duration);
212
+
213
+		$ban->save();
214
+
215
+		Logger::banned($database, $ban, $reason);
216
+
217
+		$this->getNotificationHelper()->banned($ban);
218
+		SessionAlert::quick('Ban has been set.');
219
+
220
+		$this->redirect('bans');
221
+	}
222
+
223
+	/**
224
+	 * Handles the GET method on the set action
225
+	 */
226
+	protected function handleGetMethodForSetBan()
227
+	{
228
+		$this->setTemplate('bans/banform.tpl');
229
+		$this->assignCSRFToken();
230
+
231
+		$banType = WebRequest::getString('type');
232
+		$banTarget = WebRequest::getInt('request');
233
+
234
+		$database = $this->getDatabase();
235
+
236
+		// if the parameters are null, skip loading a request.
237
+		if ($banType === null
238
+			|| !in_array($banType, array('IP', 'Name', 'EMail'))
239
+			|| $banTarget === null
240
+			|| $banTarget === 0
241
+		) {
242
+			$this->assign('bantarget', '');
243
+			$this->assign('bantype', '');
244
+
245
+			return;
246
+		}
247
+
248
+		// Set the ban type, which the user has indicated.
249
+		$this->assign('bantype', $banType);
250
+
251
+		// Attempt to resolve the correct target
252
+		/** @var Request $request */
253
+		$request = Request::getById($banTarget, $database);
254
+		if ($request === false) {
255
+			$this->assign('bantarget', '');
256
+
257
+			return;
258
+		}
259
+
260
+		$realTarget = '';
261
+		switch ($banType) {
262
+			case 'EMail':
263
+				$realTarget = $request->getEmail();
264
+				break;
265
+			case 'IP':
266
+				$xffProvider = $this->getXffTrustProvider();
267
+				$realTarget = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
268
+				break;
269
+			case 'Name':
270
+				$realTarget = $request->getName();
271
+				break;
272
+		}
273
+
274
+		$this->assign('bantarget', $realTarget);
275
+	}
276
+
277
+	/**
278
+	 * Validates an IP ban target
279
+	 *
280
+	 * @param string $target
281
+	 *
282
+	 * @throws ApplicationLogicException
283
+	 */
284
+	private function validateIpBan($target)
285
+	{
286
+		$squidIpList = $this->getSiteConfiguration()->getSquidList();
287
+
288
+		if (filter_var($target, FILTER_VALIDATE_IP) === false) {
289
+			throw new ApplicationLogicException('Invalid target - IP address expected.');
290
+		}
291
+
292
+		if (in_array($target, $squidIpList)) {
293
+			throw new ApplicationLogicException("This IP address is on the protected list of proxies, and cannot be banned.");
294
+		}
295
+	}
296
+
297
+	/**
298
+	 * Validates an email address as a ban target
299
+	 *
300
+	 * @param string $target
301
+	 *
302
+	 * @throws ApplicationLogicException
303
+	 */
304
+	private function validateEmailBanTarget($target)
305
+	{
306
+		if (filter_var($target, FILTER_VALIDATE_EMAIL) !== $target) {
307
+			throw new ApplicationLogicException('Invalid target - email address expected.');
308
+		}
309
+	}
310
+
311
+	/**
312
+	 * @return Ban
313
+	 * @throws ApplicationLogicException
314
+	 */
315
+	private function getBanForUnban()
316
+	{
317
+		$banId = WebRequest::getInt('id');
318
+		if ($banId === null || $banId === 0) {
319
+			throw new ApplicationLogicException("The ban ID appears to be missing. This is probably a bug.");
320
+		}
321
+
322
+		$ban = Ban::getActiveId($banId, $this->getDatabase());
323
+
324
+		if ($ban === false) {
325
+			throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
326
+		}
327
+
328
+		return $ban;
329
+	}
330 330
 }
Please login to merge, or discard this patch.
includes/Pages/PageExpandedRequestList.php 1 patch
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -18,77 +18,77 @@
 block discarded – undo
18 18
 
19 19
 class PageExpandedRequestList extends InternalPageBase
20 20
 {
21
-    /**
22
-     * Main function for this page, when no specific actions are called.
23
-     * @return void
24
-     * @todo This is very similar to the PageMain code, we could probably generalise this somehow
25
-     */
26
-    protected function main()
27
-    {
28
-        $config = $this->getSiteConfiguration();
21
+	/**
22
+	 * Main function for this page, when no specific actions are called.
23
+	 * @return void
24
+	 * @todo This is very similar to the PageMain code, we could probably generalise this somehow
25
+	 */
26
+	protected function main()
27
+	{
28
+		$config = $this->getSiteConfiguration();
29 29
 
30
-        $requestedStatus = WebRequest::getString('status');
31
-        $requestStates = $config->getRequestStates();
30
+		$requestedStatus = WebRequest::getString('status');
31
+		$requestStates = $config->getRequestStates();
32 32
 
33
-        if ($requestedStatus !== null && isset($requestStates[$requestedStatus])) {
33
+		if ($requestedStatus !== null && isset($requestStates[$requestedStatus])) {
34 34
 
35
-            $this->assignCSRFToken();
35
+			$this->assignCSRFToken();
36 36
 
37
-            $database = $this->getDatabase();
37
+			$database = $this->getDatabase();
38 38
 
39
-            if ($config->getEmailConfirmationEnabled()) {
40
-                $query = "SELECT * FROM request WHERE status = :type AND emailconfirm = 'Confirmed';";
41
-                $totalQuery = "SELECT COUNT(id) FROM request WHERE status = :type AND emailconfirm = 'Confirmed';";
42
-            }
43
-            else {
44
-                $query = "SELECT * FROM request WHERE status = :type;";
45
-                $totalQuery = "SELECT COUNT(id) FROM request WHERE status = :type;";
46
-            }
39
+			if ($config->getEmailConfirmationEnabled()) {
40
+				$query = "SELECT * FROM request WHERE status = :type AND emailconfirm = 'Confirmed';";
41
+				$totalQuery = "SELECT COUNT(id) FROM request WHERE status = :type AND emailconfirm = 'Confirmed';";
42
+			}
43
+			else {
44
+				$query = "SELECT * FROM request WHERE status = :type;";
45
+				$totalQuery = "SELECT COUNT(id) FROM request WHERE status = :type;";
46
+			}
47 47
 
48
-            $statement = $database->prepare($query);
48
+			$statement = $database->prepare($query);
49 49
 
50
-            $totalRequestsStatement = $database->prepare($totalQuery);
50
+			$totalRequestsStatement = $database->prepare($totalQuery);
51 51
 
52
-            $this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
52
+			$this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
53 53
 
54
-            $type = $requestedStatus;
54
+			$type = $requestedStatus;
55 55
 
56
-            $statement->bindValue(":type", $type);
57
-            $statement->execute();
56
+			$statement->bindValue(":type", $type);
57
+			$statement->execute();
58 58
 
59
-            $requests = $statement->fetchAll(PDO::FETCH_CLASS, Request::class);
59
+			$requests = $statement->fetchAll(PDO::FETCH_CLASS, Request::class);
60 60
 
61
-            /** @var Request $req */
62
-            foreach ($requests as $req) {
63
-                $req->setDatabase($database);
64
-            }
61
+			/** @var Request $req */
62
+			foreach ($requests as $req) {
63
+				$req->setDatabase($database);
64
+			}
65 65
 
66
-            $this->assign('requests', $requests);
67
-            $this->assign('header', $type);
66
+			$this->assign('requests', $requests);
67
+			$this->assign('header', $type);
68 68
 
69
-            $totalRequestsStatement->bindValue(':type', $type);
70
-            $totalRequestsStatement->execute();
71
-            $totalRequests = $totalRequestsStatement->fetchColumn();
72
-            $totalRequestsStatement->closeCursor();
73
-            $this->assign('totalRequests', $totalRequests);
69
+			$totalRequestsStatement->bindValue(':type', $type);
70
+			$totalRequestsStatement->execute();
71
+			$totalRequests = $totalRequestsStatement->fetchColumn();
72
+			$totalRequestsStatement->closeCursor();
73
+			$this->assign('totalRequests', $totalRequests);
74 74
 
75
-            $userIds = array_map(
76
-                function(Request $entry) {
77
-                    return $entry->getReserved();
78
-                },
79
-                $requests
80
-            );
75
+			$userIds = array_map(
76
+				function(Request $entry) {
77
+					return $entry->getReserved();
78
+				},
79
+				$requests
80
+			);
81 81
 
82
-            $userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
83
-            $this->assign('userlist', $userList);
82
+			$userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
83
+			$this->assign('userlist', $userList);
84 84
 
85
-            $this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
85
+			$this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
86 86
 
87
-            $currentUser = User::getCurrent($database);
88
-            $this->assign('canBan', $this->barrierTest('set', $currentUser, PageBan::class));
89
-            $this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
87
+			$currentUser = User::getCurrent($database);
88
+			$this->assign('canBan', $this->barrierTest('set', $currentUser, PageBan::class));
89
+			$this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
90 90
 
91
-            $this->setTemplate('mainpage/expandedrequestlist.tpl');
92
-        }
93
-    }
91
+			$this->setTemplate('mainpage/expandedrequestlist.tpl');
92
+		}
93
+	}
94 94
 }
Please login to merge, or discard this patch.
includes/Helpers/SearchHelpers/SearchHelperBase.php 3 patches
Indentation   +196 added lines, -196 removed lines patch added patch discarded remove patch
@@ -15,200 +15,200 @@
 block discarded – undo
15 15
 
16 16
 abstract class SearchHelperBase
17 17
 {
18
-    /** @var PdoDatabase */
19
-    protected $database;
20
-    /** @var array */
21
-    protected $parameterList = array();
22
-    /** @var null|int */
23
-    private $limit = null;
24
-    /** @var null|int */
25
-    private $offset = null;
26
-    private $orderBy = null;
27
-    /**
28
-     * @var string The where clause.
29
-     *
30
-     * (the 1=1 condition will be optimised out of the query by the query planner, and simplifies our code here). Note
31
-     * that we use positional parameters instead of named parameters because we don't know many times different options
32
-     * will be called (looking at excluding() here, but there's the option for others).
33
-     */
34
-    protected $whereClause = ' WHERE 1 = 1';
35
-    /** @var string */
36
-    protected $table;
37
-    protected $joinClause = '';
38
-    private $targetClass;
39
-
40
-    /**
41
-     * SearchHelperBase constructor.
42
-     *
43
-     * @param PdoDatabase $database
44
-     * @param string      $table
45
-     * @param             $targetClass
46
-     * @param null|string $order Order by clause, excluding ORDER BY.
47
-     */
48
-    protected function __construct(PdoDatabase $database, $table, $targetClass, $order = null)
49
-    {
50
-        $this->database = $database;
51
-        $this->table = $table;
52
-        $this->orderBy = $order;
53
-        $this->targetClass = $targetClass;
54
-    }
55
-
56
-    /**
57
-     * Finalises the database query, and executes it, returning a set of objects.
58
-     *
59
-     * @return DataObject[]
60
-     */
61
-    public function fetch()
62
-    {
63
-        $statement = $this->getData();
64
-
65
-        /** @var DataObject[] $returnedObjects */
66
-        $returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
67
-        foreach ($returnedObjects as $req) {
68
-            $req->setDatabase($this->database);
69
-        }
70
-
71
-        return $returnedObjects;
72
-    }
73
-
74
-    /**
75
-     * Finalises the database query, and executes it, returning only the requested column.
76
-     *
77
-     * @param string $column The required column
78
-     * @return array
79
-     */
80
-    public function fetchColumn($column){
81
-        $statement = $this->getData(array($column));
82
-
83
-        return $statement->fetchAll(PDO::FETCH_COLUMN);
84
-    }
85
-
86
-    public function fetchMap($column){
87
-        $statement = $this->getData(array('id', $column));
88
-
89
-        $data = $statement->fetchAll(PDO::FETCH_ASSOC);
90
-        $map = array();
91
-
92
-        foreach ($data as $row) {
93
-            $map[$row['id']] = $row[$column];
94
-        }
95
-
96
-        return $map;
97
-    }
98
-
99
-    /**
100
-     * @param int $count Returns the record count of the result set
101
-     *
102
-     * @return $this
103
-     */
104
-    public function getRecordCount(&$count)
105
-    {
106
-        $query = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
107
-        $query .= $this->joinClause . $this->whereClause;
108
-
109
-        $statement = $this->database->prepare($query);
110
-        $statement->execute($this->parameterList);
111
-
112
-        $count = $statement->fetchColumn(0);
113
-        $statement->closeCursor();
114
-
115
-        return $this;
116
-    }
117
-
118
-    /**
119
-     * Limits the results
120
-     *
121
-     * @param integer      $limit
122
-     * @param integer|null $offset
123
-     *
124
-     * @return $this
125
-     *
126
-     */
127
-    public function limit($limit, $offset = null)
128
-    {
129
-        $this->limit = $limit;
130
-        $this->offset = $offset;
131
-
132
-        return $this;
133
-    }
134
-
135
-    private function applyLimit()
136
-    {
137
-        $clause = '';
138
-        if ($this->limit !== null) {
139
-            $clause = ' LIMIT ?';
140
-            $this->parameterList[] = $this->limit;
141
-
142
-            if ($this->offset !== null) {
143
-                $clause .= ' OFFSET ?';
144
-                $this->parameterList[] = $this->offset;
145
-            }
146
-        }
147
-
148
-        return $clause;
149
-    }
150
-
151
-    private function applyOrder()
152
-    {
153
-        if ($this->orderBy !== null) {
154
-            return ' ORDER BY ' . $this->orderBy;
155
-        }
156
-
157
-        return '';
158
-    }
159
-
160
-    /**
161
-     * @param array $columns
162
-     *
163
-     * @return PDOStatement
164
-     */
165
-    private function getData($columns = array('*'))
166
-    {
167
-        $query = $this->buildQuery($columns);
168
-        $query .= $this->applyOrder();
169
-        $query .= $this->applyLimit();
170
-
171
-        $statement = $this->database->prepare($query);
172
-        $statement->execute($this->parameterList);
173
-
174
-        return $statement;
175
-    }
176
-
177
-    /**
178
-     * @param array $columns
179
-     *
180
-     * @return string
181
-     */
182
-    protected function buildQuery($columns)
183
-    {
184
-        $colData = array();
185
-        foreach ($columns as $c) {
186
-            $colData[] = 'origin.' . $c;
187
-        }
188
-
189
-        $query = 'SELECT /* SearchHelper */ ' . implode(', ', $colData) . ' FROM ' . $this->table . ' origin ';
190
-        $query .= $this->joinClause . $this->whereClause;
191
-
192
-        return $query;
193
-    }
194
-
195
-    public function inIds($idList) {
196
-        $this->inClause('id', $idList);
197
-        return $this;
198
-    }
199
-
200
-    protected function inClause($column, $values) {
201
-        if (count($values) === 0) {
202
-            return;
203
-        }
204
-
205
-        // Urgh. OK. You can't use IN() with parameters directly, so let's munge something together.
206
-        $valueCount = count($values);
207
-
208
-        // Firstly, let's create a string of question marks, which will do as positional parameters.
209
-        $inSection = str_repeat('?,', $valueCount - 1) . '?';
210
-
211
-        $this->whereClause .= " AND {$column} IN ({$inSection})";
212
-        $this->parameterList = array_merge($this->parameterList, $values);
213
-    }
18
+	/** @var PdoDatabase */
19
+	protected $database;
20
+	/** @var array */
21
+	protected $parameterList = array();
22
+	/** @var null|int */
23
+	private $limit = null;
24
+	/** @var null|int */
25
+	private $offset = null;
26
+	private $orderBy = null;
27
+	/**
28
+	 * @var string The where clause.
29
+	 *
30
+	 * (the 1=1 condition will be optimised out of the query by the query planner, and simplifies our code here). Note
31
+	 * that we use positional parameters instead of named parameters because we don't know many times different options
32
+	 * will be called (looking at excluding() here, but there's the option for others).
33
+	 */
34
+	protected $whereClause = ' WHERE 1 = 1';
35
+	/** @var string */
36
+	protected $table;
37
+	protected $joinClause = '';
38
+	private $targetClass;
39
+
40
+	/**
41
+	 * SearchHelperBase constructor.
42
+	 *
43
+	 * @param PdoDatabase $database
44
+	 * @param string      $table
45
+	 * @param             $targetClass
46
+	 * @param null|string $order Order by clause, excluding ORDER BY.
47
+	 */
48
+	protected function __construct(PdoDatabase $database, $table, $targetClass, $order = null)
49
+	{
50
+		$this->database = $database;
51
+		$this->table = $table;
52
+		$this->orderBy = $order;
53
+		$this->targetClass = $targetClass;
54
+	}
55
+
56
+	/**
57
+	 * Finalises the database query, and executes it, returning a set of objects.
58
+	 *
59
+	 * @return DataObject[]
60
+	 */
61
+	public function fetch()
62
+	{
63
+		$statement = $this->getData();
64
+
65
+		/** @var DataObject[] $returnedObjects */
66
+		$returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
67
+		foreach ($returnedObjects as $req) {
68
+			$req->setDatabase($this->database);
69
+		}
70
+
71
+		return $returnedObjects;
72
+	}
73
+
74
+	/**
75
+	 * Finalises the database query, and executes it, returning only the requested column.
76
+	 *
77
+	 * @param string $column The required column
78
+	 * @return array
79
+	 */
80
+	public function fetchColumn($column){
81
+		$statement = $this->getData(array($column));
82
+
83
+		return $statement->fetchAll(PDO::FETCH_COLUMN);
84
+	}
85
+
86
+	public function fetchMap($column){
87
+		$statement = $this->getData(array('id', $column));
88
+
89
+		$data = $statement->fetchAll(PDO::FETCH_ASSOC);
90
+		$map = array();
91
+
92
+		foreach ($data as $row) {
93
+			$map[$row['id']] = $row[$column];
94
+		}
95
+
96
+		return $map;
97
+	}
98
+
99
+	/**
100
+	 * @param int $count Returns the record count of the result set
101
+	 *
102
+	 * @return $this
103
+	 */
104
+	public function getRecordCount(&$count)
105
+	{
106
+		$query = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
107
+		$query .= $this->joinClause . $this->whereClause;
108
+
109
+		$statement = $this->database->prepare($query);
110
+		$statement->execute($this->parameterList);
111
+
112
+		$count = $statement->fetchColumn(0);
113
+		$statement->closeCursor();
114
+
115
+		return $this;
116
+	}
117
+
118
+	/**
119
+	 * Limits the results
120
+	 *
121
+	 * @param integer      $limit
122
+	 * @param integer|null $offset
123
+	 *
124
+	 * @return $this
125
+	 *
126
+	 */
127
+	public function limit($limit, $offset = null)
128
+	{
129
+		$this->limit = $limit;
130
+		$this->offset = $offset;
131
+
132
+		return $this;
133
+	}
134
+
135
+	private function applyLimit()
136
+	{
137
+		$clause = '';
138
+		if ($this->limit !== null) {
139
+			$clause = ' LIMIT ?';
140
+			$this->parameterList[] = $this->limit;
141
+
142
+			if ($this->offset !== null) {
143
+				$clause .= ' OFFSET ?';
144
+				$this->parameterList[] = $this->offset;
145
+			}
146
+		}
147
+
148
+		return $clause;
149
+	}
150
+
151
+	private function applyOrder()
152
+	{
153
+		if ($this->orderBy !== null) {
154
+			return ' ORDER BY ' . $this->orderBy;
155
+		}
156
+
157
+		return '';
158
+	}
159
+
160
+	/**
161
+	 * @param array $columns
162
+	 *
163
+	 * @return PDOStatement
164
+	 */
165
+	private function getData($columns = array('*'))
166
+	{
167
+		$query = $this->buildQuery($columns);
168
+		$query .= $this->applyOrder();
169
+		$query .= $this->applyLimit();
170
+
171
+		$statement = $this->database->prepare($query);
172
+		$statement->execute($this->parameterList);
173
+
174
+		return $statement;
175
+	}
176
+
177
+	/**
178
+	 * @param array $columns
179
+	 *
180
+	 * @return string
181
+	 */
182
+	protected function buildQuery($columns)
183
+	{
184
+		$colData = array();
185
+		foreach ($columns as $c) {
186
+			$colData[] = 'origin.' . $c;
187
+		}
188
+
189
+		$query = 'SELECT /* SearchHelper */ ' . implode(', ', $colData) . ' FROM ' . $this->table . ' origin ';
190
+		$query .= $this->joinClause . $this->whereClause;
191
+
192
+		return $query;
193
+	}
194
+
195
+	public function inIds($idList) {
196
+		$this->inClause('id', $idList);
197
+		return $this;
198
+	}
199
+
200
+	protected function inClause($column, $values) {
201
+		if (count($values) === 0) {
202
+			return;
203
+		}
204
+
205
+		// Urgh. OK. You can't use IN() with parameters directly, so let's munge something together.
206
+		$valueCount = count($values);
207
+
208
+		// Firstly, let's create a string of question marks, which will do as positional parameters.
209
+		$inSection = str_repeat('?,', $valueCount - 1) . '?';
210
+
211
+		$this->whereClause .= " AND {$column} IN ({$inSection})";
212
+		$this->parameterList = array_merge($this->parameterList, $values);
213
+	}
214 214
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -77,13 +77,13 @@  discard block
 block discarded – undo
77 77
      * @param string $column The required column
78 78
      * @return array
79 79
      */
80
-    public function fetchColumn($column){
80
+    public function fetchColumn($column) {
81 81
         $statement = $this->getData(array($column));
82 82
 
83 83
         return $statement->fetchAll(PDO::FETCH_COLUMN);
84 84
     }
85 85
 
86
-    public function fetchMap($column){
86
+    public function fetchMap($column) {
87 87
         $statement = $this->getData(array('id', $column));
88 88
 
89 89
         $data = $statement->fetchAll(PDO::FETCH_ASSOC);
@@ -103,8 +103,8 @@  discard block
 block discarded – undo
103 103
      */
104 104
     public function getRecordCount(&$count)
105 105
     {
106
-        $query = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
107
-        $query .= $this->joinClause . $this->whereClause;
106
+        $query = 'SELECT /* SearchHelper */ COUNT(*) FROM '.$this->table.' origin ';
107
+        $query .= $this->joinClause.$this->whereClause;
108 108
 
109 109
         $statement = $this->database->prepare($query);
110 110
         $statement->execute($this->parameterList);
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
     private function applyOrder()
152 152
     {
153 153
         if ($this->orderBy !== null) {
154
-            return ' ORDER BY ' . $this->orderBy;
154
+            return ' ORDER BY '.$this->orderBy;
155 155
         }
156 156
 
157 157
         return '';
@@ -183,11 +183,11 @@  discard block
 block discarded – undo
183 183
     {
184 184
         $colData = array();
185 185
         foreach ($columns as $c) {
186
-            $colData[] = 'origin.' . $c;
186
+            $colData[] = 'origin.'.$c;
187 187
         }
188 188
 
189
-        $query = 'SELECT /* SearchHelper */ ' . implode(', ', $colData) . ' FROM ' . $this->table . ' origin ';
190
-        $query .= $this->joinClause . $this->whereClause;
189
+        $query = 'SELECT /* SearchHelper */ '.implode(', ', $colData).' FROM '.$this->table.' origin ';
190
+        $query .= $this->joinClause.$this->whereClause;
191 191
 
192 192
         return $query;
193 193
     }
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
         $valueCount = count($values);
207 207
 
208 208
         // Firstly, let's create a string of question marks, which will do as positional parameters.
209
-        $inSection = str_repeat('?,', $valueCount - 1) . '?';
209
+        $inSection = str_repeat('?,', $valueCount - 1).'?';
210 210
 
211 211
         $this->whereClause .= " AND {$column} IN ({$inSection})";
212 212
         $this->parameterList = array_merge($this->parameterList, $values);
Please login to merge, or discard this patch.
Braces   +8 added lines, -4 removed lines patch added patch discarded remove patch
@@ -77,13 +77,15 @@  discard block
 block discarded – undo
77 77
      * @param string $column The required column
78 78
      * @return array
79 79
      */
80
-    public function fetchColumn($column){
80
+    public function fetchColumn($column)
81
+    {
81 82
         $statement = $this->getData(array($column));
82 83
 
83 84
         return $statement->fetchAll(PDO::FETCH_COLUMN);
84 85
     }
85 86
 
86
-    public function fetchMap($column){
87
+    public function fetchMap($column)
88
+    {
87 89
         $statement = $this->getData(array('id', $column));
88 90
 
89 91
         $data = $statement->fetchAll(PDO::FETCH_ASSOC);
@@ -192,12 +194,14 @@  discard block
 block discarded – undo
192 194
         return $query;
193 195
     }
194 196
 
195
-    public function inIds($idList) {
197
+    public function inIds($idList)
198
+    {
196 199
         $this->inClause('id', $idList);
197 200
         return $this;
198 201
     }
199 202
 
200
-    protected function inClause($column, $values) {
203
+    protected function inClause($column, $values)
204
+    {
201 205
         if (count($values) === 0) {
202 206
             return;
203 207
         }
Please login to merge, or discard this patch.
includes/ConsoleTasks/ClearOldDataTask.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -13,25 +13,25 @@
 block discarded – undo
13 13
 
14 14
 class ClearOldDataTask extends ConsoleTaskBase
15 15
 {
16
-    public function execute()
17
-    {
18
-        $dataClearInterval = $this->getSiteConfiguration()->getDataClearInterval();
16
+	public function execute()
17
+	{
18
+		$dataClearInterval = $this->getSiteConfiguration()->getDataClearInterval();
19 19
 
20
-        $query = $this->getDatabase()->prepare(<<<SQL
20
+		$query = $this->getDatabase()->prepare(<<<SQL
21 21
 UPDATE request
22 22
 SET ip = :ip, forwardedip = null, email = :mail, useragent = ''
23 23
 WHERE date < DATE_SUB(curdate(), INTERVAL {$dataClearInterval})
24 24
 AND status = 'Closed';
25 25
 SQL
26
-        );
26
+		);
27 27
 
28
-        $success = $query->execute(array(
29
-            ":ip"   => $this->getSiteConfiguration()->getDataClearIp(),
30
-            ":mail" => $this->getSiteConfiguration()->getDataClearEmail(),
31
-        ));
28
+		$success = $query->execute(array(
29
+			":ip"   => $this->getSiteConfiguration()->getDataClearIp(),
30
+			":mail" => $this->getSiteConfiguration()->getDataClearEmail(),
31
+		));
32 32
 
33
-        if (!$success) {
34
-            throw new Exception("Error in transaction: Could not clear data.");
35
-        }
36
-    }
33
+		if (!$success) {
34
+			throw new Exception("Error in transaction: Could not clear data.");
35
+		}
36
+	}
37 37
 }
38 38
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/PageLog.php 1 patch
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -18,149 +18,149 @@
 block discarded – undo
18 18
 
19 19
 class PageLog extends InternalPageBase
20 20
 {
21
-    /**
22
-     * Main function for this page, when no specific actions are called.
23
-     */
24
-    protected function main()
25
-    {
26
-        $this->setHtmlTitle('Logs');
27
-
28
-        $filterUser = WebRequest::getString('filterUser');
29
-        $filterAction = WebRequest::getString('filterAction');
30
-        $filterObjectType = WebRequest::getString('filterObjectType');
31
-        $filterObjectId = WebRequest::getInt('filterObjectId');
32
-
33
-        $database = $this->getDatabase();
34
-
35
-        if (!array_key_exists($filterObjectType, LogHelper::getObjectTypes())) {
36
-            $filterObjectType = null;
37
-        }
38
-
39
-        $this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
40
-            return UserSearchHelper::get($database)->fetchColumn('username');
41
-        });
42
-
43
-        $limit = WebRequest::getInt('limit');
44
-        if ($limit === null) {
45
-            $limit = 100;
46
-        }
47
-
48
-        $page = WebRequest::getInt('page');
49
-        if ($page === null) {
50
-            $page = 1;
51
-        }
52
-
53
-        $offset = ($page - 1) * $limit;
54
-
55
-        $logSearch = LogSearchHelper::get($database)->limit($limit, $offset);
56
-        $this->setupSearchHelper($logSearch, $database, $filterUser, $filterAction, $filterObjectType, $filterObjectId);
57
-
58
-        /** @var Log[] $logs */
59
-        $logs = $logSearch->getRecordCount($count)->fetch();
60
-
61
-        if ($count === 0) {
62
-            $this->assign('logs', array());
63
-            $this->setTemplate('logs/main.tpl');
64
-
65
-            return;
66
-        }
67
-
68
-        list($users, $logData) = LogHelper::prepareLogsForTemplate($logs, $database, $this->getSiteConfiguration());
69
-
70
-        $this->setupPageData($page, $limit, $count);
71
-
72
-        $this->assign("logs", $logData);
73
-        $this->assign("users", $users);
74
-
75
-        $this->assign("filterUser", $filterUser);
76
-        $this->assign("filterAction", $filterAction);
77
-        $this->assign("filterObjectType", $filterObjectType);
78
-        $this->assign("filterObjectId", $filterObjectId);
79
-
80
-        $this->assign('allLogActions', LogHelper::getLogActions($this->getDatabase()));
81
-        $this->assign('allObjectTypes', LogHelper::getObjectTypes());
82
-
83
-        $this->setTemplate("logs/main.tpl");
84
-    }
85
-
86
-    /**
87
-     * @param int $page
88
-     * @param int $limit
89
-     * @param int $count
90
-     */
91
-    protected function setupPageData($page, $limit, $count)
92
-    {
93
-        // The number of pages on the pager to show. Must be odd
94
-        $pageLimit = 9;
95
-
96
-        $pageData = array(
97
-            // Can the user go to the previous page?
98
-            'canprev'   => $page != 1,
99
-            // Can the user go to the next page?
100
-            'cannext'   => ($page * $limit) < $count,
101
-            // Maximum page number
102
-            'maxpage'   => ceil($count / $limit),
103
-            // Limit to the number of pages to display
104
-            'pagelimit' => $pageLimit,
105
-        );
106
-
107
-        // number of pages either side of the current to show
108
-        $pageMargin = (($pageLimit - 1) / 2);
109
-
110
-        // Calculate the number of pages either side to show - this is for situations like:
111
-        //  [1]  [2] [[3]] [4]  [5]  [6]  [7]  [8]  [9] - where you can't just use the page margin calculated
112
-        $pageData['lowpage'] = max(1, $page - $pageMargin);
113
-        $pageData['hipage'] = min($pageData['maxpage'], $page + $pageMargin);
114
-        $pageCount = ($pageData['hipage'] - $pageData['lowpage']) + 1;
115
-
116
-        if ($pageCount < $pageLimit) {
117
-            if ($pageData['lowpage'] == 1 && $pageData['hipage'] < $pageData['maxpage']) {
118
-                $pageData['hipage'] = min($pageLimit, $pageData['maxpage']);
119
-            }
120
-            elseif ($pageData['lowpage'] > 1 && $pageData['hipage'] == $pageData['maxpage']) {
121
-                $pageData['lowpage'] = max(1, $pageData['maxpage'] - $pageLimit + 1);
122
-            }
123
-        }
124
-
125
-        // Put the range of pages into the page data
126
-        $pageData['pages'] = range($pageData['lowpage'], $pageData['hipage']);
127
-
128
-        $this->assign("pagedata", $pageData);
129
-
130
-        $this->assign("limit", $limit);
131
-        $this->assign("page", $page);
132
-    }
133
-
134
-    /**
135
-     * @param $logSearch
136
-     * @param $database
137
-     * @param $filterUser
138
-     * @param $filterAction
139
-     * @param $filterObjectType
140
-     * @param $filterObjectId
141
-     */
142
-    private function setupSearchHelper(
143
-        $logSearch,
144
-        $database,
145
-        $filterUser,
146
-        $filterAction,
147
-        $filterObjectType,
148
-        $filterObjectId
149
-    ) {
150
-        if ($filterUser !== null) {
151
-            $logSearch->byUser(User::getByUsername($filterUser, $database)->getId());
152
-        }
153
-
154
-        if ($filterAction !== null) {
155
-            $logSearch->byAction($filterAction);
156
-        }
157
-
158
-        if ($filterObjectType !== null) {
159
-            $logSearch->byObjectType($filterObjectType);
160
-        }
161
-
162
-        if ($filterObjectId !== null) {
163
-            $logSearch->byObjectId($filterObjectId);
164
-        }
165
-    }
21
+	/**
22
+	 * Main function for this page, when no specific actions are called.
23
+	 */
24
+	protected function main()
25
+	{
26
+		$this->setHtmlTitle('Logs');
27
+
28
+		$filterUser = WebRequest::getString('filterUser');
29
+		$filterAction = WebRequest::getString('filterAction');
30
+		$filterObjectType = WebRequest::getString('filterObjectType');
31
+		$filterObjectId = WebRequest::getInt('filterObjectId');
32
+
33
+		$database = $this->getDatabase();
34
+
35
+		if (!array_key_exists($filterObjectType, LogHelper::getObjectTypes())) {
36
+			$filterObjectType = null;
37
+		}
38
+
39
+		$this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
40
+			return UserSearchHelper::get($database)->fetchColumn('username');
41
+		});
42
+
43
+		$limit = WebRequest::getInt('limit');
44
+		if ($limit === null) {
45
+			$limit = 100;
46
+		}
47
+
48
+		$page = WebRequest::getInt('page');
49
+		if ($page === null) {
50
+			$page = 1;
51
+		}
52
+
53
+		$offset = ($page - 1) * $limit;
54
+
55
+		$logSearch = LogSearchHelper::get($database)->limit($limit, $offset);
56
+		$this->setupSearchHelper($logSearch, $database, $filterUser, $filterAction, $filterObjectType, $filterObjectId);
57
+
58
+		/** @var Log[] $logs */
59
+		$logs = $logSearch->getRecordCount($count)->fetch();
60
+
61
+		if ($count === 0) {
62
+			$this->assign('logs', array());
63
+			$this->setTemplate('logs/main.tpl');
64
+
65
+			return;
66
+		}
67
+
68
+		list($users, $logData) = LogHelper::prepareLogsForTemplate($logs, $database, $this->getSiteConfiguration());
69
+
70
+		$this->setupPageData($page, $limit, $count);
71
+
72
+		$this->assign("logs", $logData);
73
+		$this->assign("users", $users);
74
+
75
+		$this->assign("filterUser", $filterUser);
76
+		$this->assign("filterAction", $filterAction);
77
+		$this->assign("filterObjectType", $filterObjectType);
78
+		$this->assign("filterObjectId", $filterObjectId);
79
+
80
+		$this->assign('allLogActions', LogHelper::getLogActions($this->getDatabase()));
81
+		$this->assign('allObjectTypes', LogHelper::getObjectTypes());
82
+
83
+		$this->setTemplate("logs/main.tpl");
84
+	}
85
+
86
+	/**
87
+	 * @param int $page
88
+	 * @param int $limit
89
+	 * @param int $count
90
+	 */
91
+	protected function setupPageData($page, $limit, $count)
92
+	{
93
+		// The number of pages on the pager to show. Must be odd
94
+		$pageLimit = 9;
95
+
96
+		$pageData = array(
97
+			// Can the user go to the previous page?
98
+			'canprev'   => $page != 1,
99
+			// Can the user go to the next page?
100
+			'cannext'   => ($page * $limit) < $count,
101
+			// Maximum page number
102
+			'maxpage'   => ceil($count / $limit),
103
+			// Limit to the number of pages to display
104
+			'pagelimit' => $pageLimit,
105
+		);
106
+
107
+		// number of pages either side of the current to show
108
+		$pageMargin = (($pageLimit - 1) / 2);
109
+
110
+		// Calculate the number of pages either side to show - this is for situations like:
111
+		//  [1]  [2] [[3]] [4]  [5]  [6]  [7]  [8]  [9] - where you can't just use the page margin calculated
112
+		$pageData['lowpage'] = max(1, $page - $pageMargin);
113
+		$pageData['hipage'] = min($pageData['maxpage'], $page + $pageMargin);
114
+		$pageCount = ($pageData['hipage'] - $pageData['lowpage']) + 1;
115
+
116
+		if ($pageCount < $pageLimit) {
117
+			if ($pageData['lowpage'] == 1 && $pageData['hipage'] < $pageData['maxpage']) {
118
+				$pageData['hipage'] = min($pageLimit, $pageData['maxpage']);
119
+			}
120
+			elseif ($pageData['lowpage'] > 1 && $pageData['hipage'] == $pageData['maxpage']) {
121
+				$pageData['lowpage'] = max(1, $pageData['maxpage'] - $pageLimit + 1);
122
+			}
123
+		}
124
+
125
+		// Put the range of pages into the page data
126
+		$pageData['pages'] = range($pageData['lowpage'], $pageData['hipage']);
127
+
128
+		$this->assign("pagedata", $pageData);
129
+
130
+		$this->assign("limit", $limit);
131
+		$this->assign("page", $page);
132
+	}
133
+
134
+	/**
135
+	 * @param $logSearch
136
+	 * @param $database
137
+	 * @param $filterUser
138
+	 * @param $filterAction
139
+	 * @param $filterObjectType
140
+	 * @param $filterObjectId
141
+	 */
142
+	private function setupSearchHelper(
143
+		$logSearch,
144
+		$database,
145
+		$filterUser,
146
+		$filterAction,
147
+		$filterObjectType,
148
+		$filterObjectId
149
+	) {
150
+		if ($filterUser !== null) {
151
+			$logSearch->byUser(User::getByUsername($filterUser, $database)->getId());
152
+		}
153
+
154
+		if ($filterAction !== null) {
155
+			$logSearch->byAction($filterAction);
156
+		}
157
+
158
+		if ($filterObjectType !== null) {
159
+			$logSearch->byObjectType($filterObjectType);
160
+		}
161
+
162
+		if ($filterObjectId !== null) {
163
+			$logSearch->byObjectId($filterObjectId);
164
+		}
165
+	}
166 166
 }
Please login to merge, or discard this patch.
includes/Helpers/LogHelper.php 2 patches
Indentation   +355 added lines, -355 removed lines patch added patch discarded remove patch
@@ -26,366 +26,366 @@
 block discarded – undo
26 26
 
27 27
 class LogHelper
28 28
 {
29
-    /**
30
-     * Summary of getRequestLogsWithComments
31
-     *
32
-     * @param int             $requestId
33
-     * @param PdoDatabase     $db
34
-     * @param SecurityManager $securityManager
35
-     *
36
-     * @return \Waca\DataObject[]
37
-     */
38
-    public static function getRequestLogsWithComments($requestId, PdoDatabase $db, SecurityManager $securityManager)
39
-    {
40
-        $logs = LogSearchHelper::get($db)->byObjectType('Request')->byObjectId($requestId)->fetch();
41
-
42
-        $currentUser = User::getCurrent($db);
43
-        $securityResult = $securityManager->allows('RequestData', 'seeRestrictedComments', $currentUser);
44
-        $showAllComments = $securityResult === SecurityManager::ALLOWED;
45
-
46
-        $comments = Comment::getForRequest($requestId, $db, $showAllComments, $currentUser->getId());
47
-
48
-        $items = array_merge($logs, $comments);
49
-
50
-        /**
51
-         * @param DataObject $item
52
-         *
53
-         * @return int
54
-         */
55
-        $sortKey = function(DataObject $item) {
56
-            if ($item instanceof Log) {
57
-                return $item->getTimestamp()->getTimestamp();
58
-            }
59
-
60
-            if ($item instanceof Comment) {
61
-                return $item->getTime()->getTimestamp();
62
-            }
63
-
64
-            return 0;
65
-        };
66
-
67
-        do {
68
-            $flag = false;
69
-
70
-            $loopLimit = (count($items) - 1);
71
-            for ($i = 0; $i < $loopLimit; $i++) {
72
-                // are these two items out of order?
73
-                if ($sortKey($items[$i]) > $sortKey($items[$i + 1])) {
74
-                    // swap them
75
-                    $swap = $items[$i];
76
-                    $items[$i] = $items[$i + 1];
77
-                    $items[$i + 1] = $swap;
78
-
79
-                    // set a flag to say we've modified the array this time around
80
-                    $flag = true;
81
-                }
82
-            }
83
-        }
84
-        while ($flag);
85
-
86
-        return $items;
87
-    }
88
-
89
-    /**
90
-     * Summary of getLogDescription
91
-     *
92
-     * @param Log $entry
93
-     *
94
-     * @return string
95
-     */
96
-    public static function getLogDescription(Log $entry)
97
-    {
98
-        $text = "Deferred to ";
99
-        if (substr($entry->getAction(), 0, strlen($text)) == $text) {
100
-            // Deferred to a different queue
101
-            // This is exactly what we want to display.
102
-            return $entry->getAction();
103
-        }
104
-
105
-        $text = "Closed custom-n";
106
-        if ($entry->getAction() == $text) {
107
-            // Custom-closed
108
-            return "closed (custom reason - account not created)";
109
-        }
110
-
111
-        $text = "Closed custom-y";
112
-        if ($entry->getAction() == $text) {
113
-            // Custom-closed
114
-            return "closed (custom reason - account created)";
115
-        }
116
-
117
-        $text = "Closed 0";
118
-        if ($entry->getAction() == $text) {
119
-            // Dropped the request - short-circuit the lookup
120
-            return "dropped request";
121
-        }
122
-
123
-        $text = "Closed ";
124
-        if (substr($entry->getAction(), 0, strlen($text)) == $text) {
125
-            // Closed with a reason - do a lookup here.
126
-            $id = substr($entry->getAction(), strlen($text));
127
-            /** @var EmailTemplate $template */
128
-            $template = EmailTemplate::getById((int)$id, $entry->getDatabase());
129
-
130
-            if ($template != false) {
131
-                return "closed (" . $template->getName() . ")";
132
-            }
133
-        }
134
-
135
-        // Fall back to the basic stuff
136
-        $lookup = array(
137
-            'Reserved'        => 'reserved',
138
-            'Email Confirmed' => 'email-confirmed',
139
-            'Unreserved'      => 'unreserved',
140
-            'Approved'        => 'approved',
141
-            'Suspended'       => 'suspended',
142
-            'RoleChange'      => 'changed roles',
143
-            'Banned'          => 'banned',
144
-            'Edited'          => 'edited interface message',
145
-            'Declined'        => 'declined',
146
-            'EditComment-c'   => 'edited a comment',
147
-            'EditComment-r'   => 'edited a comment',
148
-            'Unbanned'        => 'unbanned',
149
-            'Promoted'        => 'promoted to tool admin',
150
-            'BreakReserve'    => 'forcibly broke the reservation',
151
-            'Prefchange'      => 'changed user preferences',
152
-            'Renamed'         => 'renamed',
153
-            'Demoted'         => 'demoted from tool admin',
154
-            'ReceiveReserved' => 'received the reservation',
155
-            'SendReserved'    => 'sent the reservation',
156
-            'EditedEmail'     => 'edited email',
157
-            'DeletedTemplate' => 'deleted template',
158
-            'EditedTemplate'  => 'edited template',
159
-            'CreatedEmail'    => 'created email',
160
-            'CreatedTemplate' => 'created template',
161
-            'SentMail'        => 'sent an email to the requestor',
162
-            'Registered'      => 'registered a tool account',
163
-        );
164
-
165
-        if (array_key_exists($entry->getAction(), $lookup)) {
166
-            return $lookup[$entry->getAction()];
167
-        }
168
-
169
-        // OK, I don't know what this is. Fall back to something sane.
170
-        return "performed an unknown action ({$entry->getAction()})";
171
-    }
172
-
173
-    /**
174
-     * @param PdoDatabase $database
175
-     *
176
-     * @return array
177
-     */
178
-    public static function getLogActions(PdoDatabase $database)
179
-    {
180
-        $lookup = array(
181
-            'Reserved'        => 'reserved',
182
-            'Email Confirmed' => 'email-confirmed',
183
-            'Unreserved'      => 'unreserved',
184
-            'Approved'        => 'approved',
185
-            'Suspended'       => 'suspended',
186
-            'RoleChange'      => 'changed roles',
187
-            'Banned'          => 'banned',
188
-            'Edited'          => 'edited interface message',
189
-            'Declined'        => 'declined',
190
-            'EditComment-c'   => 'edited a comment (by comment ID)',
191
-            'EditComment-r'   => 'edited a comment (by request)',
192
-            'Unbanned'        => 'unbanned',
193
-            'Promoted'        => 'promoted to tool admin',
194
-            'BreakReserve'    => 'forcibly broke the reservation',
195
-            'Prefchange'      => 'changed user preferences',
196
-            'Renamed'         => 'renamed',
197
-            'Demoted'         => 'demoted from tool admin',
198
-            'ReceiveReserved' => 'received the reservation',
199
-            'SendReserved'    => 'sent the reservation',
200
-            'EditedEmail'     => 'edited email',
201
-            'DeletedTemplate' => 'deleted template',
202
-            'EditedTemplate'  => 'edited template',
203
-            'CreatedEmail'    => 'created email',
204
-            'CreatedTemplate' => 'created template',
205
-            'SentMail'        => 'sent an email to the requestor',
206
-            'Registered'      => 'registered a tool account',
207
-            'Closed 0'        => 'dropped request',
208
-        );
209
-
210
-        $statement = $database->query(<<<SQL
29
+	/**
30
+	 * Summary of getRequestLogsWithComments
31
+	 *
32
+	 * @param int             $requestId
33
+	 * @param PdoDatabase     $db
34
+	 * @param SecurityManager $securityManager
35
+	 *
36
+	 * @return \Waca\DataObject[]
37
+	 */
38
+	public static function getRequestLogsWithComments($requestId, PdoDatabase $db, SecurityManager $securityManager)
39
+	{
40
+		$logs = LogSearchHelper::get($db)->byObjectType('Request')->byObjectId($requestId)->fetch();
41
+
42
+		$currentUser = User::getCurrent($db);
43
+		$securityResult = $securityManager->allows('RequestData', 'seeRestrictedComments', $currentUser);
44
+		$showAllComments = $securityResult === SecurityManager::ALLOWED;
45
+
46
+		$comments = Comment::getForRequest($requestId, $db, $showAllComments, $currentUser->getId());
47
+
48
+		$items = array_merge($logs, $comments);
49
+
50
+		/**
51
+		 * @param DataObject $item
52
+		 *
53
+		 * @return int
54
+		 */
55
+		$sortKey = function(DataObject $item) {
56
+			if ($item instanceof Log) {
57
+				return $item->getTimestamp()->getTimestamp();
58
+			}
59
+
60
+			if ($item instanceof Comment) {
61
+				return $item->getTime()->getTimestamp();
62
+			}
63
+
64
+			return 0;
65
+		};
66
+
67
+		do {
68
+			$flag = false;
69
+
70
+			$loopLimit = (count($items) - 1);
71
+			for ($i = 0; $i < $loopLimit; $i++) {
72
+				// are these two items out of order?
73
+				if ($sortKey($items[$i]) > $sortKey($items[$i + 1])) {
74
+					// swap them
75
+					$swap = $items[$i];
76
+					$items[$i] = $items[$i + 1];
77
+					$items[$i + 1] = $swap;
78
+
79
+					// set a flag to say we've modified the array this time around
80
+					$flag = true;
81
+				}
82
+			}
83
+		}
84
+		while ($flag);
85
+
86
+		return $items;
87
+	}
88
+
89
+	/**
90
+	 * Summary of getLogDescription
91
+	 *
92
+	 * @param Log $entry
93
+	 *
94
+	 * @return string
95
+	 */
96
+	public static function getLogDescription(Log $entry)
97
+	{
98
+		$text = "Deferred to ";
99
+		if (substr($entry->getAction(), 0, strlen($text)) == $text) {
100
+			// Deferred to a different queue
101
+			// This is exactly what we want to display.
102
+			return $entry->getAction();
103
+		}
104
+
105
+		$text = "Closed custom-n";
106
+		if ($entry->getAction() == $text) {
107
+			// Custom-closed
108
+			return "closed (custom reason - account not created)";
109
+		}
110
+
111
+		$text = "Closed custom-y";
112
+		if ($entry->getAction() == $text) {
113
+			// Custom-closed
114
+			return "closed (custom reason - account created)";
115
+		}
116
+
117
+		$text = "Closed 0";
118
+		if ($entry->getAction() == $text) {
119
+			// Dropped the request - short-circuit the lookup
120
+			return "dropped request";
121
+		}
122
+
123
+		$text = "Closed ";
124
+		if (substr($entry->getAction(), 0, strlen($text)) == $text) {
125
+			// Closed with a reason - do a lookup here.
126
+			$id = substr($entry->getAction(), strlen($text));
127
+			/** @var EmailTemplate $template */
128
+			$template = EmailTemplate::getById((int)$id, $entry->getDatabase());
129
+
130
+			if ($template != false) {
131
+				return "closed (" . $template->getName() . ")";
132
+			}
133
+		}
134
+
135
+		// Fall back to the basic stuff
136
+		$lookup = array(
137
+			'Reserved'        => 'reserved',
138
+			'Email Confirmed' => 'email-confirmed',
139
+			'Unreserved'      => 'unreserved',
140
+			'Approved'        => 'approved',
141
+			'Suspended'       => 'suspended',
142
+			'RoleChange'      => 'changed roles',
143
+			'Banned'          => 'banned',
144
+			'Edited'          => 'edited interface message',
145
+			'Declined'        => 'declined',
146
+			'EditComment-c'   => 'edited a comment',
147
+			'EditComment-r'   => 'edited a comment',
148
+			'Unbanned'        => 'unbanned',
149
+			'Promoted'        => 'promoted to tool admin',
150
+			'BreakReserve'    => 'forcibly broke the reservation',
151
+			'Prefchange'      => 'changed user preferences',
152
+			'Renamed'         => 'renamed',
153
+			'Demoted'         => 'demoted from tool admin',
154
+			'ReceiveReserved' => 'received the reservation',
155
+			'SendReserved'    => 'sent the reservation',
156
+			'EditedEmail'     => 'edited email',
157
+			'DeletedTemplate' => 'deleted template',
158
+			'EditedTemplate'  => 'edited template',
159
+			'CreatedEmail'    => 'created email',
160
+			'CreatedTemplate' => 'created template',
161
+			'SentMail'        => 'sent an email to the requestor',
162
+			'Registered'      => 'registered a tool account',
163
+		);
164
+
165
+		if (array_key_exists($entry->getAction(), $lookup)) {
166
+			return $lookup[$entry->getAction()];
167
+		}
168
+
169
+		// OK, I don't know what this is. Fall back to something sane.
170
+		return "performed an unknown action ({$entry->getAction()})";
171
+	}
172
+
173
+	/**
174
+	 * @param PdoDatabase $database
175
+	 *
176
+	 * @return array
177
+	 */
178
+	public static function getLogActions(PdoDatabase $database)
179
+	{
180
+		$lookup = array(
181
+			'Reserved'        => 'reserved',
182
+			'Email Confirmed' => 'email-confirmed',
183
+			'Unreserved'      => 'unreserved',
184
+			'Approved'        => 'approved',
185
+			'Suspended'       => 'suspended',
186
+			'RoleChange'      => 'changed roles',
187
+			'Banned'          => 'banned',
188
+			'Edited'          => 'edited interface message',
189
+			'Declined'        => 'declined',
190
+			'EditComment-c'   => 'edited a comment (by comment ID)',
191
+			'EditComment-r'   => 'edited a comment (by request)',
192
+			'Unbanned'        => 'unbanned',
193
+			'Promoted'        => 'promoted to tool admin',
194
+			'BreakReserve'    => 'forcibly broke the reservation',
195
+			'Prefchange'      => 'changed user preferences',
196
+			'Renamed'         => 'renamed',
197
+			'Demoted'         => 'demoted from tool admin',
198
+			'ReceiveReserved' => 'received the reservation',
199
+			'SendReserved'    => 'sent the reservation',
200
+			'EditedEmail'     => 'edited email',
201
+			'DeletedTemplate' => 'deleted template',
202
+			'EditedTemplate'  => 'edited template',
203
+			'CreatedEmail'    => 'created email',
204
+			'CreatedTemplate' => 'created template',
205
+			'SentMail'        => 'sent an email to the requestor',
206
+			'Registered'      => 'registered a tool account',
207
+			'Closed 0'        => 'dropped request',
208
+		);
209
+
210
+		$statement = $database->query(<<<SQL
211 211
 SELECT CONCAT('Closed ', id) AS k, CONCAT('closed (',name,')') AS v
212 212
 FROM emailtemplate;
213 213
 SQL
214
-        );
215
-        foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
216
-            $lookup[$row['k']] = $row['v'];
217
-        }
218
-
219
-        return $lookup;
220
-    }
221
-
222
-    public static function getObjectTypes()
223
-    {
224
-        return array(
225
-            'Ban'             => 'Ban',
226
-            'Comment'         => 'Comment',
227
-            'EmailTemplate'   => 'Email template',
228
-            'Request'         => 'Request',
229
-            'SiteNotice'      => 'Site notice',
230
-            'User'            => 'User',
231
-            'WelcomeTemplate' => 'Welcome template',
232
-        );
233
-    }
234
-
235
-    /**
236
-     * This returns a HTML
237
-     *
238
-     * @param string            $objectId
239
-     * @param string            $objectType
240
-     * @param PdoDatabase       $database
241
-     * @param SiteConfiguration $configuration
242
-     *
243
-     * @return null|string
244
-     * @category Security-Critical
245
-     */
246
-    private static function getObjectDescription(
247
-        $objectId,
248
-        $objectType,
249
-        PdoDatabase $database,
250
-        SiteConfiguration $configuration
251
-    ) {
252
-        if ($objectType == '') {
253
-            return null;
254
-        }
255
-
256
-        $baseurl = $configuration->getBaseUrl();
257
-
258
-        switch ($objectType) {
259
-            case 'Ban':
260
-                /** @var Ban $ban */
261
-                $ban = Ban::getById($objectId, $database);
262
-
263
-                if ($ban === false) {
264
-                    return 'Ban #' . $objectId . "</a>";
265
-                }
266
-
267
-                return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
268
-            case 'EmailTemplate':
269
-                /** @var EmailTemplate $emailTemplate */
270
-                $emailTemplate = EmailTemplate::getById($objectId, $database);
271
-                $name = htmlentities($emailTemplate->getName(), ENT_COMPAT, 'UTF-8');
272
-
273
-                return <<<HTML
214
+		);
215
+		foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
216
+			$lookup[$row['k']] = $row['v'];
217
+		}
218
+
219
+		return $lookup;
220
+	}
221
+
222
+	public static function getObjectTypes()
223
+	{
224
+		return array(
225
+			'Ban'             => 'Ban',
226
+			'Comment'         => 'Comment',
227
+			'EmailTemplate'   => 'Email template',
228
+			'Request'         => 'Request',
229
+			'SiteNotice'      => 'Site notice',
230
+			'User'            => 'User',
231
+			'WelcomeTemplate' => 'Welcome template',
232
+		);
233
+	}
234
+
235
+	/**
236
+	 * This returns a HTML
237
+	 *
238
+	 * @param string            $objectId
239
+	 * @param string            $objectType
240
+	 * @param PdoDatabase       $database
241
+	 * @param SiteConfiguration $configuration
242
+	 *
243
+	 * @return null|string
244
+	 * @category Security-Critical
245
+	 */
246
+	private static function getObjectDescription(
247
+		$objectId,
248
+		$objectType,
249
+		PdoDatabase $database,
250
+		SiteConfiguration $configuration
251
+	) {
252
+		if ($objectType == '') {
253
+			return null;
254
+		}
255
+
256
+		$baseurl = $configuration->getBaseUrl();
257
+
258
+		switch ($objectType) {
259
+			case 'Ban':
260
+				/** @var Ban $ban */
261
+				$ban = Ban::getById($objectId, $database);
262
+
263
+				if ($ban === false) {
264
+					return 'Ban #' . $objectId . "</a>";
265
+				}
266
+
267
+				return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
268
+			case 'EmailTemplate':
269
+				/** @var EmailTemplate $emailTemplate */
270
+				$emailTemplate = EmailTemplate::getById($objectId, $database);
271
+				$name = htmlentities($emailTemplate->getName(), ENT_COMPAT, 'UTF-8');
272
+
273
+				return <<<HTML
274 274
 <a href="{$baseurl}/internal.php/emailManagement/view?id={$objectId}">Email Template #{$objectId} ({$name})</a>
275 275
 HTML;
276
-            case 'SiteNotice':
277
-                return "<a href=\"{$baseurl}/internal.php/siteNotice\">the site notice</a>";
278
-            case 'Request':
279
-                /** @var Request $request */
280
-                $request = Request::getById($objectId, $database);
281
-                $name = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
282
-
283
-                return <<<HTML
276
+			case 'SiteNotice':
277
+				return "<a href=\"{$baseurl}/internal.php/siteNotice\">the site notice</a>";
278
+			case 'Request':
279
+				/** @var Request $request */
280
+				$request = Request::getById($objectId, $database);
281
+				$name = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
282
+
283
+				return <<<HTML
284 284
 <a href="{$baseurl}/internal.php/viewRequest?id={$objectId}">Request #{$objectId} ({$name})</a>
285 285
 HTML;
286
-            case 'User':
287
-                /** @var User $user */
288
-                $user = User::getById($objectId, $database);
289
-                $username = htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8');
290
-
291
-                return "<a href=\"{$baseurl}/internal.php/statistics/users/detail?user={$objectId}\">{$username}</a>";
292
-            case 'WelcomeTemplate':
293
-                /** @var WelcomeTemplate $welcomeTemplate */
294
-                $welcomeTemplate = WelcomeTemplate::getById($objectId, $database);
295
-
296
-                // some old templates have been completely deleted and lost to the depths of time.
297
-                if ($welcomeTemplate === false) {
298
-                    return "Welcome template #{$objectId}";
299
-                }
300
-                else {
301
-                    $userCode = htmlentities($welcomeTemplate->getUserCode(), ENT_COMPAT, 'UTF-8');
302
-
303
-                    return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
304
-                }
305
-            default:
306
-                return '[' . $objectType . " " . $objectId . ']';
307
-        }
308
-    }
309
-
310
-    /**
311
-     * @param    Log[]          $logs
312
-     * @param     PdoDatabase   $database
313
-     * @param SiteConfiguration $configuration
314
-     *
315
-     * @return array
316
-     * @throws Exception
317
-     */
318
-    public static function prepareLogsForTemplate($logs, PdoDatabase $database, SiteConfiguration $configuration)
319
-    {
320
-        $userIds = array();
321
-
322
-        /** @var Log $logEntry */
323
-        foreach ($logs as $logEntry) {
324
-            if (!$logEntry instanceof Log) {
325
-                // if this happens, we've done something wrong with passing back the log data.
326
-                throw new Exception('Log entry is not an instance of a Log, this should never happen.');
327
-            }
328
-
329
-            $user = $logEntry->getUser();
330
-            if ($user === -1) {
331
-                continue;
332
-            }
333
-
334
-            if (!array_search($user, $userIds)) {
335
-                $userIds[] = $user;
336
-            }
337
-        }
338
-
339
-        $users = UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username');
340
-        $users[-1] = User::getCommunity()->getUsername();
341
-
342
-        $logData = array();
343
-
344
-        /** @var Log $logEntry */
345
-        foreach ($logs as $logEntry) {
346
-            $objectDescription = self::getObjectDescription($logEntry->getObjectId(), $logEntry->getObjectType(),
347
-                $database, $configuration);
348
-
349
-            switch ($logEntry->getAction()) {
350
-                case 'Renamed':
351
-                    $renameData = unserialize($logEntry->getComment());
352
-                    $oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
353
-                    $newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
354
-                    $comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
355
-                    break;
356
-                case 'RoleChange':
357
-                    $roleChangeData = unserialize($logEntry->getComment());
358
-
359
-                    $removed = array();
360
-                    foreach ($roleChangeData['removed'] as $r) {
361
-                        $removed[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
362
-                    }
363
-
364
-                    $added = array();
365
-                    foreach ($roleChangeData['added'] as $r) {
366
-                        $added[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
367
-                    }
368
-
369
-                    $reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
370
-
371
-                    $roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
372
-                    $comment = $roleDelta . ' with comment: ' . $reason;
373
-                    break;
374
-                default:
375
-                    $comment = $logEntry->getComment();
376
-                    break;
377
-            }
378
-
379
-            $logData[] = array(
380
-                'timestamp'         => $logEntry->getTimestamp(),
381
-                'userid'            => $logEntry->getUser(),
382
-                'username'          => $users[$logEntry->getUser()],
383
-                'description'       => self::getLogDescription($logEntry),
384
-                'objectdescription' => $objectDescription,
385
-                'comment'           => $comment,
386
-            );
387
-        }
388
-
389
-        return array($users, $logData);
390
-    }
286
+			case 'User':
287
+				/** @var User $user */
288
+				$user = User::getById($objectId, $database);
289
+				$username = htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8');
290
+
291
+				return "<a href=\"{$baseurl}/internal.php/statistics/users/detail?user={$objectId}\">{$username}</a>";
292
+			case 'WelcomeTemplate':
293
+				/** @var WelcomeTemplate $welcomeTemplate */
294
+				$welcomeTemplate = WelcomeTemplate::getById($objectId, $database);
295
+
296
+				// some old templates have been completely deleted and lost to the depths of time.
297
+				if ($welcomeTemplate === false) {
298
+					return "Welcome template #{$objectId}";
299
+				}
300
+				else {
301
+					$userCode = htmlentities($welcomeTemplate->getUserCode(), ENT_COMPAT, 'UTF-8');
302
+
303
+					return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
304
+				}
305
+			default:
306
+				return '[' . $objectType . " " . $objectId . ']';
307
+		}
308
+	}
309
+
310
+	/**
311
+	 * @param    Log[]          $logs
312
+	 * @param     PdoDatabase   $database
313
+	 * @param SiteConfiguration $configuration
314
+	 *
315
+	 * @return array
316
+	 * @throws Exception
317
+	 */
318
+	public static function prepareLogsForTemplate($logs, PdoDatabase $database, SiteConfiguration $configuration)
319
+	{
320
+		$userIds = array();
321
+
322
+		/** @var Log $logEntry */
323
+		foreach ($logs as $logEntry) {
324
+			if (!$logEntry instanceof Log) {
325
+				// if this happens, we've done something wrong with passing back the log data.
326
+				throw new Exception('Log entry is not an instance of a Log, this should never happen.');
327
+			}
328
+
329
+			$user = $logEntry->getUser();
330
+			if ($user === -1) {
331
+				continue;
332
+			}
333
+
334
+			if (!array_search($user, $userIds)) {
335
+				$userIds[] = $user;
336
+			}
337
+		}
338
+
339
+		$users = UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username');
340
+		$users[-1] = User::getCommunity()->getUsername();
341
+
342
+		$logData = array();
343
+
344
+		/** @var Log $logEntry */
345
+		foreach ($logs as $logEntry) {
346
+			$objectDescription = self::getObjectDescription($logEntry->getObjectId(), $logEntry->getObjectType(),
347
+				$database, $configuration);
348
+
349
+			switch ($logEntry->getAction()) {
350
+				case 'Renamed':
351
+					$renameData = unserialize($logEntry->getComment());
352
+					$oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
353
+					$newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
354
+					$comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
355
+					break;
356
+				case 'RoleChange':
357
+					$roleChangeData = unserialize($logEntry->getComment());
358
+
359
+					$removed = array();
360
+					foreach ($roleChangeData['removed'] as $r) {
361
+						$removed[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
362
+					}
363
+
364
+					$added = array();
365
+					foreach ($roleChangeData['added'] as $r) {
366
+						$added[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
367
+					}
368
+
369
+					$reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
370
+
371
+					$roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
372
+					$comment = $roleDelta . ' with comment: ' . $reason;
373
+					break;
374
+				default:
375
+					$comment = $logEntry->getComment();
376
+					break;
377
+			}
378
+
379
+			$logData[] = array(
380
+				'timestamp'         => $logEntry->getTimestamp(),
381
+				'userid'            => $logEntry->getUser(),
382
+				'username'          => $users[$logEntry->getUser()],
383
+				'description'       => self::getLogDescription($logEntry),
384
+				'objectdescription' => $objectDescription,
385
+				'comment'           => $comment,
386
+			);
387
+		}
388
+
389
+		return array($users, $logData);
390
+	}
391 391
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
             $template = EmailTemplate::getById((int)$id, $entry->getDatabase());
129 129
 
130 130
             if ($template != false) {
131
-                return "closed (" . $template->getName() . ")";
131
+                return "closed (".$template->getName().")";
132 132
             }
133 133
         }
134 134
 
@@ -261,10 +261,10 @@  discard block
 block discarded – undo
261 261
                 $ban = Ban::getById($objectId, $database);
262 262
 
263 263
                 if ($ban === false) {
264
-                    return 'Ban #' . $objectId . "</a>";
264
+                    return 'Ban #'.$objectId."</a>";
265 265
                 }
266 266
 
267
-                return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
267
+                return 'Ban #'.$objectId." (".htmlentities($ban->getTarget()).")</a>";
268 268
             case 'EmailTemplate':
269 269
                 /** @var EmailTemplate $emailTemplate */
270 270
                 $emailTemplate = EmailTemplate::getById($objectId, $database);
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
                     return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
304 304
                 }
305 305
             default:
306
-                return '[' . $objectType . " " . $objectId . ']';
306
+                return '['.$objectType." ".$objectId.']';
307 307
         }
308 308
     }
309 309
 
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
                     $renameData = unserialize($logEntry->getComment());
352 352
                     $oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
353 353
                     $newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
354
-                    $comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
354
+                    $comment = 'Renamed \''.$oldName.'\' to \''.$newName.'\'.';
355 355
                     break;
356 356
                 case 'RoleChange':
357 357
                     $roleChangeData = unserialize($logEntry->getComment());
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 
369 369
                     $reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
370 370
 
371
-                    $roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
372
-                    $comment = $roleDelta . ' with comment: ' . $reason;
371
+                    $roleDelta = 'Removed ['.implode(', ', $removed).'], Added ['.implode(', ', $added).']';
372
+                    $comment = $roleDelta.' with comment: '.$reason;
373 373
                     break;
374 374
                 default:
375 375
                     $comment = $logEntry->getComment();
Please login to merge, or discard this patch.