Completed
Pull Request — newinternal (#285)
by Simon
07:17 queued 04:17
created
includes/Pages/Statistics/StatsMain.php 1 patch
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -12,104 +12,104 @@
 block discarded – undo
12 12
 
13 13
 class StatsMain extends InternalPageBase
14 14
 {
15
-    public function main()
16
-    {
17
-        $this->setHtmlTitle('Statistics');
18
-
19
-        $this->assign('statsPageTitle', 'Account Creation Statistics');
20
-
21
-        $statsPages = array(
22
-            'fastCloses'       => 'Requests closed less than 30 seconds after reservation in the past 3 months',
23
-            'inactiveUsers'    => 'Inactive tool users',
24
-            'monthlyStats'     => 'Monthly Statistics',
25
-            'reservedRequests' => 'All currently reserved requests',
26
-            'templateStats'    => 'Template Stats',
27
-            'topCreators'      => 'Top Account Creators',
28
-            'users'            => 'Account Creation Tool users',
29
-        );
30
-
31
-        $this->generateSmallStatsTable();
32
-
33
-        $this->assign('statsPages', $statsPages);
34
-
35
-        $graphList = array('day', '2day', '4day', 'week', '2week', 'month', '3month');
36
-        $this->assign('graphList', $graphList);
37
-
38
-        $this->setTemplate('statistics/main.tpl');
39
-    }
40
-
41
-    /**
42
-     * Gets the relevant statistics from the database for the small statistics table
43
-     */
44
-    private function generateSmallStatsTable()
45
-    {
46
-        $database = $this->getDatabase();
47
-        $requestsQuery = <<<'SQL'
15
+	public function main()
16
+	{
17
+		$this->setHtmlTitle('Statistics');
18
+
19
+		$this->assign('statsPageTitle', 'Account Creation Statistics');
20
+
21
+		$statsPages = array(
22
+			'fastCloses'       => 'Requests closed less than 30 seconds after reservation in the past 3 months',
23
+			'inactiveUsers'    => 'Inactive tool users',
24
+			'monthlyStats'     => 'Monthly Statistics',
25
+			'reservedRequests' => 'All currently reserved requests',
26
+			'templateStats'    => 'Template Stats',
27
+			'topCreators'      => 'Top Account Creators',
28
+			'users'            => 'Account Creation Tool users',
29
+		);
30
+
31
+		$this->generateSmallStatsTable();
32
+
33
+		$this->assign('statsPages', $statsPages);
34
+
35
+		$graphList = array('day', '2day', '4day', 'week', '2week', 'month', '3month');
36
+		$this->assign('graphList', $graphList);
37
+
38
+		$this->setTemplate('statistics/main.tpl');
39
+	}
40
+
41
+	/**
42
+	 * Gets the relevant statistics from the database for the small statistics table
43
+	 */
44
+	private function generateSmallStatsTable()
45
+	{
46
+		$database = $this->getDatabase();
47
+		$requestsQuery = <<<'SQL'
48 48
 SELECT COUNT(*) FROM request WHERE status = :status AND emailconfirm = 'Confirmed';
49 49
 SQL;
50
-        $requestsStatement = $database->prepare($requestsQuery);
50
+		$requestsStatement = $database->prepare($requestsQuery);
51 51
 
52
-        $requestStates = $this->getSiteConfiguration()->getRequestStates();
52
+		$requestStates = $this->getSiteConfiguration()->getRequestStates();
53 53
 
54
-        $requestStateData = array();
54
+		$requestStateData = array();
55 55
 
56
-        foreach ($requestStates as $statusName => $data) {
57
-            $requestsStatement->execute(array(':status' => $statusName));
58
-            $requestCount = $requestsStatement->fetchColumn();
59
-            $requestsStatement->closeCursor();
60
-            $headerText = $data['header'];
61
-            $requestStateData[$headerText] = $requestCount;
62
-        }
56
+		foreach ($requestStates as $statusName => $data) {
57
+			$requestsStatement->execute(array(':status' => $statusName));
58
+			$requestCount = $requestsStatement->fetchColumn();
59
+			$requestsStatement->closeCursor();
60
+			$headerText = $data['header'];
61
+			$requestStateData[$headerText] = $requestCount;
62
+		}
63 63
 
64
-        $this->assign('requestCountData', $requestStateData);
64
+		$this->assign('requestCountData', $requestStateData);
65 65
 
66
-        // Unconfirmed requests
67
-        $unconfirmedStatement = $database->query(<<<SQL
66
+		// Unconfirmed requests
67
+		$unconfirmedStatement = $database->query(<<<SQL
68 68
 SELECT COUNT(*) FROM request WHERE emailconfirm != 'Confirmed' AND emailconfirm != '';
69 69
 SQL
70
-        );
71
-        $unconfirmed = $unconfirmedStatement->fetchColumn();
72
-        $unconfirmedStatement->closeCursor();
73
-        $this->assign('statsUnconfirmed', $unconfirmed);
74
-
75
-        $userStatusStatement = $database->prepare('SELECT COUNT(*) FROM user WHERE status = :status;');
76
-
77
-        // Admin users
78
-        $userStatusStatement->execute(array(':status' => 'Admin'));
79
-        $adminUsers = $userStatusStatement->fetchColumn();
80
-        $userStatusStatement->closeCursor();
81
-        $this->assign('statsAdminUsers', $adminUsers);
82
-
83
-        // Users
84
-        $userStatusStatement->execute(array(':status' => 'User'));
85
-        $users = $userStatusStatement->fetchColumn();
86
-        $userStatusStatement->closeCursor();
87
-        $this->assign('statsUsers', $users);
88
-
89
-        // Suspended users
90
-        $userStatusStatement->execute(array(':status' => 'Suspended'));
91
-        $suspendedUsers = $userStatusStatement->fetchColumn();
92
-        $userStatusStatement->closeCursor();
93
-        $this->assign('statsSuspendedUsers', $suspendedUsers);
94
-
95
-        // New users
96
-        $userStatusStatement->execute(array(':status' => 'New'));
97
-        $newUsers = $userStatusStatement->fetchColumn();
98
-        $userStatusStatement->closeCursor();
99
-        $this->assign('statsNewUsers', $newUsers);
100
-
101
-        // Most comments on a request
102
-        $mostCommentsStatement = $database->query(<<<SQL
70
+		);
71
+		$unconfirmed = $unconfirmedStatement->fetchColumn();
72
+		$unconfirmedStatement->closeCursor();
73
+		$this->assign('statsUnconfirmed', $unconfirmed);
74
+
75
+		$userStatusStatement = $database->prepare('SELECT COUNT(*) FROM user WHERE status = :status;');
76
+
77
+		// Admin users
78
+		$userStatusStatement->execute(array(':status' => 'Admin'));
79
+		$adminUsers = $userStatusStatement->fetchColumn();
80
+		$userStatusStatement->closeCursor();
81
+		$this->assign('statsAdminUsers', $adminUsers);
82
+
83
+		// Users
84
+		$userStatusStatement->execute(array(':status' => 'User'));
85
+		$users = $userStatusStatement->fetchColumn();
86
+		$userStatusStatement->closeCursor();
87
+		$this->assign('statsUsers', $users);
88
+
89
+		// Suspended users
90
+		$userStatusStatement->execute(array(':status' => 'Suspended'));
91
+		$suspendedUsers = $userStatusStatement->fetchColumn();
92
+		$userStatusStatement->closeCursor();
93
+		$this->assign('statsSuspendedUsers', $suspendedUsers);
94
+
95
+		// New users
96
+		$userStatusStatement->execute(array(':status' => 'New'));
97
+		$newUsers = $userStatusStatement->fetchColumn();
98
+		$userStatusStatement->closeCursor();
99
+		$this->assign('statsNewUsers', $newUsers);
100
+
101
+		// Most comments on a request
102
+		$mostCommentsStatement = $database->query(<<<SQL
103 103
 SELECT request FROM comment GROUP BY request ORDER BY COUNT(*) DESC LIMIT 1;
104 104
 SQL
105
-        );
106
-        $mostComments = $mostCommentsStatement->fetchColumn();
107
-        $mostCommentsStatement->closeCursor();
108
-        $this->assign('mostComments', $mostComments);
109
-    }
110
-
111
-    public function getSecurityConfiguration()
112
-    {
113
-        return $this->getSecurityManager()->configure()->asInternalPage();
114
-    }
105
+		);
106
+		$mostComments = $mostCommentsStatement->fetchColumn();
107
+		$mostCommentsStatement->closeCursor();
108
+		$this->assign('mostComments', $mostComments);
109
+	}
110
+
111
+	public function getSecurityConfiguration()
112
+	{
113
+		return $this->getSecurityManager()->configure()->asInternalPage();
114
+	}
115 115
 }
Please login to merge, or discard this patch.
includes/Pages/Statistics/StatsReservedRequests.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -13,11 +13,11 @@  discard block
 block discarded – undo
13 13
 
14 14
 class StatsReservedRequests extends InternalPageBase
15 15
 {
16
-    public function main()
17
-    {
18
-        $this->setHtmlTitle('Reserved Requests :: Statistics');
16
+	public function main()
17
+	{
18
+		$this->setHtmlTitle('Reserved Requests :: Statistics');
19 19
 
20
-        $query = <<<sql
20
+		$query = <<<sql
21 21
 SELECT
22 22
     p.id AS requestid,
23 23
     p.name AS name,
@@ -29,16 +29,16 @@  discard block
 block discarded – undo
29 29
 WHERE reserved != 0;
30 30
 sql;
31 31
 
32
-        $database = $this->getDatabase();
33
-        $statement = $database->query($query);
34
-        $data = $statement->fetchAll(PDO::FETCH_ASSOC);
35
-        $this->assign('dataTable', $data);
36
-        $this->assign('statsPageTitle', 'All currently reserved requests');
37
-        $this->setTemplate('statistics/reserved-requests.tpl');
38
-    }
32
+		$database = $this->getDatabase();
33
+		$statement = $database->query($query);
34
+		$data = $statement->fetchAll(PDO::FETCH_ASSOC);
35
+		$this->assign('dataTable', $data);
36
+		$this->assign('statsPageTitle', 'All currently reserved requests');
37
+		$this->setTemplate('statistics/reserved-requests.tpl');
38
+	}
39 39
 
40
-    public function getSecurityConfiguration()
41
-    {
42
-        return $this->getSecurityManager()->configure()->asInternalPage();
43
-    }
40
+	public function getSecurityConfiguration()
41
+	{
42
+		return $this->getSecurityManager()->configure()->asInternalPage();
43
+	}
44 44
 }
Please login to merge, or discard this patch.
includes/Pages/Statistics/StatsTemplateStats.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -13,11 +13,11 @@  discard block
 block discarded – undo
13 13
 
14 14
 class StatsTemplateStats extends InternalPageBase
15 15
 {
16
-    public function main()
17
-    {
18
-        $this->setHtmlTitle('Template Stats :: Statistics');
16
+	public function main()
17
+	{
18
+		$this->setHtmlTitle('Template Stats :: Statistics');
19 19
 
20
-        $query = <<<SQL
20
+		$query = <<<SQL
21 21
 SELECT
22 22
     t.id AS templateid,
23 23
     t.usercode AS usercode,
@@ -45,16 +45,16 @@  discard block
 block discarded – undo
45 45
         GROUP BY welcome_template
46 46
     ) u2 ON u2.allid = t.id;
47 47
 SQL;
48
-        $database = $this->getDatabase();
49
-        $statement = $database->query($query);
50
-        $data = $statement->fetchAll(PDO::FETCH_ASSOC);
51
-        $this->assign('dataTable', $data);
52
-        $this->assign('statsPageTitle', 'Template Stats');
53
-        $this->setTemplate('statistics/welcome-template-usage.tpl');
54
-    }
48
+		$database = $this->getDatabase();
49
+		$statement = $database->query($query);
50
+		$data = $statement->fetchAll(PDO::FETCH_ASSOC);
51
+		$this->assign('dataTable', $data);
52
+		$this->assign('statsPageTitle', 'Template Stats');
53
+		$this->setTemplate('statistics/welcome-template-usage.tpl');
54
+	}
55 55
 
56
-    public function getSecurityConfiguration()
57
-    {
58
-        return $this->getSecurityManager()->configure()->asInternalPage();
59
-    }
56
+	public function getSecurityConfiguration()
57
+	{
58
+		return $this->getSecurityManager()->configure()->asInternalPage();
59
+	}
60 60
 }
