Completed
Pull Request — rbac (#446)
by Dat
03:37
created
includes/Pages/Registration/PageRegisterOption.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -12,17 +12,17 @@
 block discarded – undo
12 12
 
13 13
 class PageRegisterOption extends InternalPageBase
14 14
 {
15
-    /**
16
-     * Main function for this page, when no specific actions are called.
17
-     * @return void
18
-     */
19
-    protected function main()
20
-    {
21
-        $this->setTemplate('registration/option.tpl');
22
-    }
15
+	/**
16
+	 * Main function for this page, when no specific actions are called.
17
+	 * @return void
18
+	 */
19
+	protected function main()
20
+	{
21
+		$this->setTemplate('registration/option.tpl');
22
+	}
23 23
 
24
-    protected function isProtectedPage()
25
-    {
26
-        return false;
27
-    }
24
+	protected function isProtectedPage()
25
+	{
26
+		return false;
27
+	}
28 28
 }
Please login to merge, or discard this patch.
includes/Pages/Registration/PageRegisterStandard.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -10,19 +10,19 @@
 block discarded – undo
10 10
 
11 11
 class PageRegisterStandard extends PageRegisterBase
12 12
 {
13
-    /**
14
-     * @return string
15
-     */
16
-    protected function getRegistrationTemplate()
17
-    {
18
-        return "registration/register.tpl";
19
-    }
13
+	/**
14
+	 * @return string
15
+	 */
16
+	protected function getRegistrationTemplate()
17
+	{
18
+		return "registration/register.tpl";
19
+	}
20 20
 
21
-    /**
22
-     * @return string
23
-     */
24
-    protected function getDefaultRole()
25
-    {
26
-        return 'user';
27
-    }
21
+	/**
22
+	 * @return string
23
+	 */
24
+	protected function getDefaultRole()
25
+	{
26
+		return 'user';
27
+	}
28 28
 }
Please login to merge, or discard this patch.
includes/Pages/PageSiteNotice.php 1 patch
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -15,37 +15,37 @@
 block discarded – undo
15 15
 
16 16
 class PageSiteNotice extends InternalPageBase
17 17
 {
18
-    /**
19
-     * Main function for this page, when no specific actions are called.
20
-     * @return void
21
-     */
22
-    protected function main()
23
-    {
24
-        $this->setHtmlTitle('Site Notice');
25
-
26
-        $database = $this->getDatabase();
27
-
28
-        /** @var SiteNotice $siteNoticeMessage */
29
-        $siteNoticeMessage = SiteNotice::getById(1, $database);
30
-
31
-        // Dual-mode
32
-        if (WebRequest::wasPosted()) {
33
-            $this->validateCSRFToken();
34
-
35
-            $siteNoticeMessage->setContent(WebRequest::postString('mailtext'));
36
-            $siteNoticeMessage->setUpdateVersion(WebRequest::postInt('updateversion'));
37
-            $siteNoticeMessage->save();
38
-
39
-            Logger::siteNoticeEdited($database, $siteNoticeMessage);
40
-            $this->getNotificationHelper()->siteNoticeEdited();
41
-
42
-            $this->redirect();
43
-        }
44
-        else {
45
-            $this->assignCSRFToken();
46
-
47
-            $this->setTemplate('site-notice/edit-form.tpl');
48
-            $this->assign('message', $siteNoticeMessage);
49
-        }
50
-    }
18
+	/**
19
+	 * Main function for this page, when no specific actions are called.
20
+	 * @return void
21
+	 */
22
+	protected function main()
23
+	{
24
+		$this->setHtmlTitle('Site Notice');
25
+
26
+		$database = $this->getDatabase();
27
+
28
+		/** @var SiteNotice $siteNoticeMessage */
29
+		$siteNoticeMessage = SiteNotice::getById(1, $database);
30
+
31
+		// Dual-mode
32
+		if (WebRequest::wasPosted()) {
33
+			$this->validateCSRFToken();
34
+
35
+			$siteNoticeMessage->setContent(WebRequest::postString('mailtext'));
36
+			$siteNoticeMessage->setUpdateVersion(WebRequest::postInt('updateversion'));
37
+			$siteNoticeMessage->save();
38
+
39
+			Logger::siteNoticeEdited($database, $siteNoticeMessage);
40
+			$this->getNotificationHelper()->siteNoticeEdited();
41
+
42
+			$this->redirect();
43
+		}
44
+		else {
45
+			$this->assignCSRFToken();
46
+
47
+			$this->setTemplate('site-notice/edit-form.tpl');
48
+			$this->assign('message', $siteNoticeMessage);
49
+		}
50
+	}
51 51
 }
Please login to merge, or discard this patch.
includes/Pages/PageLog.php 1 patch
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -18,113 +18,113 @@
 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
-
31
-        $database = $this->getDatabase();
32
-
33
-        $this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
34
-            return UserSearchHelper::get($database)->fetchColumn('username');
35
-        });
36
-
37
-        $limit = WebRequest::getInt('limit');
38
-        if ($limit === null) {
39
-            $limit = 100;
40
-        }
41
-
42
-        $page = WebRequest::getInt('page');
43
-        if ($page === null) {
44
-            $page = 1;
45
-        }
46
-
47
-        $offset = ($page - 1) * $limit;
48
-
49
-        $logSearch = LogSearchHelper::get($database)->limit($limit, $offset);
50
-        if ($filterUser !== null) {
51
-            $logSearch->byUser(User::getByUsername($filterUser, $database)->getId());
52
-        }
53
-
54
-        if ($filterAction !== null) {
55
-            $logSearch->byAction($filterAction);
56
-        }
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
-
78
-        $this->assign('allLogActions', LogHelper::getLogActions($this->getDatabase()));
79
-
80
-        $this->setTemplate("logs/main.tpl");
81
-    }
82
-
83
-    /**
84
-     * @param int $page
85
-     * @param int $limit
86
-     * @param int $count
87
-     */
88
-    protected function setupPageData($page, $limit, $count)
89
-    {
90
-        // The number of pages on the pager to show. Must be odd
91
-        $pageLimit = 9;
92
-
93
-        $pageData = array(
94
-            // Can the user go to the previous page?
95
-            'canprev'   => $page != 1,
96
-            // Can the user go to the next page?
97
-            'cannext'   => ($page * $limit) < $count,
98
-            // Maximum page number
99
-            'maxpage'   => ceil($count / $limit),
100
-            // Limit to the number of pages to display
101
-            'pagelimit' => $pageLimit,
102
-        );
103
-
104
-        // number of pages either side of the current to show
105
-        $pageMargin = (($pageLimit - 1) / 2);
106
-
107
-        // Calculate the number of pages either side to show - this is for situations like:
108
-        //  [1]  [2] [[3]] [4]  [5]  [6]  [7]  [8]  [9] - where you can't just use the page margin calculated
109
-        $pageData['lowpage'] = max(1, $page - $pageMargin);
110
-        $pageData['hipage'] = min($pageData['maxpage'], $page + $pageMargin);
111
-        $pageCount = ($pageData['hipage'] - $pageData['lowpage']) + 1;
112
-
113
-        if ($pageCount < $pageLimit) {
114
-            if ($pageData['lowpage'] == 1 && $pageData['hipage'] < $pageData['maxpage']) {
115
-                $pageData['hipage'] = min($pageLimit, $pageData['maxpage']);
116
-            }
117
-            elseif ($pageData['lowpage'] > 1 && $pageData['hipage'] == $pageData['maxpage']) {
118
-                $pageData['lowpage'] = max(1, $pageData['maxpage'] - $pageLimit + 1);
119
-            }
120
-        }
121
-
122
-        // Put the range of pages into the page data
123
-        $pageData['pages'] = range($pageData['lowpage'], $pageData['hipage']);
124
-
125
-        $this->assign("pagedata", $pageData);
126
-
127
-        $this->assign("limit", $limit);
128
-        $this->assign("page", $page);
129
-    }
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
+
31
+		$database = $this->getDatabase();
32
+
33
+		$this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
34
+			return UserSearchHelper::get($database)->fetchColumn('username');
35
+		});
36
+
37
+		$limit = WebRequest::getInt('limit');
38
+		if ($limit === null) {
39
+			$limit = 100;
40
+		}
41
+
42
+		$page = WebRequest::getInt('page');
43
+		if ($page === null) {
44
+			$page = 1;
45
+		}
46
+
47
+		$offset = ($page - 1) * $limit;
48
+
49
+		$logSearch = LogSearchHelper::get($database)->limit($limit, $offset);
50
+		if ($filterUser !== null) {
51
+			$logSearch->byUser(User::getByUsername($filterUser, $database)->getId());
52
+		}
53
+
54
+		if ($filterAction !== null) {
55
+			$logSearch->byAction($filterAction);
56
+		}
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
+
78
+		$this->assign('allLogActions', LogHelper::getLogActions($this->getDatabase()));
79
+
80
+		$this->setTemplate("logs/main.tpl");
81
+	}
82
+
83
+	/**
84
+	 * @param int $page
85
+	 * @param int $limit
86
+	 * @param int $count
87
+	 */
88
+	protected function setupPageData($page, $limit, $count)
89
+	{
90
+		// The number of pages on the pager to show. Must be odd
91
+		$pageLimit = 9;
92
+
93
+		$pageData = array(
94
+			// Can the user go to the previous page?
95
+			'canprev'   => $page != 1,
96
+			// Can the user go to the next page?
97
+			'cannext'   => ($page * $limit) < $count,
98
+			// Maximum page number
99
+			'maxpage'   => ceil($count / $limit),
100
+			// Limit to the number of pages to display
101
+			'pagelimit' => $pageLimit,
102
+		);
103
+
104
+		// number of pages either side of the current to show
105
+		$pageMargin = (($pageLimit - 1) / 2);
106
+
107
+		// Calculate the number of pages either side to show - this is for situations like:
108
+		//  [1]  [2] [[3]] [4]  [5]  [6]  [7]  [8]  [9] - where you can't just use the page margin calculated
109
+		$pageData['lowpage'] = max(1, $page - $pageMargin);
110
+		$pageData['hipage'] = min($pageData['maxpage'], $page + $pageMargin);
111
+		$pageCount = ($pageData['hipage'] - $pageData['lowpage']) + 1;
112
+
113
+		if ($pageCount < $pageLimit) {
114
+			if ($pageData['lowpage'] == 1 && $pageData['hipage'] < $pageData['maxpage']) {
115
+				$pageData['hipage'] = min($pageLimit, $pageData['maxpage']);
116
+			}
117
+			elseif ($pageData['lowpage'] > 1 && $pageData['hipage'] == $pageData['maxpage']) {
118
+				$pageData['lowpage'] = max(1, $pageData['maxpage'] - $pageLimit + 1);
119
+			}
120
+		}
121
+
122
+		// Put the range of pages into the page data
123
+		$pageData['pages'] = range($pageData['lowpage'], $pageData['hipage']);
124
+
125
+		$this->assign("pagedata", $pageData);
126
+
127
+		$this->assign("limit", $limit);
128
+		$this->assign("page", $page);
129
+	}
130 130
 }
Please login to merge, or discard this patch.
includes/Pages/Page404.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -12,20 +12,20 @@
 block discarded – undo
12 12
 
13 13
 class Page404 extends InternalPageBase
14 14
 {
15
-    /**
16
-     * Main function for this page, when no actions are called.
17
-     */
18
-    protected function main()
19
-    {
20
-        if (!headers_sent()) {
21
-            header("HTTP/1.1 404 Not Found");
22
-        }
15
+	/**
16
+	 * Main function for this page, when no actions are called.
17
+	 */
18
+	protected function main()
19
+	{
20
+		if (!headers_sent()) {
21
+			header("HTTP/1.1 404 Not Found");
22
+		}
23 23
 
24
-        $this->setTemplate("404.tpl");
25
-    }
24
+		$this->setTemplate("404.tpl");
25
+	}
26 26
 
27
-    protected function isProtectedPage()
28
-    {
29
-        return false;
30
-    }
27
+	protected function isProtectedPage()
28
+	{
29
+		return false;
30
+	}
31 31
 }
Please login to merge, or discard this patch.
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.