Please login to merge, or discard this patch.
includes/Pages/PagePreferences.php 1 patch
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -17,113 +17,113 @@
 block discarded – undo
17 17
 
18 18
 class PagePreferences extends InternalPageBase
19 19
 {
20
-    /**
21
-     * Main function for this page, when no specific actions are called.
22
-     * @return void
23
-     */
24
-    protected function main()
25
-    {
26
-        $this->setHtmlTitle('Preferences');
27
-
28
-        $enforceOAuth = $this->getSiteConfiguration()->getEnforceOAuth();
29
-
30
-        // Dual mode
31
-        if (WebRequest::wasPosted()) {
32
-            $this->validateCSRFToken();
33
-            $user = User::getCurrent($this->getDatabase());
34
-            $user->setWelcomeSig(WebRequest::postString('sig'));
35
-            $user->setEmailSig(WebRequest::postString('emailsig'));
36
-            $user->setAbortPref(WebRequest::getBoolean('sig') ? 1 : 0);
37
-
38
-            $email = WebRequest::postEmail('email');
39
-            if ($email !== null) {
40
-                $user->setEmail($email);
41
-            }
42
-
43
-            $user->save();
44
-            SessionAlert::success("Preferences updated!");
45
-
46
-            $this->redirect('');
47
-        }
48
-        else {
49
-            $this->assignCSRFToken();
50
-            $this->setTemplate('preferences/prefs.tpl');
51
-            $this->assign("enforceOAuth", $enforceOAuth);
52
-        }
53
-    }
54
-
55
-    protected function changePassword()
56
-    {
57
-        $this->setHtmlTitle('Change Password');
58
-
59
-        if (WebRequest::wasPosted()) {
60
-            $this->validateCSRFToken();
61
-            try {
62
-                $oldPassword = WebRequest::postString('oldpassword');
63
-                $newPassword = WebRequest::postString('newpassword');
64
-                $newPasswordConfirmation = WebRequest::postString('newpasswordconfirm');
65
-
66
-                $user = User::getCurrent($this->getDatabase());
67
-                if (!$user instanceof User) {
68
-                    throw new ApplicationLogicException('User not found');
69
-                }
70
-
71
-                $this->validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, $user);
72
-            }
73
-            catch (ApplicationLogicException $ex) {
74
-                SessionAlert::error($ex->getMessage());
75
-                $this->redirect('preferences', 'changePassword');
76
-
77
-                return;
78
-            }
79
-
80
-            $user->setPassword($newPassword);
81
-            $user->save();
82
-
83
-            SessionAlert::success('Password changed successfully!');
84
-
85
-            $this->redirect('preferences');
86
-        }
87
-        else {
88
-            // not allowed to GET this.
89
-            $this->redirect('preferences');
90
-        }
91
-    }
92
-
93
-    /**
94
-     * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
95
-     * the return value from this function.
96
-     *
97
-     * If this page even supports actions, you will need to check the route
98
-     *
99
-     * @return SecurityConfiguration
100
-     * @category Security-Critical
101
-     */
102
-    protected function getSecurityConfiguration()
103
-    {
104
-        return $this->getSecurityManager()->configure()->asInternalPage();
105
-    }
106
-
107
-    /**
108
-     * @param string $oldPassword
109
-     * @param string $newPassword
110
-     * @param string $newPasswordConfirmation
111
-     * @param User   $user
112
-     *
113
-     * @throws ApplicationLogicException
114
-     */
115
-    protected function validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, User $user)
116
-    {
117
-        if ($oldPassword === null || $newPassword === null || $newPasswordConfirmation === null) {
118
-            throw new ApplicationLogicException('All three fields must be completed to change your password');
119
-        }
120
-
121
-        if ($newPassword !== $newPasswordConfirmation) {
122
-            throw new ApplicationLogicException('Your new passwords did not match!');
123
-        }
124
-
125
-        if (!$user->authenticate($oldPassword)) {
126
-            throw new ApplicationLogicException('The password you entered was incorrect.');
127
-        }
128
-    }
20
+	/**
21
+	 * Main function for this page, when no specific actions are called.
22
+	 * @return void
23
+	 */
24
+	protected function main()
25
+	{
26
+		$this->setHtmlTitle('Preferences');
27
+
28
+		$enforceOAuth = $this->getSiteConfiguration()->getEnforceOAuth();
29
+
30
+		// Dual mode
31
+		if (WebRequest::wasPosted()) {
32
+			$this->validateCSRFToken();
33
+			$user = User::getCurrent($this->getDatabase());
34
+			$user->setWelcomeSig(WebRequest::postString('sig'));
35
+			$user->setEmailSig(WebRequest::postString('emailsig'));
36
+			$user->setAbortPref(WebRequest::getBoolean('sig') ? 1 : 0);
37
+
38
+			$email = WebRequest::postEmail('email');
39
+			if ($email !== null) {
40
+				$user->setEmail($email);
41
+			}
42
+
43
+			$user->save();
44
+			SessionAlert::success("Preferences updated!");
45
+
46
+			$this->redirect('');
47
+		}
48
+		else {
49
+			$this->assignCSRFToken();
50
+			$this->setTemplate('preferences/prefs.tpl');
51
+			$this->assign("enforceOAuth", $enforceOAuth);
52
+		}
53
+	}
54
+
55
+	protected function changePassword()
56
+	{
57
+		$this->setHtmlTitle('Change Password');
58
+
59
+		if (WebRequest::wasPosted()) {
60
+			$this->validateCSRFToken();
61
+			try {
62
+				$oldPassword = WebRequest::postString('oldpassword');
63
+				$newPassword = WebRequest::postString('newpassword');
64
+				$newPasswordConfirmation = WebRequest::postString('newpasswordconfirm');
65
+
66
+				$user = User::getCurrent($this->getDatabase());
67
+				if (!$user instanceof User) {
68
+					throw new ApplicationLogicException('User not found');
69
+				}
70
+
71
+				$this->validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, $user);
72
+			}
73
+			catch (ApplicationLogicException $ex) {
74
+				SessionAlert::error($ex->getMessage());
75
+				$this->redirect('preferences', 'changePassword');
76
+
77
+				return;
78
+			}
79
+
80
+			$user->setPassword($newPassword);
81
+			$user->save();
82
+
83
+			SessionAlert::success('Password changed successfully!');
84
+
85
+			$this->redirect('preferences');
86
+		}
87
+		else {
88
+			// not allowed to GET this.
89
+			$this->redirect('preferences');
90
+		}
91
+	}
92
+
93
+	/**
94
+	 * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
95
+	 * the return value from this function.
96
+	 *
97
+	 * If this page even supports actions, you will need to check the route
98
+	 *
99
+	 * @return SecurityConfiguration
100
+	 * @category Security-Critical
101
+	 */
102
+	protected function getSecurityConfiguration()
103
+	{
104
+		return $this->getSecurityManager()->configure()->asInternalPage();
105
+	}
106
+
107
+	/**
108
+	 * @param string $oldPassword
109
+	 * @param string $newPassword
110
+	 * @param string $newPasswordConfirmation
111
+	 * @param User   $user
112
+	 *
113
+	 * @throws ApplicationLogicException
114
+	 */
115
+	protected function validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, User $user)
116
+	{
117
+		if ($oldPassword === null || $newPassword === null || $newPasswordConfirmation === null) {
118
+			throw new ApplicationLogicException('All three fields must be completed to change your password');
119
+		}
120
+
121
+		if ($newPassword !== $newPasswordConfirmation) {
122
+			throw new ApplicationLogicException('Your new passwords did not match!');
123
+		}
124
+
125
+		if (!$user->authenticate($oldPassword)) {
126
+			throw new ApplicationLogicException('The password you entered was incorrect.');
127
+		}
128
+	}
129 129
 }
130 130
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/PageBan.php 1 patch
Indentation   +322 added lines, -322 removed lines patch added patch discarded remove patch
@@ -21,326 +21,326 @@
 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 = User::getUsernames($userIds, $this->getDatabase());
41
-
42
-        $this->assign('usernames', $userList);
43
-        $this->assign('activebans', $bans);
44
-        $this->setTemplate('bans/banlist.tpl');
45
-    }
46
-
47
-    /**
48
-     * Entry point for the ban set action
49
-     */
50
-    protected function set()
51
-    {
52
-        $this->setHtmlTitle('Bans');
53
-
54
-        // dual-mode action
55
-        if (WebRequest::wasPosted()) {
56
-            try {
57
-                $this->handlePostMethodForSetBan();
58
-            }
59
-            catch (ApplicationLogicException $ex) {
60
-                SessionAlert::error($ex->getMessage());
61
-                $this->redirect("bans", "set");
62
-            }
63
-        }
64
-        else {
65
-            $this->handleGetMethodForSetBan();
66
-        }
67
-    }
68
-
69
-    /**
70
-     * Entry point for the ban remove action
71
-     */
72
-    protected function remove()
73
-    {
74
-        $this->setHtmlTitle('Bans');
75
-
76
-        $ban = $this->getBanForUnban();
77
-
78
-        // dual mode
79
-        if (WebRequest::wasPosted()) {
80
-            $this->validateCSRFToken();
81
-            $unbanReason = WebRequest::postString('unbanreason');
82
-
83
-            if ($unbanReason === null || trim($unbanReason) === "") {
84
-                SessionAlert::error('No unban reason specified');
85
-                $this->redirect("bans", "remove", array('id' => $ban->getId()));
86
-            }
87
-
88
-            // set optimistic locking from delete form page load
89
-            $updateVersion = WebRequest::postInt('updateversion');
90
-            $ban->setUpdateVersion($updateVersion);
91
-
92
-            $database = $this->getDatabase();
93
-            $ban->setActive(false);
94
-            $ban->save();
95
-
96
-            Logger::unbanned($database, $ban, $unbanReason);
97
-
98
-            SessionAlert::quick('Disabled ban.');
99
-            $this->getNotificationHelper()->unbanned($ban, $unbanReason);
100
-
101
-            $this->redirect('bans');
102
-        }
103
-        else {
104
-            $this->assignCSRFToken();
105
-            $this->assign('ban', $ban);
106
-            $this->setTemplate('bans/unban.tpl');
107
-        }
108
-    }
109
-
110
-    /**
111
-     * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
112
-     * the return value from this function.
113
-     *
114
-     * If this page even supports actions, you will need to check the route
115
-     *
116
-     * @return SecurityConfiguration
117
-     * @category Security-Critical
118
-     */
119
-    protected function getSecurityConfiguration()
120
-    {
121
-        // display of bans is allowed for any user, but setting and removing bans is admin-only.
122
-        switch ($this->getRouteName()) {
123
-            case "main":
124
-                return $this->getSecurityManager()->configure()->asInternalPage();
125
-            default:
126
-                return $this->getSecurityManager()->configure()->asAdminPage();
127
-        }
128
-    }
129
-
130
-    /**
131
-     * @throws ApplicationLogicException
132
-     */
133
-    private function getBanDuration()
134
-    {
135
-        $duration = WebRequest::postString('duration');
136
-        if ($duration === "other") {
137
-            $duration = strtotime(WebRequest::postString('otherduration'));
138
-
139
-            if (!$duration) {
140
-                throw new ApplicationLogicException('Invalid ban time');
141
-            }
142
-            elseif (time() > $duration) {
143
-                throw new ApplicationLogicException('Ban time has already expired!');
144
-            }
145
-
146
-            return $duration;
147
-        }
148
-        elseif ($duration === "-1") {
149
-            $duration = -1;
150
-
151
-            return $duration;
152
-        }
153
-        else {
154
-            $duration = WebRequest::postInt('duration') + time();
155
-
156
-            return $duration;
157
-        }
158
-    }
159
-
160
-    /**
161
-     * @param string $type
162
-     * @param string $target
163
-     *
164
-     * @throws ApplicationLogicException
165
-     */
166
-    private function validateBanType($type, $target)
167
-    {
168
-        switch ($type) {
169
-            case 'IP':
170
-                $this->validateIpBan($target);
171
-
172
-                return;
173
-            case 'Name':
174
-                // No validation needed here.
175
-                return;
176
-            case 'EMail':
177
-                $this->validateEmailBanTarget($target);
178
-
179
-                return;
180
-            default:
181
-                throw new ApplicationLogicException("Unknown ban type");
182
-        }
183
-    }
184
-
185
-    /**
186
-     * Handles the POST method on the set action
187
-     *
188
-     * @throws ApplicationLogicException
189
-     * @throws Exception
190
-     */
191
-    private function handlePostMethodForSetBan()
192
-    {
193
-        $this->validateCSRFToken();
194
-        $reason = WebRequest::postString('banreason');
195
-        $target = WebRequest::postString('target');
196
-
197
-        // Checks whether there is a reason entered for ban.
198
-        if ($reason === null || trim($reason) === "") {
199
-            throw new ApplicationLogicException('You must specify a ban reason');
200
-        }
201
-
202
-        // Checks whether there is a target entered to ban.
203
-        if ($target === null || trim($target) === "") {
204
-            throw new ApplicationLogicException('You must specify a target to be banned');
205
-        }
206
-
207
-        // Validate ban duration
208
-        $duration = $this->getBanDuration();
209
-
210
-        // Validate ban type & target for that type
211
-        $type = WebRequest::postString('type');
212
-        $this->validateBanType($type, $target);
213
-
214
-        $database = $this->getDatabase();
215
-
216
-        if (count(Ban::getActiveBans($target, $database)) > 0) {
217
-            throw new ApplicationLogicException('This target is already banned!');
218
-        }
219
-
220
-        $ban = new Ban();
221
-        $ban->setDatabase($database);
222
-        $ban->setActive(true);
223
-        $ban->setType($type);
224
-        $ban->setTarget($target);
225
-        $ban->setUser(User::getCurrent($database)->getId());
226
-        $ban->setReason($reason);
227
-        $ban->setDuration($duration);
228
-
229
-        $ban->save();
230
-
231
-        Logger::banned($database, $ban, $reason);
232
-
233
-        $this->getNotificationHelper()->banned($ban);
234
-        SessionAlert::quick('Ban has been set.');
235
-
236
-        $this->redirect('bans');
237
-    }
238
-
239
-    /**
240
-     * Handles the GET method on the set action
241
-     */
242
-    protected function handleGetMethodForSetBan()
243
-    {
244
-        $this->setTemplate('bans/banform.tpl');
245
-        $this->assignCSRFToken();
246
-
247
-        $banType = WebRequest::getString('type');
248
-        $banTarget = WebRequest::getInt('request');
249
-
250
-        $database = $this->getDatabase();
251
-
252
-        // if the parameters are null, skip loading a request.
253
-        if ($banType === null
254
-            || !in_array($banType, array('IP', 'Name', 'EMail'))
255
-            || $banTarget === null
256
-            || $banTarget === 0
257
-        ) {
258
-            $this->assign('bantarget', '');
259
-            $this->assign('bantype', '');
260
-
261
-            return;
262
-        }
263
-
264
-        // Set the ban type, which the user has indicated.
265
-        $this->assign('bantype', $banType);
266
-
267
-        // Attempt to resolve the correct target
268
-        /** @var Request $request */
269
-        $request = Request::getById($banTarget, $database);
270
-        if ($request === false) {
271
-            $this->assign('bantarget', '');
272
-
273
-            return;
274
-        }
275
-
276
-        $realTarget = '';
277
-        switch ($banType) {
278
-            case 'EMail':
279
-                $realTarget = $request->getEmail();
280
-                break;
281
-            case 'IP':
282
-                $xffProvider = $this->getXffTrustProvider();
283
-                $realTarget = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
284
-                break;
285
-            case 'Name':
286
-                $realTarget = $request->getName();
287
-                break;
288
-        }
289
-
290
-        $this->assign('bantarget', $realTarget);
291
-    }
292
-
293
-    /**
294
-     * Validates an IP ban target
295
-     *
296
-     * @param string $target
297
-     *
298
-     * @throws ApplicationLogicException
299
-     */
300
-    private function validateIpBan($target)
301
-    {
302
-        $squidIpList = $this->getSiteConfiguration()->getSquidList();
303
-
304
-        if (filter_var($target, FILTER_VALIDATE_IP) === false) {
305
-            throw new ApplicationLogicException('Invalid target - IP address expected.');
306
-        }
307
-
308
-        if (in_array($target, $squidIpList)) {
309
-            throw new ApplicationLogicException("This IP address is on the protected list of proxies, and cannot be banned.");
310
-        }
311
-    }
312
-
313
-    /**
314
-     * Validates an email address as a ban target
315
-     *
316
-     * @param string $target
317
-     *
318
-     * @throws ApplicationLogicException
319
-     */
320
-    private function validateEmailBanTarget($target)
321
-    {
322
-        if (filter_var($target, FILTER_VALIDATE_EMAIL) !== $target) {
323
-            throw new ApplicationLogicException('Invalid target - email address expected.');
324
-        }
325
-    }
326
-
327
-    /**
328
-     * @return Ban
329
-     * @throws ApplicationLogicException
330
-     */
331
-    private function getBanForUnban()
332
-    {
333
-        $banId = WebRequest::getInt('id');
334
-        if ($banId === null || $banId === 0) {
335
-            throw new ApplicationLogicException("The ban ID appears to be missing. This is probably a bug.");
336
-        }
337
-
338
-        $ban = Ban::getActiveId($banId, $this->getDatabase());
339
-
340
-        if ($ban === false) {
341
-            throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
342
-        }
343
-
344
-        return $ban;
345
-    }
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 = User::getUsernames($userIds, $this->getDatabase());
41
+
42
+		$this->assign('usernames', $userList);
43
+		$this->assign('activebans', $bans);
44
+		$this->setTemplate('bans/banlist.tpl');
45
+	}
46
+
47
+	/**
48
+	 * Entry point for the ban set action
49
+	 */
50
+	protected function set()
51
+	{
52
+		$this->setHtmlTitle('Bans');
53
+
54
+		// dual-mode action
55
+		if (WebRequest::wasPosted()) {
56
+			try {
57
+				$this->handlePostMethodForSetBan();
58
+			}
59
+			catch (ApplicationLogicException $ex) {
60
+				SessionAlert::error($ex->getMessage());
61
+				$this->redirect("bans", "set");
62
+			}
63
+		}
64
+		else {
65
+			$this->handleGetMethodForSetBan();
66
+		}
67
+	}
68
+
69
+	/**
70
+	 * Entry point for the ban remove action
71
+	 */
72
+	protected function remove()
73
+	{
74
+		$this->setHtmlTitle('Bans');
75
+
76
+		$ban = $this->getBanForUnban();
77
+
78
+		// dual mode
79
+		if (WebRequest::wasPosted()) {
80
+			$this->validateCSRFToken();
81
+			$unbanReason = WebRequest::postString('unbanreason');
82
+
83
+			if ($unbanReason === null || trim($unbanReason) === "") {
84
+				SessionAlert::error('No unban reason specified');
85
+				$this->redirect("bans", "remove", array('id' => $ban->getId()));
86
+			}
87
+
88
+			// set optimistic locking from delete form page load
89
+			$updateVersion = WebRequest::postInt('updateversion');
90
+			$ban->setUpdateVersion($updateVersion);
91
+
92
+			$database = $this->getDatabase();
93
+			$ban->setActive(false);
94
+			$ban->save();
95
+
96
+			Logger::unbanned($database, $ban, $unbanReason);
97
+
98
+			SessionAlert::quick('Disabled ban.');
99
+			$this->getNotificationHelper()->unbanned($ban, $unbanReason);
100
+
101
+			$this->redirect('bans');
102
+		}
103
+		else {
104
+			$this->assignCSRFToken();
105
+			$this->assign('ban', $ban);
106
+			$this->setTemplate('bans/unban.tpl');
107
+		}
108
+	}
109
+
110
+	/**
111
+	 * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
112
+	 * the return value from this function.
113
+	 *
114
+	 * If this page even supports actions, you will need to check the route
115
+	 *
116
+	 * @return SecurityConfiguration
117
+	 * @category Security-Critical
118
+	 */
119
+	protected function getSecurityConfiguration()
120
+	{
121
+		// display of bans is allowed for any user, but setting and removing bans is admin-only.
122
+		switch ($this->getRouteName()) {
123
+			case "main":
124
+				return $this->getSecurityManager()->configure()->asInternalPage();
125
+			default:
126
+				return $this->getSecurityManager()->configure()->asAdminPage();
127
+		}
128
+	}
129
+
130
+	/**
131
+	 * @throws ApplicationLogicException
132
+	 */
133
+	private function getBanDuration()
134
+	{
135
+		$duration = WebRequest::postString('duration');
136
+		if ($duration === "other") {
137
+			$duration = strtotime(WebRequest::postString('otherduration'));
138
+
139
+			if (!$duration) {
140
+				throw new ApplicationLogicException('Invalid ban time');
141
+			}
142
+			elseif (time() > $duration) {
143
+				throw new ApplicationLogicException('Ban time has already expired!');
144
+			}
145
+
146
+			return $duration;
147
+		}
148
+		elseif ($duration === "-1") {
149
+			$duration = -1;
150
+
151
+			return $duration;
152
+		}
153
+		else {
154
+			$duration = WebRequest::postInt('duration') + time();
155
+
156
+			return $duration;
157
+		}
158
+	}
159
+
160
+	/**
161
+	 * @param string $type
162
+	 * @param string $target
163
+	 *
164
+	 * @throws ApplicationLogicException
165
+	 */
166
+	private function validateBanType($type, $target)
167
+	{
168
+		switch ($type) {
169
+			case 'IP':
170
+				$this->validateIpBan($target);
171
+
172
+				return;
173
+			case 'Name':
174
+				// No validation needed here.
175
+				return;
176
+			case 'EMail':
177
+				$this->validateEmailBanTarget($target);
178
+
179
+				return;
180
+			default:
181
+				throw new ApplicationLogicException("Unknown ban type");
182
+		}
183
+	}
184
+
185
+	/**
186
+	 * Handles the POST method on the set action
187
+	 *
188
+	 * @throws ApplicationLogicException
189
+	 * @throws Exception
190
+	 */
191
+	private function handlePostMethodForSetBan()
192
+	{
193
+		$this->validateCSRFToken();
194
+		$reason = WebRequest::postString('banreason');
195
+		$target = WebRequest::postString('target');
196
+
197
+		// Checks whether there is a reason entered for ban.
198
+		if ($reason === null || trim($reason) === "") {
199
+			throw new ApplicationLogicException('You must specify a ban reason');
200
+		}
201
+
202
+		// Checks whether there is a target entered to ban.
203
+		if ($target === null || trim($target) === "") {
204
+			throw new ApplicationLogicException('You must specify a target to be banned');
205
+		}
206
+
207
+		// Validate ban duration
208
+		$duration = $this->getBanDuration();
209
+
210
+		// Validate ban type & target for that type
211
+		$type = WebRequest::postString('type');
212
+		$this->validateBanType($type, $target);
213
+
214
+		$database = $this->getDatabase();
215
+
216
+		if (count(Ban::getActiveBans($target, $database)) > 0) {
217
+			throw new ApplicationLogicException('This target is already banned!');
218
+		}
219
+
220
+		$ban = new Ban();
221
+		$ban->setDatabase($database);
222
+		$ban->setActive(true);
223
+		$ban->setType($type);
224
+		$ban->setTarget($target);
225
+		$ban->setUser(User::getCurrent($database)->getId());
226
+		$ban->setReason($reason);
227
+		$ban->setDuration($duration);
228
+
229
+		$ban->save();
230
+
231
+		Logger::banned($database, $ban, $reason);
232
+
233
+		$this->getNotificationHelper()->banned($ban);
234
+		SessionAlert::quick('Ban has been set.');
235
+
236
+		$this->redirect('bans');
237
+	}
238
+
239
+	/**
240
+	 * Handles the GET method on the set action
241
+	 */
242
+	protected function handleGetMethodForSetBan()
243
+	{
244
+		$this->setTemplate('bans/banform.tpl');
245
+		$this->assignCSRFToken();
246
+
247
+		$banType = WebRequest::getString('type');
248
+		$banTarget = WebRequest::getInt('request');
249
+
250
+		$database = $this->getDatabase();
251
+
252
+		// if the parameters are null, skip loading a request.
253
+		if ($banType === null
254
+			|| !in_array($banType, array('IP', 'Name', 'EMail'))
255
+			|| $banTarget === null
256
+			|| $banTarget === 0
257
+		) {
258
+			$this->assign('bantarget', '');
259
+			$this->assign('bantype', '');
260
+
261
+			return;
262
+		}
263
+
264
+		// Set the ban type, which the user has indicated.
265
+		$this->assign('bantype', $banType);
266
+
267
+		// Attempt to resolve the correct target
268
+		/** @var Request $request */
269
+		$request = Request::getById($banTarget, $database);
270
+		if ($request === false) {
271
+			$this->assign('bantarget', '');
272
+
273
+			return;
274
+		}
275
+
276
+		$realTarget = '';
277
+		switch ($banType) {
278
+			case 'EMail':
279
+				$realTarget = $request->getEmail();
280
+				break;
281
+			case 'IP':
282
+				$xffProvider = $this->getXffTrustProvider();
283
+				$realTarget = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
284
+				break;
285
+			case 'Name':
286
+				$realTarget = $request->getName();
287
+				break;
288
+		}
289
+
290
+		$this->assign('bantarget', $realTarget);
291
+	}
292
+
293
+	/**
294
+	 * Validates an IP ban target
295
+	 *
296
+	 * @param string $target
297
+	 *
298
+	 * @throws ApplicationLogicException
299
+	 */
300
+	private function validateIpBan($target)
301
+	{
302
+		$squidIpList = $this->getSiteConfiguration()->getSquidList();
303
+
304
+		if (filter_var($target, FILTER_VALIDATE_IP) === false) {
305
+			throw new ApplicationLogicException('Invalid target - IP address expected.');
306
+		}
307
+
308
+		if (in_array($target, $squidIpList)) {
309
+			throw new ApplicationLogicException("This IP address is on the protected list of proxies, and cannot be banned.");
310
+		}
311
+	}
312
+
313
+	/**
314
+	 * Validates an email address as a ban target
315
+	 *
316
+	 * @param string $target
317
+	 *
318
+	 * @throws ApplicationLogicException
319
+	 */
320
+	private function validateEmailBanTarget($target)
321
+	{
322
+		if (filter_var($target, FILTER_VALIDATE_EMAIL) !== $target) {
323
+			throw new ApplicationLogicException('Invalid target - email address expected.');
324
+		}
325
+	}
326
+
327
+	/**
328
+	 * @return Ban
329
+	 * @throws ApplicationLogicException
330
+	 */
331
+	private function getBanForUnban()
332
+	{
333
+		$banId = WebRequest::getInt('id');
334
+		if ($banId === null || $banId === 0) {
335
+			throw new ApplicationLogicException("The ban ID appears to be missing. This is probably a bug.");
336
+		}
337
+
338
+		$ban = Ban::getActiveId($banId, $this->getDatabase());
339
+
340
+		if ($ban === false) {
341
+			throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
342
+		}
343
+
344
+		return $ban;
345
+	}
346 346
 }
347 347
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/PageLogin.php 2 patches
Indentation   +143 added lines, -143 removed lines patch added patch discarded remove patch
@@ -21,147 +21,147 @@
 block discarded – undo
21 21
  */
22 22
 class PageLogin extends InternalPageBase
23 23
 {
24
-    /**
25
-     * Main function for this page, when no specific actions are called.
26
-     */
27
-    protected function main()
28
-    {
29
-        // Start by enforcing HTTPS
30
-        if ($this->getSiteConfiguration()->getUseStrictTransportSecurity() !== false) {
31
-            if (WebRequest::isHttps()) {
32
-                // Client can clearly use HTTPS, so let's enforce it for all connections.
33
-                if (!headers_sent()) {
34
-                    header("Strict-Transport-Security: max-age=15768000");
35
-                }
36
-            }
37
-            else {
38
-                // This is the login form, not the request form. We need protection here.
39
-                $this->redirectUrl('https://' . WebRequest::serverName() . WebRequest::requestUri());
40
-
41
-                return;
42
-            }
43
-        }
44
-
45
-        if (WebRequest::wasPosted()) {
46
-            // POST. Do some authentication.
47
-            $this->validateCSRFToken();
48
-
49
-            $user = null;
50
-            try {
51
-                $user = $this->getAuthenticatingUser();
52
-            }
53
-            catch (ApplicationLogicException $ex) {
54
-                SessionAlert::error($ex->getMessage());
55
-                $this->redirect('login');
56
-
57
-                return;
58
-            }
59
-
60
-            // Touch force logout
61
-            $user->setForceLogout(false);
62
-            $user->save();
63
-
64
-            if ($this->getSiteConfiguration()->getEnforceOAuth()) {
65
-                if (!$user->isOAuthLinked()) {
66
-                    $oauthHelper = $this->getOAuthHelper();
67
-
68
-                    $requestToken = $oauthHelper->getRequestToken();
69
-                    $user->setOAuthRequestToken($requestToken->key);
70
-                    $user->setOAuthRequestSecret($requestToken->secret);
71
-                    $user->save();
72
-
73
-                    WebRequest::setPartialLogin($user);
74
-                    $this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
75
-
76
-                    return;
77
-                }
78
-            }
79
-
80
-            // User is partially linked to OAuth. This is not allowed. Enforce it for this user.
81
-            if ($user->getOnWikiName() === '##OAUTH##') {
82
-                $oauthHelper = $this->getOAuthHelper();
83
-
84
-                $requestToken = $oauthHelper->getRequestToken();
85
-                $user->setOAuthRequestToken($requestToken->key);
86
-                $user->setOAuthRequestSecret($requestToken->secret);
87
-                $user->save();
88
-
89
-                WebRequest::setPartialLogin($user);
90
-                $this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
91
-
92
-                return;
93
-            }
94
-
95
-            WebRequest::setLoggedInUser($user);
96
-
97
-            $this->goBackWhenceYouCame($user);
98
-        }
99
-        else {
100
-            // GET. Show the form
101
-            $this->assignCSRFToken();
102
-            $this->setTemplate("login.tpl");
103
-        }
104
-    }
105
-
106
-    /**
107
-     * @return User
108
-     * @throws ApplicationLogicException
109
-     */
110
-    private function getAuthenticatingUser()
111
-    {
112
-        $username = WebRequest::postString("username");
113
-        $password = WebRequest::postString("password");
114
-
115
-        if ($username === null || $password === null || $username === "" || $password === "") {
116
-            throw new ApplicationLogicException("No username/password specified");
117
-        }
118
-
119
-        /** @var User $user */
120
-        $user = User::getByUsername($username, $this->getDatabase());
121
-
122
-        if ($user == false || !$user->authenticate($password)) {
123
-            throw new ApplicationLogicException("Authentication failed");
124
-        }
125
-
126
-        return $user;
127
-    }
128
-
129
-    /**
130
-     * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
131
-     * the return value from this function.
132
-     *
133
-     * If this page even supports actions, you will need to check the route
134
-     *
135
-     * @return SecurityConfiguration
136
-     * @category Security-Critical
137
-     */
138
-    protected function getSecurityConfiguration()
139
-    {
140
-        // Login pages, by definition, have to be accessible to the public
141
-        return $this->getSecurityManager()->configure()->asPublicPage();
142
-    }
143
-
144
-    /**
145
-     * Redirect the user back to wherever they came from after a successful login
146
-     *
147
-     * @param User $user
148
-     */
149
-    private function goBackWhenceYouCame(User $user)
150
-    {
151
-        // Redirect to wherever the user came from
152
-        $redirectDestination = WebRequest::clearPostLoginRedirect();
153
-        if ($redirectDestination !== null) {
154
-            $this->redirectUrl($redirectDestination);
155
-        }
156
-        else {
157
-            if ($user->isNewUser()) {
158
-                // home page isn't allowed, go to preferences instead
159
-                $this->redirect('preferences');
160
-            }
161
-            else {
162
-                // go to the home page
163
-                $this->redirect('');
164
-            }
165
-        }
166
-    }
24
+	/**
25
+	 * Main function for this page, when no specific actions are called.
26
+	 */
27
+	protected function main()
28
+	{
29
+		// Start by enforcing HTTPS
30
+		if ($this->getSiteConfiguration()->getUseStrictTransportSecurity() !== false) {
31
+			if (WebRequest::isHttps()) {
32
+				// Client can clearly use HTTPS, so let's enforce it for all connections.
33
+				if (!headers_sent()) {
34
+					header("Strict-Transport-Security: max-age=15768000");
35
+				}
36
+			}
37
+			else {
38
+				// This is the login form, not the request form. We need protection here.
39
+				$this->redirectUrl('https://' . WebRequest::serverName() . WebRequest::requestUri());
40
+
41
+				return;
42
+			}
43
+		}
44
+
45
+		if (WebRequest::wasPosted()) {
46
+			// POST. Do some authentication.
47
+			$this->validateCSRFToken();
48
+
49
+			$user = null;
50
+			try {
51
+				$user = $this->getAuthenticatingUser();
52
+			}
53
+			catch (ApplicationLogicException $ex) {
54
+				SessionAlert::error($ex->getMessage());
55
+				$this->redirect('login');
56
+
57
+				return;
58
+			}
59
+
60
+			// Touch force logout
61
+			$user->setForceLogout(false);
62
+			$user->save();
63
+
64
+			if ($this->getSiteConfiguration()->getEnforceOAuth()) {
65
+				if (!$user->isOAuthLinked()) {
66
+					$oauthHelper = $this->getOAuthHelper();
67
+
68
+					$requestToken = $oauthHelper->getRequestToken();
69
+					$user->setOAuthRequestToken($requestToken->key);
70
+					$user->setOAuthRequestSecret($requestToken->secret);
71
+					$user->save();
72
+
73
+					WebRequest::setPartialLogin($user);
74
+					$this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
75
+
76
+					return;
77
+				}
78
+			}
79
+
80
+			// User is partially linked to OAuth. This is not allowed. Enforce it for this user.
81
+			if ($user->getOnWikiName() === '##OAUTH##') {
82
+				$oauthHelper = $this->getOAuthHelper();
83
+
84
+				$requestToken = $oauthHelper->getRequestToken();
85
+				$user->setOAuthRequestToken($requestToken->key);
86
+				$user->setOAuthRequestSecret($requestToken->secret);
87
+				$user->save();
88
+
89
+				WebRequest::setPartialLogin($user);
90
+				$this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
91
+
92
+				return;
93
+			}
94
+
95
+			WebRequest::setLoggedInUser($user);
96
+
97
+			$this->goBackWhenceYouCame($user);
98
+		}
99
+		else {
100
+			// GET. Show the form
101
+			$this->assignCSRFToken();
102
+			$this->setTemplate("login.tpl");
103
+		}
104
+	}
105
+
106
+	/**
107
+	 * @return User
108
+	 * @throws ApplicationLogicException
109
+	 */
110
+	private function getAuthenticatingUser()
111
+	{
112
+		$username = WebRequest::postString("username");
113
+		$password = WebRequest::postString("password");
114
+
115
+		if ($username === null || $password === null || $username === "" || $password === "") {
116
+			throw new ApplicationLogicException("No username/password specified");
117
+		}
118
+
119
+		/** @var User $user */
120
+		$user = User::getByUsername($username, $this->getDatabase());
121
+
122
+		if ($user == false || !$user->authenticate($password)) {
123
+			throw new ApplicationLogicException("Authentication failed");
124
+		}
125
+
126
+		return $user;
127
+	}
128
+
129
+	/**
130
+	 * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
131
+	 * the return value from this function.
132
+	 *
133
+	 * If this page even supports actions, you will need to check the route
134
+	 *
135
+	 * @return SecurityConfiguration
136
+	 * @category Security-Critical
137
+	 */
138
+	protected function getSecurityConfiguration()
139
+	{
140
+		// Login pages, by definition, have to be accessible to the public
141
+		return $this->getSecurityManager()->configure()->asPublicPage();
142
+	}
143
+
144
+	/**
145
+	 * Redirect the user back to wherever they came from after a successful login
146
+	 *
147
+	 * @param User $user
148
+	 */
149
+	private function goBackWhenceYouCame(User $user)
150
+	{
151
+		// Redirect to wherever the user came from
152
+		$redirectDestination = WebRequest::clearPostLoginRedirect();
153
+		if ($redirectDestination !== null) {
154
+			$this->redirectUrl($redirectDestination);
155
+		}
156
+		else {
157
+			if ($user->isNewUser()) {
158
+				// home page isn't allowed, go to preferences instead
159
+				$this->redirect('preferences');
160
+			}
161
+			else {
162
+				// go to the home page
163
+				$this->redirect('');
164
+			}
165
+		}
166
+	}
167 167
 }
168 168
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@
 block discarded – undo
36 36
             }
37 37
             else {
38 38
                 // This is the login form, not the request form. We need protection here.
39
-                $this->redirectUrl('https://' . WebRequest::serverName() . WebRequest::requestUri());
39
+                $this->redirectUrl('https://'.WebRequest::serverName().WebRequest::requestUri());
40 40
 
41 41
                 return;
42 42
             }
Please login to merge, or discard this patch.
includes/Pages/PageRegister.php 1 patch
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -18,196 +18,196 @@
 block discarded – undo
18 18
 
19 19
 class PageRegister extends InternalPageBase
20 20
 {
21
-    /**
22
-     * Main function for this page, when no specific actions are called.
23
-     */
24
-    protected function main()
25
-    {
26
-        $useOAuthSignup = $this->getSiteConfiguration()->getUseOAuthSignup();
27
-
28
-        // Dual-mode page
29
-        if (WebRequest::wasPosted()) {
30
-            $this->validateCSRFToken();
31
-
32
-            try {
33
-                $this->handlePost($useOAuthSignup);
34
-            }
35
-            catch (ApplicationLogicException $ex) {
36
-                SessionAlert::error($ex->getMessage());
37
-                $this->redirect('register');
38
-            }
39
-        }
40
-        else {
41
-            $this->assignCSRFToken();
42
-            $this->assign("useOAuthSignup", $useOAuthSignup);
43
-            $this->setTemplate("registration/register.tpl");
44
-        }
45
-    }
46
-
47
-    /**
48
-     * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
49
-     * the return value from this function.
50
-     *
51
-     * If this page even supports actions, you will need to check the route
52
-     *
53
-     * @return SecurityConfiguration
54
-     * @category Security-Critical
55
-     */
56
-    protected function getSecurityConfiguration()
57
-    {
58
-        return $this->getSecurityManager()->configure()->asPublicPage();
59
-    }
60
-
61
-    /**
62
-     * Entry point for registration complete
63
-     */
64
-    protected function done()
65
-    {
66
-        $this->setTemplate('registration/alert-registrationcomplete.tpl');
67
-    }
68
-
69
-    /**
70
-     * @param string $emailAddress
71
-     *
72
-     * @throws ApplicationLogicException
73
-     */
74
-    private function validateUniqueEmail($emailAddress)
75
-    {
76
-        $query = 'SELECT COUNT(id) FROM user WHERE email = :email';
77
-        $statement = $this->getDatabase()->prepare($query);
78
-        $statement->execute(array(':email' => $emailAddress));
79
-
80
-        if ($statement->fetchColumn() > 0) {
81
-            throw new ApplicationLogicException('That email address is already in use on this system.');
82
-        }
83
-
84
-        $statement->closeCursor();
85
-    }
86
-
87
-    /**
88
-     * @param $emailAddress
89
-     * @param $password
90
-     * @param $username
91
-     * @param $useOAuthSignup
92
-     * @param $confirmationId
93
-     * @param $onwikiUsername
94
-     *
95
-     * @throws ApplicationLogicException
96
-     */
97
-    private function validateRequest(
98
-        $emailAddress,
99
-        $password,
100
-        $username,
101
-        $useOAuthSignup,
102
-        $confirmationId,
103
-        $onwikiUsername
104
-    ) {
105
-        if (!WebRequest::postBoolean('guidelines')) {
106
-            throw new ApplicationLogicException('You must read the interface guidelines before your request may be submitted.');
107
-        }
108
-
109
-        $this->validateGeneralInformation($emailAddress, $password, $username);
110
-        $this->validateUniqueEmail($emailAddress);
111
-        $this->validateNonOAuthFields($useOAuthSignup, $confirmationId, $onwikiUsername);
112
-    }
113
-
114
-    /**
115
-     * @param $useOAuthSignup
116
-     *
117
-     * @throws ApplicationLogicException
118
-     * @throws \Exception
119
-     */
120
-    protected function handlePost($useOAuthSignup)
121
-    {
122
-        // Get the data
123
-        $emailAddress = WebRequest::postEmail('email');
124
-        $password = WebRequest::postString('pass');
125
-        $username = WebRequest::postString('name');
126
-
127
-        // Only set if OAuth is disabled
128
-        $confirmationId = WebRequest::postInt('conf_revid');
129
-        $onwikiUsername = WebRequest::postString('wname');
130
-
131
-        // Do some validation
132
-        $this->validateRequest($emailAddress, $password, $username, $useOAuthSignup, $confirmationId,
133
-            $onwikiUsername);
134
-
135
-        $user = new User();
136
-        $user->setDatabase($this->getDatabase());
137
-
138
-        $user->setUsername($username);
139
-        $user->setPassword($password);
140
-        $user->setEmail($emailAddress);
141
-
142
-        if (!$useOAuthSignup) {
143
-            $user->setOnWikiName($onwikiUsername);
144
-            $user->setConfirmationDiff($confirmationId);
145
-        }
146
-
147
-        $user->save();
148
-
149
-        // Log now to get the signup date.
150
-        Logger::newUser($this->getDatabase(), $user);
151
-
152
-        if ($useOAuthSignup) {
153
-            $oauthHelper = $this->getOAuthHelper();
154
-
155
-            $requestToken = $oauthHelper->getRequestToken();
156
-            $user->setOAuthRequestToken($requestToken->key);
157
-            $user->setOAuthRequestSecret($requestToken->secret);
158
-            $user->save();
159
-
160
-            WebRequest::setPartialLogin($user);
161
-
162
-            $this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
163
-        }
164
-        else {
165
-            // only notify if we're not using the oauth signup.
166
-            $this->getNotificationHelper()->userNew($user);
167
-            WebRequest::setLoggedInUser($user);
168
-            $this->redirect('preferences');
169
-        }
170
-    }
171
-
172
-    /**
173
-     * @param $useOAuthSignup
174
-     * @param $confirmationId
175
-     * @param $onwikiUsername
176
-     *
177
-     * @throws ApplicationLogicException
178
-     */
179
-    private function validateNonOAuthFields($useOAuthSignup, $confirmationId, $onwikiUsername)
180
-    {
181
-        if (!$useOAuthSignup) {
182
-            if ($confirmationId === null || $confirmationId <= 0) {
183
-                throw new ApplicationLogicException('Please enter the revision id of your confirmation edit.');
184
-            }
185
-
186
-            if ($onwikiUsername === null) {
187
-                throw new ApplicationLogicException('Please specify your on-wiki username.');
188
-            }
189
-        }
190
-    }
191
-
192
-    /**
193
-     * @param $emailAddress
194
-     * @param $password
195
-     * @param $username
196
-     *
197
-     * @throws ApplicationLogicException
198
-     */
199
-    private function validateGeneralInformation($emailAddress, $password, $username)
200
-    {
201
-        if ($emailAddress === null) {
202
-            throw new ApplicationLogicException('Your email address appears to be invalid!');
203
-        }
204
-
205
-        if ($password !== WebRequest::postString('pass2')) {
206
-            throw new ApplicationLogicException('Your passwords did not match, please try again.');
207
-        }
208
-
209
-        if (User::getByUsername($username, $this->getDatabase()) !== false) {
210
-            throw new ApplicationLogicException('That username is already in use on this system.');
211
-        }
212
-    }
21
+	/**
22
+	 * Main function for this page, when no specific actions are called.
23
+	 */
24
+	protected function main()
25
+	{
26
+		$useOAuthSignup = $this->getSiteConfiguration()->getUseOAuthSignup();
27
+
28
+		// Dual-mode page
29
+		if (WebRequest::wasPosted()) {
30
+			$this->validateCSRFToken();
31
+
32
+			try {
33
+				$this->handlePost($useOAuthSignup);
34
+			}
35
+			catch (ApplicationLogicException $ex) {
36
+				SessionAlert::error($ex->getMessage());
37
+				$this->redirect('register');
38
+			}
39
+		}
40
+		else {
41
+			$this->assignCSRFToken();
42
+			$this->assign("useOAuthSignup", $useOAuthSignup);
43
+			$this->setTemplate("registration/register.tpl");
44
+		}
45
+	}
46
+
47
+	/**
48
+	 * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
49
+	 * the return value from this function.
50
+	 *
51
+	 * If this page even supports actions, you will need to check the route
52
+	 *
53
+	 * @return SecurityConfiguration
54
+	 * @category Security-Critical
55
+	 */
56
+	protected function getSecurityConfiguration()
57
+	{
58
+		return $this->getSecurityManager()->configure()->asPublicPage();
59
+	}
60
+
61
+	/**
62
+	 * Entry point for registration complete
63
+	 */
64
+	protected function done()
65
+	{
66
+		$this->setTemplate('registration/alert-registrationcomplete.tpl');
67
+	}
68
+
69
+	/**
70
+	 * @param string $emailAddress
71
+	 *
72
+	 * @throws ApplicationLogicException
73
+	 */
74
+	private function validateUniqueEmail($emailAddress)
75
+	{
76
+		$query = 'SELECT COUNT(id) FROM user WHERE email = :email';
77
+		$statement = $this->getDatabase()->prepare($query);
78
+		$statement->execute(array(':email' => $emailAddress));
79
+
80
+		if ($statement->fetchColumn() > 0) {
81
+			throw new ApplicationLogicException('That email address is already in use on this system.');
82
+		}
83
+
84
+		$statement->closeCursor();
85
+	}
86
+
87
+	/**
88
+	 * @param $emailAddress
89
+	 * @param $password
90
+	 * @param $username
91
+	 * @param $useOAuthSignup
92
+	 * @param $confirmationId
93
+	 * @param $onwikiUsername
94
+	 *
95
+	 * @throws ApplicationLogicException
96
+	 */
97
+	private function validateRequest(
98
+		$emailAddress,
99
+		$password,
100
+		$username,
101
+		$useOAuthSignup,
102
+		$confirmationId,
103
+		$onwikiUsername
104
+	) {
105
+		if (!WebRequest::postBoolean('guidelines')) {
106
+			throw new ApplicationLogicException('You must read the interface guidelines before your request may be submitted.');
107
+		}
108
+
109
+		$this->validateGeneralInformation($emailAddress, $password, $username);
110
+		$this->validateUniqueEmail($emailAddress);
111
+		$this->validateNonOAuthFields($useOAuthSignup, $confirmationId, $onwikiUsername);
112
+	}
113
+
114
+	/**
115
+	 * @param $useOAuthSignup
116
+	 *
117
+	 * @throws ApplicationLogicException
118
+	 * @throws \Exception
119
+	 */
120
+	protected function handlePost($useOAuthSignup)
121
+	{
122
+		// Get the data
123
+		$emailAddress = WebRequest::postEmail('email');
124
+		$password = WebRequest::postString('pass');
125
+		$username = WebRequest::postString('name');
126
+
127
+		// Only set if OAuth is disabled
128
+		$confirmationId = WebRequest::postInt('conf_revid');
129
+		$onwikiUsername = WebRequest::postString('wname');
130
+
131
+		// Do some validation
132
+		$this->validateRequest($emailAddress, $password, $username, $useOAuthSignup, $confirmationId,
133
+			$onwikiUsername);
134
+
135
+		$user = new User();
136
+		$user->setDatabase($this->getDatabase());
137
+
138
+		$user->setUsername($username);
139
+		$user->setPassword($password);
140
+		$user->setEmail($emailAddress);
141
+
142
+		if (!$useOAuthSignup) {
143
+			$user->setOnWikiName($onwikiUsername);
144
+			$user->setConfirmationDiff($confirmationId);
145
+		}
146
+
147
+		$user->save();
148
+
149
+		// Log now to get the signup date.
150
+		Logger::newUser($this->getDatabase(), $user);
151
+
152
+		if ($useOAuthSignup) {
153
+			$oauthHelper = $this->getOAuthHelper();
154
+
155
+			$requestToken = $oauthHelper->getRequestToken();
156
+			$user->setOAuthRequestToken($requestToken->key);
157
+			$user->setOAuthRequestSecret($requestToken->secret);
158
+			$user->save();
159
+
160
+			WebRequest::setPartialLogin($user);
161
+
162
+			$this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
163
+		}
164
+		else {
165
+			// only notify if we're not using the oauth signup.
166
+			$this->getNotificationHelper()->userNew($user);
167
+			WebRequest::setLoggedInUser($user);
168
+			$this->redirect('preferences');
169
+		}
170
+	}
171
+
172
+	/**
173
+	 * @param $useOAuthSignup
174
+	 * @param $confirmationId
175
+	 * @param $onwikiUsername
176
+	 *
177
+	 * @throws ApplicationLogicException
178
+	 */
179
+	private function validateNonOAuthFields($useOAuthSignup, $confirmationId, $onwikiUsername)
180
+	{
181
+		if (!$useOAuthSignup) {
182
+			if ($confirmationId === null || $confirmationId <= 0) {
183
+				throw new ApplicationLogicException('Please enter the revision id of your confirmation edit.');
184
+			}
185
+
186
+			if ($onwikiUsername === null) {
187
+				throw new ApplicationLogicException('Please specify your on-wiki username.');
188
+			}
189
+		}
190
+	}
191
+
192
+	/**
193
+	 * @param $emailAddress
194
+	 * @param $password
195
+	 * @param $username
196
+	 *
197
+	 * @throws ApplicationLogicException
198
+	 */
199
+	private function validateGeneralInformation($emailAddress, $password, $username)
200
+	{
201
+		if ($emailAddress === null) {
202
+			throw new ApplicationLogicException('Your email address appears to be invalid!');
203
+		}
204
+
205
+		if ($password !== WebRequest::postString('pass2')) {
206
+			throw new ApplicationLogicException('Your passwords did not match, please try again.');
207
+		}
208
+
209
+		if (User::getByUsername($username, $this->getDatabase()) !== false) {
210
+			throw new ApplicationLogicException('That username is already in use on this system.');
211
+		}
212
+	}
213 213
 }
214 214
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/PageLogout.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -14,26 +14,26 @@
 block discarded – undo
14 14
 
15 15
 class PageLogout extends InternalPageBase
16 16
 {
17
-    /**
18
-     * Main function for this page, when no specific actions are called.
19
-     */
20
-    protected function main()
21
-    {
22
-        Session::destroy();
23
-        $this->redirect("login");
24
-    }
17
+	/**
18
+	 * Main function for this page, when no specific actions are called.
19
+	 */
20
+	protected function main()
21
+	{
22
+		Session::destroy();
23
+		$this->redirect("login");
24
+	}
25 25
 
26
-    /**
27
-     * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
28
-     * the return value from this function.
29
-     *
30
-     * If this page even supports actions, you will need to check the route
31
-     *
32
-     * @return SecurityConfiguration
33
-     * @category Security-Critical
34
-     */
35
-    protected function getSecurityConfiguration()
36
-    {
37
-        return $this->getSecurityManager()->configure()->asPublicPage();
38
-    }
26
+	/**
27
+	 * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
28
+	 * the return value from this function.
29
+	 *
30
+	 * If this page even supports actions, you will need to check the route
31
+	 *
32
+	 * @return SecurityConfiguration
33
+	 * @category Security-Critical
34
+	 */
35
+	protected function getSecurityConfiguration()
36
+	{
37
+		return $this->getSecurityManager()->configure()->asPublicPage();
38
+	}
39 39
 }
40 40
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/PageEmailManagement.php 1 patch
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -18,195 +18,195 @@
 block discarded – undo
18 18
 
19 19
 class PageEmailManagement extends InternalPageBase
20 20
 {
21
-    /**
22
-     * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
23
-     * the return value from this function.
24
-     *
25
-     * If this page even supports actions, you will need to check the route
26
-     *
27
-     * @return \Waca\Security\SecurityConfiguration
28
-     * @category Security-Critical
29
-     */
30
-    protected function getSecurityConfiguration()
31
-    {
32
-        switch ($this->getRouteName()) {
33
-            case 'edit':
34
-            case 'create':
35
-                return $this->getSecurityManager()->configure()->asAdminPage();
36
-            case 'view':
37
-            case 'main':
38
-                return $this->getSecurityManager()->configure()->asInternalPage();
39
-        }
40
-
41
-        // deny all
42
-        return $this->getSecurityManager()->configure()->asNone();
43
-    }
44
-
45
-    /**
46
-     * Main function for this page, when no specific actions are called.
47
-     * @return void
48
-     */
49
-    protected function main()
50
-    {
51
-        $this->setHtmlTitle('Close Emails');
52
-
53
-        // Get all active email templates
54
-        $activeTemplates = EmailTemplate::getAllActiveTemplates(null, $this->getDatabase());
55
-        $inactiveTemplates = EmailTemplate::getAllInactiveTemplates($this->getDatabase());
56
-
57
-        $this->assign('activeTemplates', $activeTemplates);
58
-        $this->assign('inactiveTemplates', $inactiveTemplates);
59
-
60
-        $this->setTemplate('email-management/main.tpl');
61
-    }
62
-
63
-    protected function view()
64
-    {
65
-        $this->setHtmlTitle('Close Emails');
66
-
67
-        $database = $this->getDatabase();
68
-        $template = $this->getTemplate($database);
69
-
70
-        $createdId = $this->getSiteConfiguration()->getDefaultCreatedTemplateId();
71
-        $requestStates = $this->getSiteConfiguration()->getRequestStates();
72
-
73
-        $this->assign('id', $template->getId());
74
-        $this->assign('emailTemplate', $template);
75
-        $this->assign('createdid', $createdId);
76
-        $this->assign('requeststates', $requestStates);
77
-
78
-        $this->setTemplate('email-management/view.tpl');
79
-    }
80
-
81
-    /**
82
-     * @param PdoDatabase $database
83
-     *
84
-     * @return EmailTemplate
85
-     * @throws ApplicationLogicException
86
-     */
87
-    protected function getTemplate(PdoDatabase $database)
88
-    {
89
-        $templateId = WebRequest::getInt('id');
90
-        if ($templateId === null) {
91
-            throw new ApplicationLogicException('Template not specified');
92
-        }
93
-        $template = EmailTemplate::getById($templateId, $database);
94
-        if ($template === false || !is_a($template, EmailTemplate::class)) {
95
-            throw new ApplicationLogicException('Template not found');
96
-        }
97
-
98
-        return $template;
99
-    }
100
-
101
-    protected function edit()
102
-    {
103
-        $this->setHtmlTitle('Close Emails');
104
-
105
-        $database = $this->getDatabase();
106
-        $template = $this->getTemplate($database);
107
-
108
-        $createdId = $this->getSiteConfiguration()->getDefaultCreatedTemplateId();
109
-        $requestStates = $this->getSiteConfiguration()->getRequestStates();
110
-
111
-        if (WebRequest::wasPosted()) {
112
-            $this->validateCSRFToken();
113
-
114
-            $this->modifyTemplateData($template);
115
-
116
-            $other = EmailTemplate::getByName($template->getName(), $database);
117
-            if ($other !== false && $other->getId() !== $template->getId()) {
118
-                throw new ApplicationLogicException('A template with this name already exists');
119
-            }
120
-
121
-            if ($template->getId() === $createdId) {
122
-                $template->setDefaultAction(EmailTemplate::CREATED);
123
-                $template->setActive(true);
124
-                $template->setPreloadOnly(false);
125
-            }
126
-
127
-            // optimistically lock on load of edit form
128
-            $updateVersion = WebRequest::postInt('updateversion');
129
-            $template->setUpdateVersion($updateVersion);
130
-
131
-            $template->save();
132
-            Logger::editedEmail($database, $template);
133
-            $this->getNotificationHelper()->emailEdited($template);
134
-            SessionAlert::success("Email template has been saved successfully.");
135
-
136
-            $this->redirect('emailManagement');
137
-        }
138
-        else {
139
-            $this->assignCSRFToken();
140
-            $this->assign('id', $template->getId());
141
-            $this->assign('emailTemplate', $template);
142
-            $this->assign('createdid', $createdId);
143
-            $this->assign('requeststates', $requestStates);
144
-
145
-            $this->setTemplate('email-management/edit.tpl');
146
-        }
147
-    }
148
-
149
-    /**
150
-     * @param EmailTemplate $template
151
-     *
152
-     * @throws ApplicationLogicException
153
-     */
154
-    private function modifyTemplateData(EmailTemplate $template)
155
-    {
156
-        $name = WebRequest::postString('name');
157
-        if ($name === null || $name === '') {
158
-            throw new ApplicationLogicException('Name not specified');
159
-        }
160
-
161
-        $template->setName($name);
162
-
163
-        $text = WebRequest::postString('text');
164
-        if ($text === null || $text === '') {
165
-            throw new ApplicationLogicException('Text not specified');
166
-        }
167
-
168
-        $template->setText($text);
169
-
170
-        $template->setJsquestion(WebRequest::postString('jsquestion'));
171
-
172
-        $template->setDefaultAction(WebRequest::postString('defaultaction'));
173
-        $template->setActive(WebRequest::postBoolean('active'));
174
-        $template->setPreloadOnly(WebRequest::postBoolean('preloadonly'));
175
-    }
176
-
177
-    protected function create()
178
-    {
179
-        $this->setHtmlTitle('Close Emails');
180
-
181
-        $database = $this->getDatabase();
182
-
183
-        $requestStates = $this->getSiteConfiguration()->getRequestStates();
184
-
185
-        if (WebRequest::wasPosted()) {
186
-            $this->validateCSRFToken();
187
-            $template = new EmailTemplate();
188
-            $template->setDatabase($database);
189
-
190
-            $this->modifyTemplateData($template);
191
-
192
-            $other = EmailTemplate::getByName($template->getName(), $database);
193
-            if ($other !== false) {
194
-                throw new ApplicationLogicException('A template with this name already exists');
195
-            }
196
-
197
-            $template->save();
198
-
199
-            Logger::createEmail($database, $template);
200
-            $this->getNotificationHelper()->emailCreated($template);
201
-
202
-            SessionAlert::success("Email template has been saved successfully.");
203
-
204
-            $this->redirect('emailManagement');
205
-        }
206
-        else {
207
-            $this->assignCSRFToken();
208
-            $this->assign('requeststates', $requestStates);
209
-            $this->setTemplate('email-management/create.tpl');
210
-        }
211
-    }
21
+	/**
22
+	 * Sets up the security for this page. If certain actions have different permissions, this should be reflected in
23
+	 * the return value from this function.
24
+	 *
25
+	 * If this page even supports actions, you will need to check the route
26
+	 *
27
+	 * @return \Waca\Security\SecurityConfiguration
28
+	 * @category Security-Critical
29
+	 */
30
+	protected function getSecurityConfiguration()
31
+	{
32
+		switch ($this->getRouteName()) {
33
+			case 'edit':
34
+			case 'create':
35
+				return $this->getSecurityManager()->configure()->asAdminPage();
36
+			case 'view':
37
+			case 'main':
38
+				return $this->getSecurityManager()->configure()->asInternalPage();
39
+		}
40
+
41
+		// deny all
42
+		return $this->getSecurityManager()->configure()->asNone();
43
+	}
44
+
45
+	/**
46
+	 * Main function for this page, when no specific actions are called.
47
+	 * @return void
48
+	 */
49
+	protected function main()
50
+	{
51
+		$this->setHtmlTitle('Close Emails');
52
+
53
+		// Get all active email templates
54
+		$activeTemplates = EmailTemplate::getAllActiveTemplates(null, $this->getDatabase());
55
+		$inactiveTemplates = EmailTemplate::getAllInactiveTemplates($this->getDatabase());
56
+
57
+		$this->assign('activeTemplates', $activeTemplates);
58
+		$this->assign('inactiveTemplates', $inactiveTemplates);
59
+
60
+		$this->setTemplate('email-management/main.tpl');
61
+	}
62
+
63
+	protected function view()
64
+	{
65
+		$this->setHtmlTitle('Close Emails');
66
+
67
+		$database = $this->getDatabase();
68
+		$template = $this->getTemplate($database);
69
+
70
+		$createdId = $this->getSiteConfiguration()->getDefaultCreatedTemplateId();
71
+		$requestStates = $this->getSiteConfiguration()->getRequestStates();
72
+
73
+		$this->assign('id', $template->getId());
74
+		$this->assign('emailTemplate', $template);
75
+		$this->assign('createdid', $createdId);
76
+		$this->assign('requeststates', $requestStates);
77
+
78
+		$this->setTemplate('email-management/view.tpl');
79
+	}
80
+
81
+	/**
82
+	 * @param PdoDatabase $database
83
+	 *
84
+	 * @return EmailTemplate
85
+	 * @throws ApplicationLogicException
86
+	 */
87
+	protected function getTemplate(PdoDatabase $database)
88
+	{
89
+		$templateId = WebRequest::getInt('id');
90
+		if ($templateId === null) {
91
+			throw new ApplicationLogicException('Template not specified');
92
+		}
93
+		$template = EmailTemplate::getById($templateId, $database);
94
+		if ($template === false || !is_a($template, EmailTemplate::class)) {
95
+			throw new ApplicationLogicException('Template not found');
96
+		}
97
+
98
+		return $template;
99
+	}
100
+
101
+	protected function edit()
102
+	{
103
+		$this->setHtmlTitle('Close Emails');
104
+
105
+		$database = $this->getDatabase();
106
+		$template = $this->getTemplate($database);
107
+
108
+		$createdId = $this->getSiteConfiguration()->getDefaultCreatedTemplateId();
109
+		$requestStates = $this->getSiteConfiguration()->getRequestStates();
110
+
111
+		if (WebRequest::wasPosted()) {
112
+			$this->validateCSRFToken();
113
+
114
+			$this->modifyTemplateData($template);
115
+
116
+			$other = EmailTemplate::getByName($template->getName(), $database);
117
+			if ($other !== false && $other->getId() !== $template->getId()) {
118
+				throw new ApplicationLogicException('A template with this name already exists');
119
+			}
120
+
121
+			if ($template->getId() === $createdId) {
122
+				$template->setDefaultAction(EmailTemplate::CREATED);
123
+				$template->setActive(true);
124
+				$template->setPreloadOnly(false);
125
+			}
126
+
127
+			// optimistically lock on load of edit form
128
+			$updateVersion = WebRequest::postInt('updateversion');
129
+			$template->setUpdateVersion($updateVersion);
130
+
131
+			$template->save();
132
+			Logger::editedEmail($database, $template);
133
+			$this->getNotificationHelper()->emailEdited($template);
134
+			SessionAlert::success("Email template has been saved successfully.");
135
+
136
+			$this->redirect('emailManagement');
137
+		}
138
+		else {
139
+			$this->assignCSRFToken();
140
+			$this->assign('id', $template->getId());
141
+			$this->assign('emailTemplate', $template);
142
+			$this->assign('createdid', $createdId);
143
+			$this->assign('requeststates', $requestStates);
144
+
145
+			$this->setTemplate('email-management/edit.tpl');
146
+		}
147
+	}
148
+
149
+	/**
150
+	 * @param EmailTemplate $template
151
+	 *
152
+	 * @throws ApplicationLogicException
153
+	 */
154
+	private function modifyTemplateData(EmailTemplate $template)
155
+	{
156
+		$name = WebRequest::postString('name');
157
+		if ($name === null || $name === '') {
158
+			throw new ApplicationLogicException('Name not specified');
159
+		}
160
+
161
+		$template->setName($name);
162
+
163
+		$text = WebRequest::postString('text');
164
+		if ($text === null || $text === '') {
165
+			throw new ApplicationLogicException('Text not specified');
166
+		}
167
+
168
+		$template->setText($text);
169
+
170
+		$template->setJsquestion(WebRequest::postString('jsquestion'));
171
+
172
+		$template->setDefaultAction(WebRequest::postString('defaultaction'));
173
+		$template->setActive(WebRequest::postBoolean('active'));
174
+		$template->setPreloadOnly(WebRequest::postBoolean('preloadonly'));
175
+	}
176
+
177
+	protected function create()
178
+	{
179
+		$this->setHtmlTitle('Close Emails');
180
+
181
+		$database = $this->getDatabase();
182
+
183
+		$requestStates = $this->getSiteConfiguration()->getRequestStates();
184
+
185
+		if (WebRequest::wasPosted()) {
186
+			$this->validateCSRFToken();
187
+			$template = new EmailTemplate();
188
+			$template->setDatabase($database);
189
+
190
+			$this->modifyTemplateData($template);
191
+
192
+			$other = EmailTemplate::getByName($template->getName(), $database);
193
+			if ($other !== false) {
194
+				throw new ApplicationLogicException('A template with this name already exists');
195
+			}
196
+
197
+			$template->save();
198
+
199
+			Logger::createEmail($database, $template);
200
+			$this->getNotificationHelper()->emailCreated($template);
201
+
202
+			SessionAlert::success("Email template has been saved successfully.");
203
+
204
+			$this->redirect('emailManagement');
205
+		}
206
+		else {
207
+			$this->assignCSRFToken();
208
+			$this->assign('requeststates', $requestStates);
209
+			$this->setTemplate('email-management/create.tpl');
210
+		}
211
+	}
212 212
 }
213 213
\ No newline at end of file
Please login to merge, or discard this patch.