Passed
Push — dependabot/composer/php8/media... ( e6d0f9 )
by
unknown
34:23 queued 29:40
created
includes/Pages/UserAuth/PageOAuth.php 1 patch
Indentation   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -22,81 +22,81 @@
 block discarded – undo
22 22
 
23 23
 class PageOAuth extends InternalPageBase
24 24
 {
25
-    /**
26
-     * Attach entry point
27
-     *
28
-     * must be posted, or will redirect to preferences
29
-     */
30
-    protected function attach()
31
-    {
32
-        if (!WebRequest::wasPosted()) {
33
-            $this->redirect('preferences');
34
-
35
-            return;
36
-        }
37
-
38
-        $database = $this->getDatabase();
39
-
40
-        $this->validateCSRFToken();
41
-
42
-        $oauthProtocolHelper = $this->getOAuthProtocolHelper();
43
-        $user = User::getCurrent($database);
44
-        $oauth = new OAuthUserHelper($user, $database, $oauthProtocolHelper, $this->getSiteConfiguration());
45
-
46
-        try {
47
-            $authoriseUrl = $oauth->getRequestToken();
48
-            $this->redirectUrl($authoriseUrl);
49
-        }
50
-        catch (CurlException $ex) {
51
-            throw new ApplicationLogicException($ex->getMessage(), 0, $ex);
52
-        }
53
-    }
54
-
55
-    /**
56
-     * Detach account entry point
57
-     * @throws Exception
58
-     */
59
-    protected function detach()
60
-    {
61
-        if ($this->getSiteConfiguration()->getEnforceOAuth()) {
62
-            throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
63
-        }
64
-
65
-        $database = $this->getDatabase();
66
-        $user = User::getCurrent($database);
67
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
68
-
69
-        try {
70
-            $oauth->refreshIdentity();
71
-        }
72
-        catch (CurlException $ex) {
73
-            // do nothing. The user's already revoked this access anyway.
74
-        }
75
-        catch (OAuthException $ex) {
76
-            // do nothing. The user's already revoked this access anyway.
77
-        }
78
-        catch (OptimisticLockFailedException $e) {
79
-            // do nothing. The user's already revoked this access anyway.
80
-        }
81
-
82
-        $oauth->detach();
83
-
84
-        // TODO: figure out why we need to force logout after a detach.
85
-        $user->setForcelogout(true);
86
-        $user->save();
87
-
88
-        // force the user to log out
89
-        Session::destroy();
90
-
91
-        $this->redirect('login');
92
-    }
93
-
94
-    /**
95
-     * Main function for this page, when no specific actions are called.
96
-     * @return void
97
-     */
98
-    protected function main()
99
-    {
100
-        $this->redirect('preferences');
101
-    }
25
+	/**
26
+	 * Attach entry point
27
+	 *
28
+	 * must be posted, or will redirect to preferences
29
+	 */
30
+	protected function attach()
31
+	{
32
+		if (!WebRequest::wasPosted()) {
33
+			$this->redirect('preferences');
34
+
35
+			return;
36
+		}
37
+
38
+		$database = $this->getDatabase();
39
+
40
+		$this->validateCSRFToken();
41
+
42
+		$oauthProtocolHelper = $this->getOAuthProtocolHelper();
43
+		$user = User::getCurrent($database);
44
+		$oauth = new OAuthUserHelper($user, $database, $oauthProtocolHelper, $this->getSiteConfiguration());
45
+
46
+		try {
47
+			$authoriseUrl = $oauth->getRequestToken();
48
+			$this->redirectUrl($authoriseUrl);
49
+		}
50
+		catch (CurlException $ex) {
51
+			throw new ApplicationLogicException($ex->getMessage(), 0, $ex);
52
+		}
53
+	}
54
+
55
+	/**
56
+	 * Detach account entry point
57
+	 * @throws Exception
58
+	 */
59
+	protected function detach()
60
+	{
61
+		if ($this->getSiteConfiguration()->getEnforceOAuth()) {
62
+			throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
63
+		}
64
+
65
+		$database = $this->getDatabase();
66
+		$user = User::getCurrent($database);
67
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
68
+
69
+		try {
70
+			$oauth->refreshIdentity();
71
+		}
72
+		catch (CurlException $ex) {
73
+			// do nothing. The user's already revoked this access anyway.
74
+		}
75
+		catch (OAuthException $ex) {
76
+			// do nothing. The user's already revoked this access anyway.
77
+		}
78
+		catch (OptimisticLockFailedException $e) {
79
+			// do nothing. The user's already revoked this access anyway.
80
+		}
81
+
82
+		$oauth->detach();
83
+
84
+		// TODO: figure out why we need to force logout after a detach.
85
+		$user->setForcelogout(true);
86
+		$user->save();
87
+
88
+		// force the user to log out
89
+		Session::destroy();
90
+
91
+		$this->redirect('login');
92
+	}
93
+
94
+	/**
95
+	 * Main function for this page, when no specific actions are called.
96
+	 * @return void
97
+	 */
98
+	protected function main()
99
+	{
100
+		$this->redirect('preferences');
101
+	}
102 102
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageBreakReservation.php 2 patches
Indentation   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -19,81 +19,81 @@
 block discarded – undo
19 19
 
20 20
 class PageBreakReservation extends RequestActionBase
21 21
 {
22
-    protected function main()
23
-    {
24
-        $this->checkPosted();
25
-        $database = $this->getDatabase();
26
-        $request = $this->getRequest($database);
22
+	protected function main()
23
+	{
24
+		$this->checkPosted();
25
+		$database = $this->getDatabase();
26
+		$request = $this->getRequest($database);
27 27
 
28
-        if ($request->getReserved() === null) {
29
-            throw new ApplicationLogicException('Request is not reserved!');
30
-        }
28
+		if ($request->getReserved() === null) {
29
+			throw new ApplicationLogicException('Request is not reserved!');
30
+		}
31 31
 
32
-        $currentUser = User::getCurrent($database);
32
+		$currentUser = User::getCurrent($database);
33 33
 
34
-        if ($currentUser->getId() === $request->getReserved()) {
35
-            $this->doUnreserve($request, $database);
36
-        }
37
-        else {
38
-            // not the same user!
39
-            if ($this->barrierTest('force', $currentUser)) {
40
-                $this->doBreakReserve($request, $database);
41
-            }
42
-            else {
43
-                throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
44
-            }
45
-        }
46
-    }
34
+		if ($currentUser->getId() === $request->getReserved()) {
35
+			$this->doUnreserve($request, $database);
36
+		}
37
+		else {
38
+			// not the same user!
39
+			if ($this->barrierTest('force', $currentUser)) {
40
+				$this->doBreakReserve($request, $database);
41
+			}
42
+			else {
43
+				throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
44
+			}
45
+		}
46
+	}
47 47
 
48
-    /**
49
-     * @param Request     $request
50
-     * @param PdoDatabase $database
51
-     *
52
-     * @throws Exception
53
-     */
54
-    protected function doUnreserve(Request $request, PdoDatabase $database)
55
-    {
56
-        // same user! we allow people to unreserve their own stuff
57
-        $request->setReserved(null);
58
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
59
-        $request->save();
48
+	/**
49
+	 * @param Request     $request
50
+	 * @param PdoDatabase $database
51
+	 *
52
+	 * @throws Exception
53
+	 */
54
+	protected function doUnreserve(Request $request, PdoDatabase $database)
55
+	{
56
+		// same user! we allow people to unreserve their own stuff
57
+		$request->setReserved(null);
58
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
59
+		$request->save();
60 60
 
61
-        Logger::unreserve($database, $request);
62
-        $this->getNotificationHelper()->requestUnreserved($request);
61
+		Logger::unreserve($database, $request);
62
+		$this->getNotificationHelper()->requestUnreserved($request);
63 63
 
64
-        // Redirect home!
65
-        $this->redirect();
66
-    }
64
+		// Redirect home!
65
+		$this->redirect();
66
+	}
67 67
 
68
-    /**
69
-     * @param Request     $request
70
-     * @param PdoDatabase $database
71
-     *
72
-     * @throws Exception
73
-     */
74
-    protected function doBreakReserve(Request $request, PdoDatabase $database)
75
-    {
76
-        if (!WebRequest::postBoolean("confirm")) {
77
-            $this->assignCSRFToken();
68
+	/**
69
+	 * @param Request     $request
70
+	 * @param PdoDatabase $database
71
+	 *
72
+	 * @throws Exception
73
+	 */
74
+	protected function doBreakReserve(Request $request, PdoDatabase $database)
75
+	{
76
+		if (!WebRequest::postBoolean("confirm")) {
77
+			$this->assignCSRFToken();
78 78
 
79
-            $this->assign("request", $request->getId());
80
-            $this->assign("reservedUser", User::getById($request->getReserved(), $database));
81
-            $this->assign("updateversion", WebRequest::postInt('updateversion'));
79
+			$this->assign("request", $request->getId());
80
+			$this->assign("reservedUser", User::getById($request->getReserved(), $database));
81
+			$this->assign("updateversion", WebRequest::postInt('updateversion'));
82 82
 
83
-            $this->skipAlerts();
83
+			$this->skipAlerts();
84 84
 
85
-            $this->setTemplate("confirmations/breakreserve.tpl");
86
-        }
87
-        else {
88
-            $request->setReserved(null);
89
-            $request->setUpdateVersion(WebRequest::postInt('updateversion'));
90
-            $request->save();
85
+			$this->setTemplate("confirmations/breakreserve.tpl");
86
+		}
87
+		else {
88
+			$request->setReserved(null);
89
+			$request->setUpdateVersion(WebRequest::postInt('updateversion'));
90
+			$request->save();
91 91
 
92
-            Logger::breakReserve($database, $request);
93
-            $this->getNotificationHelper()->requestReserveBroken($request);
92
+			Logger::breakReserve($database, $request);
93
+			$this->getNotificationHelper()->requestReserveBroken($request);
94 94
 
95
-            // Redirect home!
96
-            $this->redirect();
97
-        }
98
-    }
95
+			// Redirect home!
96
+			$this->redirect();
97
+		}
98
+	}
99 99
 }
Please login to merge, or discard this patch.
Braces   +3 added lines, -6 removed lines patch added patch discarded remove patch
@@ -33,13 +33,11 @@  discard block
 block discarded – undo
33 33
 
34 34
         if ($currentUser->getId() === $request->getReserved()) {
35 35
             $this->doUnreserve($request, $database);
36
-        }
37
-        else {
36
+        } else {
38 37
             // not the same user!
39 38
             if ($this->barrierTest('force', $currentUser)) {
40 39
                 $this->doBreakReserve($request, $database);
41
-            }
42
-            else {
40
+            } else {
43 41
                 throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
44 42
             }
45 43
         }
@@ -83,8 +81,7 @@  discard block
 block discarded – undo
83 81
             $this->skipAlerts();
84 82
 
85 83
             $this->setTemplate("confirmations/breakreserve.tpl");
86
-        }
87
-        else {
84
+        } else {
88 85
             $request->setReserved(null);
89 86
             $request->setUpdateVersion(WebRequest::postInt('updateversion'));
90 87
             $request->save();
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageReservation.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -18,58 +18,58 @@
 block discarded – undo
18 18
 
19 19
 class PageReservation extends RequestActionBase
20 20
 {
21
-    /**
22
-     * Main function for this page, when no specific actions are called.
23
-     * @throws ApplicationLogicException
24
-     */
25
-    protected function main()
26
-    {
27
-        $this->checkPosted();
28
-        $database = $this->getDatabase();
29
-        $request = $this->getRequest($database);
21
+	/**
22
+	 * Main function for this page, when no specific actions are called.
23
+	 * @throws ApplicationLogicException
24
+	 */
25
+	protected function main()
26
+	{
27
+		$this->checkPosted();
28
+		$database = $this->getDatabase();
29
+		$request = $this->getRequest($database);
30 30
 
31
-        $closureDate = $request->getClosureDate();
31
+		$closureDate = $request->getClosureDate();
32 32
 
33
-        $date = new DateTime();
34
-        $date->modify("-7 days");
35
-        $oneweek = $date->format("Y-m-d H:i:s");
33
+		$date = new DateTime();
34
+		$date->modify("-7 days");
35
+		$oneweek = $date->format("Y-m-d H:i:s");
36 36
 
37
-        $currentUser = User::getCurrent($database);
38
-        if ($request->getStatus() == RequestStatus::CLOSED && $closureDate < $oneweek) {
39
-            if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
40
-                throw new ApplicationLogicException(
41
-                    "You are not allowed to reserve a request that has been closed for over a week.");
42
-            }
43
-        }
37
+		$currentUser = User::getCurrent($database);
38
+		if ($request->getStatus() == RequestStatus::CLOSED && $closureDate < $oneweek) {
39
+			if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
40
+				throw new ApplicationLogicException(
41
+					"You are not allowed to reserve a request that has been closed for over a week.");
42
+			}
43
+		}
44 44
 
45
-        if ($request->getReserved() !== null && $request->getReserved() != $currentUser->getId()) {
46
-            throw new ApplicationLogicException("Request is already reserved!");
47
-        }
45
+		if ($request->getReserved() !== null && $request->getReserved() != $currentUser->getId()) {
46
+			throw new ApplicationLogicException("Request is already reserved!");
47
+		}
48 48
 
49
-        if ($request->getReserved() === null) {
50
-            // Check the number of requests a user has reserved already
51
-            $doubleReserveCountQuery = $database->prepare("SELECT COUNT(*) FROM request WHERE reserved = :userid;");
52
-            $doubleReserveCountQuery->bindValue(":userid", $currentUser->getId());
53
-            $doubleReserveCountQuery->execute();
54
-            $doubleReserveCount = $doubleReserveCountQuery->fetchColumn();
55
-            $doubleReserveCountQuery->closeCursor();
49
+		if ($request->getReserved() === null) {
50
+			// Check the number of requests a user has reserved already
51
+			$doubleReserveCountQuery = $database->prepare("SELECT COUNT(*) FROM request WHERE reserved = :userid;");
52
+			$doubleReserveCountQuery->bindValue(":userid", $currentUser->getId());
53
+			$doubleReserveCountQuery->execute();
54
+			$doubleReserveCount = $doubleReserveCountQuery->fetchColumn();
55
+			$doubleReserveCountQuery->closeCursor();
56 56
 
57
-            // User already has at least one reserved.
58
-            if ($doubleReserveCount != 0) {
59
-                SessionAlert::warning("You have multiple requests reserved!");
60
-            }
57
+			// User already has at least one reserved.
58
+			if ($doubleReserveCount != 0) {
59
+				SessionAlert::warning("You have multiple requests reserved!");
60
+			}
61 61
 
62
-            $request->setReserved($currentUser->getId());
63
-            $request->setUpdateVersion(WebRequest::postInt('updateversion'));
64
-            $request->save();
62
+			$request->setReserved($currentUser->getId());
63
+			$request->setUpdateVersion(WebRequest::postInt('updateversion'));
64
+			$request->save();
65 65
 
66
-            Logger::reserve($database, $request);
66
+			Logger::reserve($database, $request);
67 67
 
68
-            $this->getNotificationHelper()->requestReserved($request);
68
+			$this->getNotificationHelper()->requestReserved($request);
69 69
 
70
-            SessionAlert::success("Reserved request {$request->getId()}.");
71
-        }
70
+			SessionAlert::success("Reserved request {$request->getId()}.");
71
+		}
72 72
 
73
-        $this->redirect('viewRequest', null, array('id' => $request->getId()));
74
-    }
73
+		$this->redirect('viewRequest', null, array('id' => $request->getId()));
74
+	}
75 75
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageManuallyConfirm.php 1 patch
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -15,39 +15,39 @@
 block discarded – undo
15 15
 
16 16
 class PageManuallyConfirm extends RequestActionBase
17 17
 {
18
-    /**
19
-     * This endpoint manually confirms a request, bypassing email confirmation.
20
-     *
21
-     * Only administrators are allowed to do this, for obvious reasons.
22
-     *
23
-     * @throws ApplicationLogicException|OptimisticLockFailedException
24
-     */
25
-    protected function main()
26
-    {
27
-        // This method throws an error if we don't post
28
-        $this->checkPosted();
29
-
30
-        // Retrieve the database.
31
-        $database = $this->getDatabase();
32
-
33
-        // Find the request
34
-        // This method throws exceptions if there is an error with the request.
35
-        $request = $this->getRequest($database);
36
-        $version = WebRequest::postInt('version');
37
-
38
-        $request->setUpdateVersion($version);
39
-
40
-        // Mark the request as confirmed.
41
-        $request->setEmailConfirm("Confirmed");
42
-        $request->save();
43
-
44
-        // Log that the request was manually confirmed
45
-        Logger::manuallyConfirmRequest($database, $request);
46
-
47
-        // Notify the IRC channel
48
-        $this->getNotificationHelper()->requestReceived($request);
49
-
50
-        // Redirect back to the main request, now it should show the request.
51
-        $this->redirect('viewRequest', null, array('id' => $request->getId()));
52
-    }
18
+	/**
19
+	 * This endpoint manually confirms a request, bypassing email confirmation.
20
+	 *
21
+	 * Only administrators are allowed to do this, for obvious reasons.
22
+	 *
23
+	 * @throws ApplicationLogicException|OptimisticLockFailedException
24
+	 */
25
+	protected function main()
26
+	{
27
+		// This method throws an error if we don't post
28
+		$this->checkPosted();
29
+
30
+		// Retrieve the database.
31
+		$database = $this->getDatabase();
32
+
33
+		// Find the request
34
+		// This method throws exceptions if there is an error with the request.
35
+		$request = $this->getRequest($database);
36
+		$version = WebRequest::postInt('version');
37
+
38
+		$request->setUpdateVersion($version);
39
+
40
+		// Mark the request as confirmed.
41
+		$request->setEmailConfirm("Confirmed");
42
+		$request->save();
43
+
44
+		// Log that the request was manually confirmed
45
+		Logger::manuallyConfirmRequest($database, $request);
46
+
47
+		// Notify the IRC channel
48
+		$this->getNotificationHelper()->requestReceived($request);
49
+
50
+		// Redirect back to the main request, now it should show the request.
51
+		$this->redirect('viewRequest', null, array('id' => $request->getId()));
52
+	}
53 53
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageCloseRequest.php 1 patch
Indentation   +244 added lines, -244 removed lines patch added patch discarded remove patch
@@ -25,248 +25,248 @@
 block discarded – undo
25 25
 
26 26
 class PageCloseRequest extends RequestActionBase
27 27
 {
28
-    protected function main()
29
-    {
30
-        $this->processClose();
31
-    }
32
-
33
-    /**
34
-     * Main function for this page, when no specific actions are called.
35
-     * @throws ApplicationLogicException
36
-     */
37
-    final protected function processClose()
38
-    {
39
-        $this->checkPosted();
40
-        $database = $this->getDatabase();
41
-
42
-        $currentUser = User::getCurrent($database);
43
-        $template = $this->getTemplate($database);
44
-        $request = $this->getRequest($database);
45
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
46
-
47
-        if ($request->getStatus() === RequestStatus::CLOSED) {
48
-            throw new ApplicationLogicException('Request is already closed');
49
-        }
50
-
51
-        if ($this->confirmEmailAlreadySent($request, $template)) {
52
-            return;
53
-        }
54
-
55
-        if ($this->checkReserveProtect($request, $currentUser)) {
56
-            return;
57
-        }
58
-
59
-        if ($this->confirmAccountCreated($request, $template)) {
60
-            return;
61
-        }
62
-
63
-        // I think we're good here...
64
-        $request->setStatus(RequestStatus::CLOSED);
65
-        $request->setQueue(null);
66
-        $request->setReserved(null);
67
-
68
-        Logger::closeRequest($database, $request, $template->getId(), null);
69
-
70
-        $request->save();
71
-
72
-        $this->processWelcome($template->getDefaultAction(), null);
73
-
74
-        // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
75
-        // be rolled back.
76
-
77
-        $this->getNotificationHelper()->requestClosed($request, $template->getName());
78
-        $sanitisedTemplateName = htmlentities($template->getName(), ENT_COMPAT, 'UTF-8');
79
-        SessionAlert::success("Request {$request->getId()} has been closed as {$sanitisedTemplateName}");
80
-
81
-        $this->sendMail($request, $template->getText(), $currentUser, false);
82
-
83
-        $this->redirect();
84
-    }
85
-
86
-    /**
87
-     * @param PdoDatabase $database
88
-     *
89
-     * @return EmailTemplate
90
-     * @throws ApplicationLogicException
91
-     */
92
-    protected function getTemplate(PdoDatabase $database)
93
-    {
94
-        $templateId = WebRequest::postInt('template');
95
-        if ($templateId === null) {
96
-            throw new ApplicationLogicException('No template specified');
97
-        }
98
-
99
-        /** @var EmailTemplate $template */
100
-        $template = EmailTemplate::getById($templateId, $database);
101
-        if ($template === false || !$template->getActive()) {
102
-            throw new ApplicationLogicException('Invalid or inactive template specified');
103
-        }
104
-
105
-        return $template;
106
-    }
107
-
108
-    /**
109
-     * @param Request       $request
110
-     * @param EmailTemplate $template
111
-     *
112
-     * @return bool
113
-     */
114
-    protected function confirmEmailAlreadySent(Request $request, EmailTemplate $template)
115
-    {
116
-        if ($this->checkEmailAlreadySent($request)) {
117
-            $this->showConfirmation($request, $template, 'close-confirmations/email-sent.tpl');
118
-
119
-            return true;
120
-        }
121
-
122
-        return false;
123
-    }
124
-
125
-    protected function checkEmailAlreadySent(Request $request)
126
-    {
127
-        if ($request->getEmailSent() && !WebRequest::postBoolean('emailSentOverride')) {
128
-            return true;
129
-        }
130
-
131
-        return false;
132
-    }
133
-
134
-    protected function checkReserveProtect(Request $request, User $currentUser)
135
-    {
136
-        $reservationId = $request->getReserved();
137
-
138
-        if ($reservationId !== 0 && $reservationId !== null) {
139
-            if ($currentUser->getId() !== $reservationId) {
140
-                SessionAlert::error("Request is reserved by someone else.");
141
-                $this->redirect('/viewRequest', null, ['id' => $request->getId()]);
142
-                return true;
143
-            }
144
-        }
145
-
146
-        return false;
147
-    }
148
-
149
-    /**
150
-     * @param Request       $request
151
-     * @param EmailTemplate $template
152
-     *
153
-     * @return bool
154
-     * @throws Exception
155
-     */
156
-    protected function confirmAccountCreated(Request $request, EmailTemplate $template)
157
-    {
158
-        if ($template->getDefaultAction() === EmailTemplate::ACTION_CREATED && $this->checkAccountCreated($request)) {
159
-            $this->showConfirmation($request, $template, 'close-confirmations/account-created.tpl');
160
-
161
-            return true;
162
-        }
163
-
164
-        return false;
165
-    }
166
-
167
-    protected function checkAccountCreated(Request $request)
168
-    {
169
-        if (!WebRequest::postBoolean('createOverride')) {
170
-            $parameters = array(
171
-                'action'  => 'query',
172
-                'list'    => 'users',
173
-                'format'  => 'php',
174
-                'ususers' => $request->getName(),
175
-            );
176
-
177
-            // FIXME: domains!
178
-            /** @var Domain $domain */
179
-            $domain = Domain::getById(1, $this->getDatabase());
180
-
181
-            $content = $this->getHttpHelper()->get($domain->getWikiApiPath(), $parameters);
182
-
183
-            $apiResult = unserialize($content);
184
-            $exists = !isset($apiResult['query']['users']['0']['missing']);
185
-
186
-            if (!$exists) {
187
-                return true;
188
-            }
189
-        }
190
-
191
-        return false;
192
-    }
193
-
194
-    /**
195
-     * @param Request $request
196
-     * @param string  $mailText
197
-     * @param User    $currentUser
198
-     * @param boolean $ccMailingList
199
-     */
200
-    protected function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
201
-    {
202
-        if (
203
-        ($request->getEmail() != $this->getSiteConfiguration()->getDataClearEmail()) &&
204
-        ($request->getIp() != $this->getSiteConfiguration()->getDataClearIp())
205
-        ) {
206
-            $requestEmailHelper = new RequestEmailHelper($this->getEmailHelper());
207
-            $requestEmailHelper->sendMail($request, $mailText, $currentUser, $ccMailingList);
208
-
209
-            $request->setEmailSent(true);
210
-            $request->save();
211
-        }
212
-    }
213
-
214
-    /**
215
-     * @param Request       $request
216
-     * @param EmailTemplate $template
217
-     * @param string        $templateName
218
-     *
219
-     * @throws Exception
220
-     * @return void
221
-     */
222
-    protected function showConfirmation(Request $request, EmailTemplate $template, $templateName)
223
-    {
224
-        $this->assignCSRFToken();
225
-
226
-        $this->assign('request', $request->getId());
227
-        $this->assign('template', $template->getId());
228
-
229
-        $this->assign('updateversion', $request->getUpdateVersion());
230
-
231
-        $this->assign('emailSentOverride', WebRequest::postBoolean('emailSentOverride') ? 'true' : 'false');
232
-        $this->assign('reserveOverride', WebRequest::postBoolean('reserveOverride') ? 'true' : 'false');
233
-        $this->assign('createOverride', WebRequest::postBoolean('createOverride') ? 'true' : 'false');
234
-        $this->assign('skipAutoWelcome', WebRequest::postBoolean('skipAutoWelcome') ? 'true' : 'false');
235
-
236
-        $this->skipAlerts();
237
-
238
-        $this->setTemplate($templateName);
239
-    }
240
-
241
-    /**
242
-     * @param string $action
243
-     * @param int|null   $parentTaskId
244
-     *
245
-     * @throws ApplicationLogicException
246
-     */
247
-    final protected function processWelcome(string $action, ?int $parentTaskId): void
248
-    {
249
-        $database = $this->getDatabase();
250
-        $currentUser = User::getCurrent($database);
251
-        $preferencesManager = PreferenceManager::getForCurrent($database);
252
-
253
-        if ($action !== EmailTemplate::ACTION_CREATED) {
254
-            return;
255
-        }
256
-
257
-        if ($preferencesManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE) === null) {
258
-            return;
259
-        }
260
-
261
-        $oauth = new OAuthUserHelper($currentUser, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
262
-        if (!$oauth->canWelcome()) {
263
-            return;
264
-        }
265
-
266
-        if (WebRequest::postBoolean('skipAutoWelcome')) {
267
-            return;
268
-        }
269
-
270
-        $this->enqueueWelcomeTask($this->getRequest($database), $parentTaskId, $currentUser, $database);
271
-    }
28
+	protected function main()
29
+	{
30
+		$this->processClose();
31
+	}
32
+
33
+	/**
34
+	 * Main function for this page, when no specific actions are called.
35
+	 * @throws ApplicationLogicException
36
+	 */
37
+	final protected function processClose()
38
+	{
39
+		$this->checkPosted();
40
+		$database = $this->getDatabase();
41
+
42
+		$currentUser = User::getCurrent($database);
43
+		$template = $this->getTemplate($database);
44
+		$request = $this->getRequest($database);
45
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
46
+
47
+		if ($request->getStatus() === RequestStatus::CLOSED) {
48
+			throw new ApplicationLogicException('Request is already closed');
49
+		}
50
+
51
+		if ($this->confirmEmailAlreadySent($request, $template)) {
52
+			return;
53
+		}
54
+
55
+		if ($this->checkReserveProtect($request, $currentUser)) {
56
+			return;
57
+		}
58
+
59
+		if ($this->confirmAccountCreated($request, $template)) {
60
+			return;
61
+		}
62
+
63
+		// I think we're good here...
64
+		$request->setStatus(RequestStatus::CLOSED);
65
+		$request->setQueue(null);
66
+		$request->setReserved(null);
67
+
68
+		Logger::closeRequest($database, $request, $template->getId(), null);
69
+
70
+		$request->save();
71
+
72
+		$this->processWelcome($template->getDefaultAction(), null);
73
+
74
+		// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
75
+		// be rolled back.
76
+
77
+		$this->getNotificationHelper()->requestClosed($request, $template->getName());
78
+		$sanitisedTemplateName = htmlentities($template->getName(), ENT_COMPAT, 'UTF-8');
79
+		SessionAlert::success("Request {$request->getId()} has been closed as {$sanitisedTemplateName}");
80
+
81
+		$this->sendMail($request, $template->getText(), $currentUser, false);
82
+
83
+		$this->redirect();
84
+	}
85
+
86
+	/**
87
+	 * @param PdoDatabase $database
88
+	 *
89
+	 * @return EmailTemplate
90
+	 * @throws ApplicationLogicException
91
+	 */
92
+	protected function getTemplate(PdoDatabase $database)
93
+	{
94
+		$templateId = WebRequest::postInt('template');
95
+		if ($templateId === null) {
96
+			throw new ApplicationLogicException('No template specified');
97
+		}
98
+
99
+		/** @var EmailTemplate $template */
100
+		$template = EmailTemplate::getById($templateId, $database);
101
+		if ($template === false || !$template->getActive()) {
102
+			throw new ApplicationLogicException('Invalid or inactive template specified');
103
+		}
104
+
105
+		return $template;
106
+	}
107
+
108
+	/**
109
+	 * @param Request       $request
110
+	 * @param EmailTemplate $template
111
+	 *
112
+	 * @return bool
113
+	 */
114
+	protected function confirmEmailAlreadySent(Request $request, EmailTemplate $template)
115
+	{
116
+		if ($this->checkEmailAlreadySent($request)) {
117
+			$this->showConfirmation($request, $template, 'close-confirmations/email-sent.tpl');
118
+
119
+			return true;
120
+		}
121
+
122
+		return false;
123
+	}
124
+
125
+	protected function checkEmailAlreadySent(Request $request)
126
+	{
127
+		if ($request->getEmailSent() && !WebRequest::postBoolean('emailSentOverride')) {
128
+			return true;
129
+		}
130
+
131
+		return false;
132
+	}
133
+
134
+	protected function checkReserveProtect(Request $request, User $currentUser)
135
+	{
136
+		$reservationId = $request->getReserved();
137
+
138
+		if ($reservationId !== 0 && $reservationId !== null) {
139
+			if ($currentUser->getId() !== $reservationId) {
140
+				SessionAlert::error("Request is reserved by someone else.");
141
+				$this->redirect('/viewRequest', null, ['id' => $request->getId()]);
142
+				return true;
143
+			}
144
+		}
145
+
146
+		return false;
147
+	}
148
+
149
+	/**
150
+	 * @param Request       $request
151
+	 * @param EmailTemplate $template
152
+	 *
153
+	 * @return bool
154
+	 * @throws Exception
155
+	 */
156
+	protected function confirmAccountCreated(Request $request, EmailTemplate $template)
157
+	{
158
+		if ($template->getDefaultAction() === EmailTemplate::ACTION_CREATED && $this->checkAccountCreated($request)) {
159
+			$this->showConfirmation($request, $template, 'close-confirmations/account-created.tpl');
160
+
161
+			return true;
162
+		}
163
+
164
+		return false;
165
+	}
166
+
167
+	protected function checkAccountCreated(Request $request)
168
+	{
169
+		if (!WebRequest::postBoolean('createOverride')) {
170
+			$parameters = array(
171
+				'action'  => 'query',
172
+				'list'    => 'users',
173
+				'format'  => 'php',
174
+				'ususers' => $request->getName(),
175
+			);
176
+
177
+			// FIXME: domains!
178
+			/** @var Domain $domain */
179
+			$domain = Domain::getById(1, $this->getDatabase());
180
+
181
+			$content = $this->getHttpHelper()->get($domain->getWikiApiPath(), $parameters);
182
+
183
+			$apiResult = unserialize($content);
184
+			$exists = !isset($apiResult['query']['users']['0']['missing']);
185
+
186
+			if (!$exists) {
187
+				return true;
188
+			}
189
+		}
190
+
191
+		return false;
192
+	}
193
+
194
+	/**
195
+	 * @param Request $request
196
+	 * @param string  $mailText
197
+	 * @param User    $currentUser
198
+	 * @param boolean $ccMailingList
199
+	 */
200
+	protected function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
201
+	{
202
+		if (
203
+		($request->getEmail() != $this->getSiteConfiguration()->getDataClearEmail()) &&
204
+		($request->getIp() != $this->getSiteConfiguration()->getDataClearIp())
205
+		) {
206
+			$requestEmailHelper = new RequestEmailHelper($this->getEmailHelper());
207
+			$requestEmailHelper->sendMail($request, $mailText, $currentUser, $ccMailingList);
208
+
209
+			$request->setEmailSent(true);
210
+			$request->save();
211
+		}
212
+	}
213
+
214
+	/**
215
+	 * @param Request       $request
216
+	 * @param EmailTemplate $template
217
+	 * @param string        $templateName
218
+	 *
219
+	 * @throws Exception
220
+	 * @return void
221
+	 */
222
+	protected function showConfirmation(Request $request, EmailTemplate $template, $templateName)
223
+	{
224
+		$this->assignCSRFToken();
225
+
226
+		$this->assign('request', $request->getId());
227
+		$this->assign('template', $template->getId());
228
+
229
+		$this->assign('updateversion', $request->getUpdateVersion());
230
+
231
+		$this->assign('emailSentOverride', WebRequest::postBoolean('emailSentOverride') ? 'true' : 'false');
232
+		$this->assign('reserveOverride', WebRequest::postBoolean('reserveOverride') ? 'true' : 'false');
233
+		$this->assign('createOverride', WebRequest::postBoolean('createOverride') ? 'true' : 'false');
234
+		$this->assign('skipAutoWelcome', WebRequest::postBoolean('skipAutoWelcome') ? 'true' : 'false');
235
+
236
+		$this->skipAlerts();
237
+
238
+		$this->setTemplate($templateName);
239
+	}
240
+
241
+	/**
242
+	 * @param string $action
243
+	 * @param int|null   $parentTaskId
244
+	 *
245
+	 * @throws ApplicationLogicException
246
+	 */
247
+	final protected function processWelcome(string $action, ?int $parentTaskId): void
248
+	{
249
+		$database = $this->getDatabase();
250
+		$currentUser = User::getCurrent($database);
251
+		$preferencesManager = PreferenceManager::getForCurrent($database);
252
+
253
+		if ($action !== EmailTemplate::ACTION_CREATED) {
254
+			return;
255
+		}
256
+
257
+		if ($preferencesManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE) === null) {
258
+			return;
259
+		}
260
+
261
+		$oauth = new OAuthUserHelper($currentUser, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
262
+		if (!$oauth->canWelcome()) {
263
+			return;
264
+		}
265
+
266
+		if (WebRequest::postBoolean('skipAutoWelcome')) {
267
+			return;
268
+		}
269
+
270
+		$this->enqueueWelcomeTask($this->getRequest($database), $parentTaskId, $currentUser, $database);
271
+	}
272 272
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/RequestActionBase.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -19,55 +19,55 @@
 block discarded – undo
19 19
 
20 20
 abstract class RequestActionBase extends InternalPageBase
21 21
 {
22
-    /**
23
-     * @param PdoDatabase $database
24
-     *
25
-     * @return Request
26
-     * @throws ApplicationLogicException
27
-     */
28
-    protected function getRequest(PdoDatabase $database)
29
-    {
30
-        $requestId = WebRequest::postInt('request');
31
-        if ($requestId === null) {
32
-            throw new ApplicationLogicException('Request ID not found');
33
-        }
22
+	/**
23
+	 * @param PdoDatabase $database
24
+	 *
25
+	 * @return Request
26
+	 * @throws ApplicationLogicException
27
+	 */
28
+	protected function getRequest(PdoDatabase $database)
29
+	{
30
+		$requestId = WebRequest::postInt('request');
31
+		if ($requestId === null) {
32
+			throw new ApplicationLogicException('Request ID not found');
33
+		}
34 34
 
35
-        /** @var Request $request */
36
-        $request = Request::getById($requestId, $database);
35
+		/** @var Request $request */
36
+		$request = Request::getById($requestId, $database);
37 37
 
38
-        if ($request === false) {
39
-            throw new ApplicationLogicException('Request not found');
40
-        }
38
+		if ($request === false) {
39
+			throw new ApplicationLogicException('Request not found');
40
+		}
41 41
 
42
-        return $request;
43
-    }
42
+		return $request;
43
+	}
44 44
 
45
-    final protected function checkPosted()
46
-    {
47
-        // if the request was not posted, send the user away.
48
-        if (!WebRequest::wasPosted()) {
49
-            throw new ApplicationLogicException('This page does not support GET methods.');
50
-        }
45
+	final protected function checkPosted()
46
+	{
47
+		// if the request was not posted, send the user away.
48
+		if (!WebRequest::wasPosted()) {
49
+			throw new ApplicationLogicException('This page does not support GET methods.');
50
+		}
51 51
 
52
-        // validate the CSRF token
53
-        $this->validateCSRFToken();
54
-    }
52
+		// validate the CSRF token
53
+		$this->validateCSRFToken();
54
+	}
55 55
 
56
-    /**
57
-     * @param Request     $request
58
-     * @param             $parentTaskId
59
-     * @param User        $user
60
-     * @param PdoDatabase $database
61
-     */
62
-    protected function enqueueWelcomeTask(Request $request, $parentTaskId, User $user, PdoDatabase $database)
63
-    {
64
-        $welcomeTask = new JobQueue();
65
-        $welcomeTask->setDomain(1); // FIXME: domains!
66
-        $welcomeTask->setTask(WelcomeUserTask::class);
67
-        $welcomeTask->setRequest($request->getId());
68
-        $welcomeTask->setParent($parentTaskId);
69
-        $welcomeTask->setTriggerUserId($user->getId());
70
-        $welcomeTask->setDatabase($database);
71
-        $welcomeTask->save();
72
-    }
56
+	/**
57
+	 * @param Request     $request
58
+	 * @param             $parentTaskId
59
+	 * @param User        $user
60
+	 * @param PdoDatabase $database
61
+	 */
62
+	protected function enqueueWelcomeTask(Request $request, $parentTaskId, User $user, PdoDatabase $database)
63
+	{
64
+		$welcomeTask = new JobQueue();
65
+		$welcomeTask->setDomain(1); // FIXME: domains!
66
+		$welcomeTask->setTask(WelcomeUserTask::class);
67
+		$welcomeTask->setRequest($request->getId());
68
+		$welcomeTask->setParent($parentTaskId);
69
+		$welcomeTask->setTriggerUserId($user->getId());
70
+		$welcomeTask->setDatabase($database);
71
+		$welcomeTask->save();
72
+	}
73 73
 }
74 74
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageDeferRequest.php 1 patch
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -21,85 +21,85 @@
 block discarded – undo
21 21
 
22 22
 class PageDeferRequest extends RequestActionBase
23 23
 {
24
-    /**
25
-     * Main function for this page, when no specific actions are called.
26
-     * @throws ApplicationLogicException
27
-     */
28
-    protected function main()
29
-    {
30
-        $this->checkPosted();
31
-        $database = $this->getDatabase();
32
-        $request = $this->getRequest($database);
33
-        $currentUser = User::getCurrent($database);
34
-
35
-        $target = WebRequest::postString('target');
36
-
37
-        // FIXME: domains!
38
-        $requestQueue = RequestQueue::getByApiName($database, $target, 1);
39
-
40
-        if ($requestQueue === false) {
41
-            throw new ApplicationLogicException('Defer target not valid');
42
-        }
43
-
44
-        if ($request->getQueue() == $requestQueue->getId() && $request->getStatus() == RequestStatus::OPEN) {
45
-            SessionAlert::warning('This request is already in the specified queue.');
46
-            $this->redirect('viewRequest', null, array('id' => $request->getId()));
47
-
48
-            return;
49
-        }
50
-
51
-        $closureDate = $request->getClosureDate();
52
-        $date = new DateTime();
53
-        $date->modify("-7 days");
54
-
55
-        if ($request->getStatus() == RequestStatus::CLOSED && $closureDate < $date) {
56
-            if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
57
-                throw new ApplicationLogicException(
58
-                    "You are not allowed to re-open a request that has been closed for over a week.");
59
-            }
60
-        }
61
-
62
-        if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
63
-            if (!$this->barrierTest('reopenClearedRequest', $currentUser, 'RequestData')) {
64
-                throw new ApplicationLogicException(
65
-                    "You are not allowed to re-open a request for which the private data has been purged.");
66
-            }
67
-        }
68
-
69
-        if ($request->getStatus() === RequestStatus::JOBQUEUE) {
70
-            /** @var JobQueue[] $pendingJobs */
71
-            // FIXME: domains
72
-            $pendingJobs = JobQueueSearchHelper::get($database, 1)
73
-                ->byRequest($request->getId())
74
-                ->statusIn([
75
-                    JobQueue::STATUS_QUEUED,
76
-                    JobQueue::STATUS_READY,
77
-                    JobQueue::STATUS_WAITING,
78
-                ])
79
-                ->fetch();
80
-
81
-            foreach ($pendingJobs as $job) {
82
-                $job->setStatus(JobQueue::STATUS_CANCELLED);
83
-                $job->setError('Cancelled by request deferral');
84
-                $job->save();
85
-
86
-                Logger::backgroundJobCancelled($database, $job);
87
-            }
88
-        }
89
-
90
-        $request->setReserved(null);
91
-        $request->setStatus(RequestStatus::OPEN);
92
-        $request->setQueue($requestQueue->getId());
93
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
94
-        $request->save();
95
-
96
-        Logger::deferRequest($database, $request, $requestQueue->getLogName());
97
-
98
-        $this->getNotificationHelper()->requestDeferred($request);
99
-
100
-        $deto = htmlentities($requestQueue->getDisplayName(), ENT_COMPAT, 'UTF-8');
101
-        SessionAlert::success("Request {$request->getId()} deferred to {$deto}");
102
-
103
-        $this->redirect();
104
-    }
24
+	/**
25
+	 * Main function for this page, when no specific actions are called.
26
+	 * @throws ApplicationLogicException
27
+	 */
28
+	protected function main()
29
+	{
30
+		$this->checkPosted();
31
+		$database = $this->getDatabase();
32
+		$request = $this->getRequest($database);
33
+		$currentUser = User::getCurrent($database);
34
+
35
+		$target = WebRequest::postString('target');
36
+
37
+		// FIXME: domains!
38
+		$requestQueue = RequestQueue::getByApiName($database, $target, 1);
39
+
40
+		if ($requestQueue === false) {
41
+			throw new ApplicationLogicException('Defer target not valid');
42
+		}
43
+
44
+		if ($request->getQueue() == $requestQueue->getId() && $request->getStatus() == RequestStatus::OPEN) {
45
+			SessionAlert::warning('This request is already in the specified queue.');
46
+			$this->redirect('viewRequest', null, array('id' => $request->getId()));
47
+
48
+			return;
49
+		}
50
+
51
+		$closureDate = $request->getClosureDate();
52
+		$date = new DateTime();
53
+		$date->modify("-7 days");
54
+
55
+		if ($request->getStatus() == RequestStatus::CLOSED && $closureDate < $date) {
56
+			if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
57
+				throw new ApplicationLogicException(
58
+					"You are not allowed to re-open a request that has been closed for over a week.");
59
+			}
60
+		}
61
+
62
+		if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
63
+			if (!$this->barrierTest('reopenClearedRequest', $currentUser, 'RequestData')) {
64
+				throw new ApplicationLogicException(
65
+					"You are not allowed to re-open a request for which the private data has been purged.");
66
+			}
67
+		}
68
+
69
+		if ($request->getStatus() === RequestStatus::JOBQUEUE) {
70
+			/** @var JobQueue[] $pendingJobs */
71
+			// FIXME: domains
72
+			$pendingJobs = JobQueueSearchHelper::get($database, 1)
73
+				->byRequest($request->getId())
74
+				->statusIn([
75
+					JobQueue::STATUS_QUEUED,
76
+					JobQueue::STATUS_READY,
77
+					JobQueue::STATUS_WAITING,
78
+				])
79
+				->fetch();
80
+
81
+			foreach ($pendingJobs as $job) {
82
+				$job->setStatus(JobQueue::STATUS_CANCELLED);
83
+				$job->setError('Cancelled by request deferral');
84
+				$job->save();
85
+
86
+				Logger::backgroundJobCancelled($database, $job);
87
+			}
88
+		}
89
+
90
+		$request->setReserved(null);
91
+		$request->setStatus(RequestStatus::OPEN);
92
+		$request->setQueue($requestQueue->getId());
93
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
94
+		$request->save();
95
+
96
+		Logger::deferRequest($database, $request, $requestQueue->getLogName());
97
+
98
+		$this->getNotificationHelper()->requestDeferred($request);
99
+
100
+		$deto = htmlentities($requestQueue->getDisplayName(), ENT_COMPAT, 'UTF-8');
101
+		SessionAlert::success("Request {$request->getId()} deferred to {$deto}");
102
+
103
+		$this->redirect();
104
+	}
105 105
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageComment.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -16,55 +16,55 @@
 block discarded – undo
16 16
 
17 17
 class PageComment extends RequestActionBase
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->checkPosted();
26
-        $database = $this->getDatabase();
27
-        $request = $this->getRequest($database);
19
+	/**
20
+	 * Main function for this page, when no specific actions are called.
21
+	 * @return void
22
+	 */
23
+	protected function main()
24
+	{
25
+		$this->checkPosted();
26
+		$database = $this->getDatabase();
27
+		$request = $this->getRequest($database);
28 28
 
29
-        $commentText = WebRequest::postString('comment');
30
-        if ($commentText === false || $commentText == '') {
31
-            $this->redirect('viewRequest', null, array('id' => $request->getId()));
29
+		$commentText = WebRequest::postString('comment');
30
+		if ($commentText === false || $commentText == '') {
31
+			$this->redirect('viewRequest', null, array('id' => $request->getId()));
32 32
 
33
-            return;
34
-        }
33
+			return;
34
+		}
35 35
 
36
-        //Look for and detect IPv4/IPv6 addresses in comment text, and warn the commenter.
37
-        $ipv4Regex = '/\b' . RegexConstants::IPV4 . '\b/';
38
-        $ipv6Regex = '/\b' . RegexConstants::IPV6 . '\b/';
36
+		//Look for and detect IPv4/IPv6 addresses in comment text, and warn the commenter.
37
+		$ipv4Regex = '/\b' . RegexConstants::IPV4 . '\b/';
38
+		$ipv6Regex = '/\b' . RegexConstants::IPV6 . '\b/';
39 39
 
40
-        $overridePolicy = WebRequest::postBoolean('privpol-check-override');
40
+		$overridePolicy = WebRequest::postBoolean('privpol-check-override');
41 41
 
42
-        if ((preg_match($ipv4Regex, $commentText) || preg_match($ipv6Regex, $commentText)) && !$overridePolicy) {
43
-            $this->assignCSRFToken();
44
-            $this->assign("request", $request);
45
-            $this->assign("comment", $commentText);
46
-            $this->skipAlerts();
47
-            $this->setTemplate("privpol-warning.tpl");
42
+		if ((preg_match($ipv4Regex, $commentText) || preg_match($ipv6Regex, $commentText)) && !$overridePolicy) {
43
+			$this->assignCSRFToken();
44
+			$this->assign("request", $request);
45
+			$this->assign("comment", $commentText);
46
+			$this->skipAlerts();
47
+			$this->setTemplate("privpol-warning.tpl");
48 48
 
49
-            return;
50
-        }
49
+			return;
50
+		}
51 51
 
52
-        $visibility = WebRequest::postString('visibility') ?? 'user';
53
-        if ($visibility !== 'user' && $visibility !== 'admin' && $visibility !== 'checkuser') {
54
-            throw new ApplicationLogicException('Invalid comment visibility');
55
-        }
52
+		$visibility = WebRequest::postString('visibility') ?? 'user';
53
+		if ($visibility !== 'user' && $visibility !== 'admin' && $visibility !== 'checkuser') {
54
+			throw new ApplicationLogicException('Invalid comment visibility');
55
+		}
56 56
 
57
-        $comment = new Comment();
58
-        $comment->setDatabase($database);
57
+		$comment = new Comment();
58
+		$comment->setDatabase($database);
59 59
 
60
-        $comment->setRequest($request->getId());
61
-        $comment->setVisibility($visibility);
62
-        $comment->setUser(User::getCurrent($database)->getId());
63
-        $comment->setComment($commentText);
60
+		$comment->setRequest($request->getId());
61
+		$comment->setVisibility($visibility);
62
+		$comment->setUser(User::getCurrent($database)->getId());
63
+		$comment->setComment($commentText);
64 64
 
65
-        $comment->save();
65
+		$comment->save();
66 66
 
67
-        $this->getNotificationHelper()->commentCreated($comment, $request);
68
-        $this->redirect('viewRequest', null, array('id' => $request->getId()));
69
-    }
67
+		$this->getNotificationHelper()->commentCreated($comment, $request);
68
+		$this->redirect('viewRequest', null, array('id' => $request->getId()));
69
+	}
70 70
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageCustomClose.php 2 patches
Indentation   +397 added lines, -397 removed lines patch added patch discarded remove patch
@@ -30,401 +30,401 @@
 block discarded – undo
30 30
 
31 31
 class PageCustomClose extends PageCloseRequest
32 32
 {
33
-    use RequestData;
34
-
35
-    public const CREATE_OAUTH = 'created-oauth';
36
-    public const CREATE_BOT = 'created-bot';
37
-
38
-    protected function main()
39
-    {
40
-        $database = $this->getDatabase();
41
-
42
-        $request = $this->getRequest($database);
43
-        $currentUser = User::getCurrent($this->getDatabase());
44
-
45
-        if ($request->getStatus() === RequestStatus::CLOSED) {
46
-            throw new ApplicationLogicException('Request is already closed');
47
-        }
48
-
49
-        // Dual-mode page
50
-        if (WebRequest::wasPosted()) {
51
-            $this->validateCSRFToken();
52
-            $success = $this->doCustomClose($currentUser, $request, $database);
53
-
54
-            if ($success) {
55
-                $this->redirect();
56
-            }
57
-        }
58
-        else {
59
-            $this->assignCSRFToken();
60
-            $this->showCustomCloseForm($database, $request);
61
-        }
62
-    }
63
-
64
-    /**
65
-     * @param $database
66
-     *
67
-     * @return Request
68
-     * @throws ApplicationLogicException
69
-     */
70
-    protected function getRequest(PdoDatabase $database)
71
-    {
72
-        $requestId = WebRequest::getInt('request');
73
-        if ($requestId === null) {
74
-            throw new ApplicationLogicException('Request ID not found');
75
-        }
76
-
77
-        /** @var Request $request */
78
-        $request = Request::getById($requestId, $database);
79
-
80
-        if ($request === false) {
81
-            throw new ApplicationLogicException('Request not found');
82
-        }
83
-
84
-        return $request;
85
-    }
86
-
87
-    /**
88
-     * @param PdoDatabase $database
89
-     *
90
-     * @return EmailTemplate|null
91
-     */
92
-    protected function getTemplate(PdoDatabase $database)
93
-    {
94
-        $templateId = WebRequest::getInt('template');
95
-        if ($templateId === null) {
96
-            return null;
97
-        }
98
-
99
-        /** @var EmailTemplate $template */
100
-        $template = EmailTemplate::getById($templateId, $database);
101
-        if ($template === false || !$template->getActive()) {
102
-            return null;
103
-        }
104
-
105
-        return $template;
106
-    }
107
-
108
-    /**
109
-     * @param $database
110
-     * @param $request
111
-     *
112
-     * @throws Exception
113
-     */
114
-    protected function showCustomCloseForm(PdoDatabase $database, Request $request)
115
-    {
116
-        $this->setHtmlTitle("Custom close");
117
-
118
-        $currentUser = User::getCurrent($database);
119
-        $preferencesManager = PreferenceManager::getForCurrent($database);
120
-        $config = $this->getSiteConfiguration();
121
-
122
-        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
123
-        if (!$allowedPrivateData) {
124
-            // we probably shouldn't be showing the user this form if they're not allowed to access private data...
125
-            throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
126
-        }
127
-
128
-        $template = $this->getTemplate($database);
129
-
130
-        // Preload data
131
-        $this->assign('defaultAction', '');
132
-        $this->assign('defaultQueue', null);
133
-        $this->assign('preloadText', '');
134
-        $this->assign('preloadTitle', '');
135
-
136
-        if ($template !== null) {
137
-            $this->assign('defaultAction', $template->getDefaultAction());
138
-            $this->assign('defaultQueue', $template->getQueue());
139
-            $this->assign('preloadText', $template->getText());
140
-            $this->assign('preloadTitle', $template->getName());
141
-        }
142
-
143
-        // Static data
144
-        $this->assign('requestQueues', $requestQueues = RequestQueue::getEnabledQueues($database));
145
-
146
-        // request data
147
-        $this->assign('requestId', $request->getIp());
148
-        $this->assign('updateVersion', $request->getUpdateVersion());
149
-        $this->setupBasicData($request, $config);
150
-        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
151
-        $this->setupPrivateData($request, $config);
152
-        $this->setupRelatedRequests($request, $config, $database);
153
-
154
-        // IP location
155
-        $trustedIp = $this->getXffTrustProvider()->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
156
-        $this->assign('iplocation', $this->getLocationProvider()->getIpLocation($trustedIp));
157
-
158
-        // Confirmations
159
-        $this->assign('confirmEmailAlreadySent', $this->checkEmailAlreadySent($request));
160
-
161
-        $this->assign('canSkipCcMailingList', $this->barrierTest('skipCcMailingList', $currentUser));
162
-
163
-        $this->assign('allowWelcomeSkip', false);
164
-        $this->assign('forceWelcomeSkip', false);
165
-
166
-        $canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $currentUser, 'RequestCreation');
167
-        $canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $currentUser, 'RequestCreation');
168
-
169
-        $oauth = new OAuthUserHelper($currentUser, $this->getDatabase(), $this->getOAuthProtocolHelper(), $config);
170
-
171
-        $welcomeTemplate = $preferencesManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
172
-        if ($welcomeTemplate != 0) {
173
-            $this->assign('allowWelcomeSkip', true);
174
-
175
-            if (!$oauth->canWelcome()) {
176
-                $this->assign('forceWelcomeSkip', true);
177
-            }
178
-        }
179
-
180
-        $this->assign('preferredCreationMode', (int)$preferencesManager->getPreference(PreferenceManager::PREF_CREATION_MODE));
181
-
182
-        // disable options if there's a misconfiguration.
183
-        $canOauthCreate &= $oauth->canCreateAccount();
184
-        $canBotCreate &= $this->getSiteConfiguration()->getCreationBotPassword() !== null;
185
-
186
-        $this->assign('canOauthCreate', $canOauthCreate);
187
-        $this->assign('canBotCreate', $canBotCreate);
188
-
189
-        // template
190
-        $this->setTemplate('custom-close.tpl');
191
-    }
192
-
193
-    /**
194
-     * @param User        $currentUser
195
-     * @param Request     $request
196
-     * @param PdoDatabase $database
197
-     *
198
-     * @throws ApplicationLogicException
199
-     */
200
-    protected function doCustomClose(User $currentUser, Request $request, PdoDatabase $database) : bool
201
-    {
202
-        $messageBody = WebRequest::postString('msgbody');
203
-        if ($messageBody === null || trim($messageBody) === '') {
204
-            throw new ApplicationLogicException('Message body cannot be blank');
205
-        }
206
-
207
-        $ccMailingList = true;
208
-        if ($this->barrierTest('skipCcMailingList', $currentUser)) {
209
-            $ccMailingList = WebRequest::postBoolean('ccMailingList');
210
-        }
211
-
212
-        if ($request->getStatus() === RequestStatus::CLOSED) {
213
-            throw new ApplicationLogicException('Request is already closed');
214
-        }
215
-
216
-        if (!(WebRequest::postBoolean('confirmEmailAlreadySent'))
217
-        ) {
218
-            throw new ApplicationLogicException('Not all confirmations checked');
219
-        }
220
-
221
-        $action = WebRequest::postString('action');
222
-
223
-        if ($action === EmailTemplate::ACTION_CREATED || $action === EmailTemplate::ACTION_NOT_CREATED) {
224
-
225
-            if ($action === EmailTemplate::ACTION_CREATED) {
226
-                if ($this->checkAccountCreated($request)) {
227
-                    $this->assignCSRFToken();
228
-                    $this->showCustomCloseForm($database, $request);
229
-
230
-                    $this->assign("preloadText", $messageBody);
231
-                    $this->assign('preloadAction', $action);
232
-                    $this->assign('ccMailingList', $ccMailingList);
233
-                    $this->assign('showNonExistentAccountWarning', true);
234
-                    $this->assign('skipAutoWelcome', WebRequest::postBoolean('skipAutoWelcome'));
235
-
236
-                    return false;
237
-                }
238
-            }
239
-
240
-            // Close request
241
-            $this->closeRequest($request, $database, $action, $messageBody);
242
-
243
-            $this->processWelcome($action, null);
244
-
245
-            // Send the mail after the save, since save can be rolled back
246
-            $this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
247
-
248
-            return true;
249
-        }
250
-
251
-        if ($action === self::CREATE_OAUTH || $action === self::CREATE_BOT) {
252
-            $this->processAutoCreation($currentUser, $action, $request, $messageBody, $ccMailingList);
253
-
254
-            return true;
255
-        }
256
-
257
-        if ($action === 'mail') {
258
-            $request->setReserved(null);
259
-            $request->setUpdateVersion(WebRequest::postInt('updateversion'));
260
-            $request->save();
261
-
262
-            // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
263
-            // and be rolled back.
264
-
265
-            // Send mail
266
-            $this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
267
-
268
-            Logger::sentMail($database, $request, $messageBody);
269
-            Logger::unreserve($database, $request);
270
-
271
-            $this->getNotificationHelper()->sentMail($request);
272
-            SessionAlert::success("Sent mail to Request {$request->getId()}");
273
-
274
-            return true;
275
-        }
276
-
277
-        $targetQueue = RequestQueue::getByApiName($database, $action, 1);
278
-        if ($targetQueue !== false) {
279
-            // Defer to other state
280
-            $this->deferRequest($request, $database, $targetQueue, $messageBody);
281
-
282
-            // Send the mail after the save, since save can be rolled back
283
-            $this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
284
-
285
-            return true;
286
-        }
287
-
288
-        throw new ApplicationLogicException('Unknown action for custom close.');
289
-    }
290
-
291
-    /**
292
-     * @param Request     $request
293
-     * @param PdoDatabase $database
294
-     * @param string      $action
295
-     * @param string      $messageBody
296
-     *
297
-     * @throws Exception
298
-     * @throws OptimisticLockFailedException
299
-     */
300
-    protected function closeRequest(Request $request, PdoDatabase $database, $action, $messageBody)
301
-    {
302
-        $request->setStatus(RequestStatus::CLOSED);
303
-        $request->setQueue(null);
304
-        $request->setReserved(null);
305
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
306
-        $request->save();
307
-
308
-        // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
309
-        // be rolled back.
310
-
311
-        if ($action == EmailTemplate::ACTION_CREATED) {
312
-            $logCloseType = 'custom-y';
313
-            $notificationCloseType = "Custom, Created";
314
-        }
315
-        else {
316
-            $logCloseType = 'custom-n';
317
-            $notificationCloseType = "Custom, Not Created";
318
-        }
319
-
320
-        Logger::closeRequest($database, $request, $logCloseType, $messageBody);
321
-        $this->getNotificationHelper()->requestClosed($request, $notificationCloseType);
322
-
323
-        $requestName = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
324
-        SessionAlert::success("Request {$request->getId()} ({$requestName}) closed as {$notificationCloseType}.");
325
-    }
326
-
327
-    /**
328
-     * @param Request      $request
329
-     * @param PdoDatabase  $database
330
-     * @param RequestQueue $targetQueue
331
-     * @param string       $messageBody
332
-     *
333
-     * @throws OptimisticLockFailedException
334
-     */
335
-    protected function deferRequest(
336
-        Request $request,
337
-        PdoDatabase $database,
338
-        RequestQueue $targetQueue,
339
-        $messageBody
340
-    ) {
341
-        $request->setStatus(RequestStatus::OPEN);
342
-        $request->setQueue($targetQueue->getId());
343
-        $request->setReserved(null);
344
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
345
-        $request->save();
346
-
347
-        // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
348
-        // and be rolled back.
349
-
350
-        $deferToLog = $targetQueue->getLogName();
351
-        Logger::sentMail($database, $request, $messageBody);
352
-        Logger::deferRequest($database, $request, $deferToLog);
353
-
354
-        $this->getNotificationHelper()->requestDeferredWithMail($request);
355
-
356
-        $deferTo = htmlentities($targetQueue->getDisplayName(), ENT_COMPAT, 'UTF-8');
357
-        SessionAlert::success("Request {$request->getId()} deferred to $deferTo, sending an email.");
358
-    }
359
-
360
-    /**
361
-     * @param User    $currentUser
362
-     * @param string  $action
363
-     * @param Request $request
364
-     * @param string  $messageBody
365
-     * @param bool    $ccMailingList
366
-     *
367
-     * @throws AccessDeniedException
368
-     * @throws ApplicationLogicException
369
-     * @throws OptimisticLockFailedException
370
-     */
371
-    protected function processAutoCreation(User $currentUser, string $action, Request $request, string $messageBody, bool $ccMailingList): void
372
-    {
373
-        $db = $this->getDatabase();
374
-        $oauth = new OAuthUserHelper($currentUser, $db, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
375
-        $canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $currentUser, 'RequestCreation');
376
-        $canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $currentUser, 'RequestCreation');
377
-        $canOauthCreate &= $oauth->canCreateAccount();
378
-        $canBotCreate &= $this->getSiteConfiguration()->getCreationBotPassword() !== null;
379
-
380
-        $creationTaskClass = null;
381
-
382
-        if ($action === self::CREATE_OAUTH) {
383
-            if (!$canOauthCreate) {
384
-                throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
385
-            }
386
-
387
-            $creationTaskClass = UserCreationTask::class;
388
-        }
389
-
390
-        if ($action === self::CREATE_BOT) {
391
-            if (!$canBotCreate) {
392
-                throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
393
-            }
394
-
395
-            $creationTaskClass = BotCreationTask::class;
396
-        }
397
-
398
-        if ($creationTaskClass === null) {
399
-            throw new ApplicationLogicException('Cannot determine creation mode');
400
-        }
401
-
402
-        $request->setStatus(RequestStatus::JOBQUEUE);
403
-        $request->setReserved(null);
404
-        $request->save();
405
-
406
-        $parameters = [
407
-            'emailText' => $messageBody,
408
-            'ccMailingList' => $ccMailingList
409
-        ];
410
-
411
-        $creationTask = new JobQueue();
412
-        $creationTask->setDomain(1); // FIXME: domains!
413
-        $creationTask->setTask($creationTaskClass);
414
-        $creationTask->setRequest($request->getId());
415
-        $creationTask->setTriggerUserId($currentUser->getId());
416
-        $creationTask->setParameters(json_encode($parameters));
417
-        $creationTask->setDatabase($db);
418
-        $creationTask->save();
419
-
420
-        $creationTaskId = $creationTask->getId();
421
-
422
-        Logger::enqueuedJobQueue($db, $request);
423
-        $this->getNotificationHelper()->requestCloseQueued($request, 'Custom, Created');
424
-
425
-        SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
426
-
427
-        // forge this since it is actually a creation.
428
-        $this->processWelcome(EmailTemplate::ACTION_CREATED, $creationTaskId);
429
-    }
33
+	use RequestData;
34
+
35
+	public const CREATE_OAUTH = 'created-oauth';
36
+	public const CREATE_BOT = 'created-bot';
37
+
38
+	protected function main()
39
+	{
40
+		$database = $this->getDatabase();
41
+
42
+		$request = $this->getRequest($database);
43
+		$currentUser = User::getCurrent($this->getDatabase());
44
+
45
+		if ($request->getStatus() === RequestStatus::CLOSED) {
46
+			throw new ApplicationLogicException('Request is already closed');
47
+		}
48
+
49
+		// Dual-mode page
50
+		if (WebRequest::wasPosted()) {
51
+			$this->validateCSRFToken();
52
+			$success = $this->doCustomClose($currentUser, $request, $database);
53
+
54
+			if ($success) {
55
+				$this->redirect();
56
+			}
57
+		}
58
+		else {
59
+			$this->assignCSRFToken();
60
+			$this->showCustomCloseForm($database, $request);
61
+		}
62
+	}
63
+
64
+	/**
65
+	 * @param $database
66
+	 *
67
+	 * @return Request
68
+	 * @throws ApplicationLogicException
69
+	 */
70
+	protected function getRequest(PdoDatabase $database)
71
+	{
72
+		$requestId = WebRequest::getInt('request');
73
+		if ($requestId === null) {
74
+			throw new ApplicationLogicException('Request ID not found');
75
+		}
76
+
77
+		/** @var Request $request */
78
+		$request = Request::getById($requestId, $database);
79
+
80
+		if ($request === false) {
81
+			throw new ApplicationLogicException('Request not found');
82
+		}
83
+
84
+		return $request;
85
+	}
86
+
87
+	/**
88
+	 * @param PdoDatabase $database
89
+	 *
90
+	 * @return EmailTemplate|null
91
+	 */
92
+	protected function getTemplate(PdoDatabase $database)
93
+	{
94
+		$templateId = WebRequest::getInt('template');
95
+		if ($templateId === null) {
96
+			return null;
97
+		}
98
+
99
+		/** @var EmailTemplate $template */
100
+		$template = EmailTemplate::getById($templateId, $database);
101
+		if ($template === false || !$template->getActive()) {
102
+			return null;
103
+		}
104
+
105
+		return $template;
106
+	}
107
+
108
+	/**
109
+	 * @param $database
110
+	 * @param $request
111
+	 *
112
+	 * @throws Exception
113
+	 */
114
+	protected function showCustomCloseForm(PdoDatabase $database, Request $request)
115
+	{
116
+		$this->setHtmlTitle("Custom close");
117
+
118
+		$currentUser = User::getCurrent($database);
119
+		$preferencesManager = PreferenceManager::getForCurrent($database);
120
+		$config = $this->getSiteConfiguration();
121
+
122
+		$allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
123
+		if (!$allowedPrivateData) {
124
+			// we probably shouldn't be showing the user this form if they're not allowed to access private data...
125
+			throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
126
+		}
127
+
128
+		$template = $this->getTemplate($database);
129
+
130
+		// Preload data
131
+		$this->assign('defaultAction', '');
132
+		$this->assign('defaultQueue', null);
133
+		$this->assign('preloadText', '');
134
+		$this->assign('preloadTitle', '');
135
+
136
+		if ($template !== null) {
137
+			$this->assign('defaultAction', $template->getDefaultAction());
138
+			$this->assign('defaultQueue', $template->getQueue());
139
+			$this->assign('preloadText', $template->getText());
140
+			$this->assign('preloadTitle', $template->getName());
141
+		}
142
+
143
+		// Static data
144
+		$this->assign('requestQueues', $requestQueues = RequestQueue::getEnabledQueues($database));
145
+
146
+		// request data
147
+		$this->assign('requestId', $request->getIp());
148
+		$this->assign('updateVersion', $request->getUpdateVersion());
149
+		$this->setupBasicData($request, $config);
150
+		$this->setupReservationDetails($request->getReserved(), $database, $currentUser);
151
+		$this->setupPrivateData($request, $config);
152
+		$this->setupRelatedRequests($request, $config, $database);
153
+
154
+		// IP location
155
+		$trustedIp = $this->getXffTrustProvider()->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
156
+		$this->assign('iplocation', $this->getLocationProvider()->getIpLocation($trustedIp));
157
+
158
+		// Confirmations
159
+		$this->assign('confirmEmailAlreadySent', $this->checkEmailAlreadySent($request));
160
+
161
+		$this->assign('canSkipCcMailingList', $this->barrierTest('skipCcMailingList', $currentUser));
162
+
163
+		$this->assign('allowWelcomeSkip', false);
164
+		$this->assign('forceWelcomeSkip', false);
165
+
166
+		$canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $currentUser, 'RequestCreation');
167
+		$canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $currentUser, 'RequestCreation');
168
+
169
+		$oauth = new OAuthUserHelper($currentUser, $this->getDatabase(), $this->getOAuthProtocolHelper(), $config);
170
+
171
+		$welcomeTemplate = $preferencesManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
172
+		if ($welcomeTemplate != 0) {
173
+			$this->assign('allowWelcomeSkip', true);
174
+
175
+			if (!$oauth->canWelcome()) {
176
+				$this->assign('forceWelcomeSkip', true);
177
+			}
178
+		}
179
+
180
+		$this->assign('preferredCreationMode', (int)$preferencesManager->getPreference(PreferenceManager::PREF_CREATION_MODE));
181
+
182
+		// disable options if there's a misconfiguration.
183
+		$canOauthCreate &= $oauth->canCreateAccount();
184
+		$canBotCreate &= $this->getSiteConfiguration()->getCreationBotPassword() !== null;
185
+
186
+		$this->assign('canOauthCreate', $canOauthCreate);
187
+		$this->assign('canBotCreate', $canBotCreate);
188
+
189
+		// template
190
+		$this->setTemplate('custom-close.tpl');
191
+	}
192
+
193
+	/**
194
+	 * @param User        $currentUser
195
+	 * @param Request     $request
196
+	 * @param PdoDatabase $database
197
+	 *
198
+	 * @throws ApplicationLogicException
199
+	 */
200
+	protected function doCustomClose(User $currentUser, Request $request, PdoDatabase $database) : bool
201
+	{
202
+		$messageBody = WebRequest::postString('msgbody');
203
+		if ($messageBody === null || trim($messageBody) === '') {
204
+			throw new ApplicationLogicException('Message body cannot be blank');
205
+		}
206
+
207
+		$ccMailingList = true;
208
+		if ($this->barrierTest('skipCcMailingList', $currentUser)) {
209
+			$ccMailingList = WebRequest::postBoolean('ccMailingList');
210
+		}
211
+
212
+		if ($request->getStatus() === RequestStatus::CLOSED) {
213
+			throw new ApplicationLogicException('Request is already closed');
214
+		}
215
+
216
+		if (!(WebRequest::postBoolean('confirmEmailAlreadySent'))
217
+		) {
218
+			throw new ApplicationLogicException('Not all confirmations checked');
219
+		}
220
+
221
+		$action = WebRequest::postString('action');
222
+
223
+		if ($action === EmailTemplate::ACTION_CREATED || $action === EmailTemplate::ACTION_NOT_CREATED) {
224
+
225
+			if ($action === EmailTemplate::ACTION_CREATED) {
226
+				if ($this->checkAccountCreated($request)) {
227
+					$this->assignCSRFToken();
228
+					$this->showCustomCloseForm($database, $request);
229
+
230
+					$this->assign("preloadText", $messageBody);
231
+					$this->assign('preloadAction', $action);
232
+					$this->assign('ccMailingList', $ccMailingList);
233
+					$this->assign('showNonExistentAccountWarning', true);
234
+					$this->assign('skipAutoWelcome', WebRequest::postBoolean('skipAutoWelcome'));
235
+
236
+					return false;
237
+				}
238
+			}
239
+
240
+			// Close request
241
+			$this->closeRequest($request, $database, $action, $messageBody);
242
+
243
+			$this->processWelcome($action, null);
244
+
245
+			// Send the mail after the save, since save can be rolled back
246
+			$this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
247
+
248
+			return true;
249
+		}
250
+
251
+		if ($action === self::CREATE_OAUTH || $action === self::CREATE_BOT) {
252
+			$this->processAutoCreation($currentUser, $action, $request, $messageBody, $ccMailingList);
253
+
254
+			return true;
255
+		}
256
+
257
+		if ($action === 'mail') {
258
+			$request->setReserved(null);
259
+			$request->setUpdateVersion(WebRequest::postInt('updateversion'));
260
+			$request->save();
261
+
262
+			// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
263
+			// and be rolled back.
264
+
265
+			// Send mail
266
+			$this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
267
+
268
+			Logger::sentMail($database, $request, $messageBody);
269
+			Logger::unreserve($database, $request);
270
+
271
+			$this->getNotificationHelper()->sentMail($request);
272
+			SessionAlert::success("Sent mail to Request {$request->getId()}");
273
+
274
+			return true;
275
+		}
276
+
277
+		$targetQueue = RequestQueue::getByApiName($database, $action, 1);
278
+		if ($targetQueue !== false) {
279
+			// Defer to other state
280
+			$this->deferRequest($request, $database, $targetQueue, $messageBody);
281
+
282
+			// Send the mail after the save, since save can be rolled back
283
+			$this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
284
+
285
+			return true;
286
+		}
287
+
288
+		throw new ApplicationLogicException('Unknown action for custom close.');
289
+	}
290
+
291
+	/**
292
+	 * @param Request     $request
293
+	 * @param PdoDatabase $database
294
+	 * @param string      $action
295
+	 * @param string      $messageBody
296
+	 *
297
+	 * @throws Exception
298
+	 * @throws OptimisticLockFailedException
299
+	 */
300
+	protected function closeRequest(Request $request, PdoDatabase $database, $action, $messageBody)
301
+	{
302
+		$request->setStatus(RequestStatus::CLOSED);
303
+		$request->setQueue(null);
304
+		$request->setReserved(null);
305
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
306
+		$request->save();
307
+
308
+		// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
309
+		// be rolled back.
310
+
311
+		if ($action == EmailTemplate::ACTION_CREATED) {
312
+			$logCloseType = 'custom-y';
313
+			$notificationCloseType = "Custom, Created";
314
+		}
315
+		else {
316
+			$logCloseType = 'custom-n';
317
+			$notificationCloseType = "Custom, Not Created";
318
+		}
319
+
320
+		Logger::closeRequest($database, $request, $logCloseType, $messageBody);
321
+		$this->getNotificationHelper()->requestClosed($request, $notificationCloseType);
322
+
323
+		$requestName = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
324
+		SessionAlert::success("Request {$request->getId()} ({$requestName}) closed as {$notificationCloseType}.");
325
+	}
326
+
327
+	/**
328
+	 * @param Request      $request
329
+	 * @param PdoDatabase  $database
330
+	 * @param RequestQueue $targetQueue
331
+	 * @param string       $messageBody
332
+	 *
333
+	 * @throws OptimisticLockFailedException
334
+	 */
335
+	protected function deferRequest(
336
+		Request $request,
337
+		PdoDatabase $database,
338
+		RequestQueue $targetQueue,
339
+		$messageBody
340
+	) {
341
+		$request->setStatus(RequestStatus::OPEN);
342
+		$request->setQueue($targetQueue->getId());
343
+		$request->setReserved(null);
344
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
345
+		$request->save();
346
+
347
+		// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
348
+		// and be rolled back.
349
+
350
+		$deferToLog = $targetQueue->getLogName();
351
+		Logger::sentMail($database, $request, $messageBody);
352
+		Logger::deferRequest($database, $request, $deferToLog);
353
+
354
+		$this->getNotificationHelper()->requestDeferredWithMail($request);
355
+
356
+		$deferTo = htmlentities($targetQueue->getDisplayName(), ENT_COMPAT, 'UTF-8');
357
+		SessionAlert::success("Request {$request->getId()} deferred to $deferTo, sending an email.");
358
+	}
359
+
360
+	/**
361
+	 * @param User    $currentUser
362
+	 * @param string  $action
363
+	 * @param Request $request
364
+	 * @param string  $messageBody
365
+	 * @param bool    $ccMailingList
366
+	 *
367
+	 * @throws AccessDeniedException
368
+	 * @throws ApplicationLogicException
369
+	 * @throws OptimisticLockFailedException
370
+	 */
371
+	protected function processAutoCreation(User $currentUser, string $action, Request $request, string $messageBody, bool $ccMailingList): void
372
+	{
373
+		$db = $this->getDatabase();
374
+		$oauth = new OAuthUserHelper($currentUser, $db, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
375
+		$canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $currentUser, 'RequestCreation');
376
+		$canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $currentUser, 'RequestCreation');
377
+		$canOauthCreate &= $oauth->canCreateAccount();
378
+		$canBotCreate &= $this->getSiteConfiguration()->getCreationBotPassword() !== null;
379
+
380
+		$creationTaskClass = null;
381
+
382
+		if ($action === self::CREATE_OAUTH) {
383
+			if (!$canOauthCreate) {
384
+				throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
385
+			}
386
+
387
+			$creationTaskClass = UserCreationTask::class;
388
+		}
389
+
390
+		if ($action === self::CREATE_BOT) {
391
+			if (!$canBotCreate) {
392
+				throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
393
+			}
394
+
395
+			$creationTaskClass = BotCreationTask::class;
396
+		}
397
+
398
+		if ($creationTaskClass === null) {
399
+			throw new ApplicationLogicException('Cannot determine creation mode');
400
+		}
401
+
402
+		$request->setStatus(RequestStatus::JOBQUEUE);
403
+		$request->setReserved(null);
404
+		$request->save();
405
+
406
+		$parameters = [
407
+			'emailText' => $messageBody,
408
+			'ccMailingList' => $ccMailingList
409
+		];
410
+
411
+		$creationTask = new JobQueue();
412
+		$creationTask->setDomain(1); // FIXME: domains!
413
+		$creationTask->setTask($creationTaskClass);
414
+		$creationTask->setRequest($request->getId());
415
+		$creationTask->setTriggerUserId($currentUser->getId());
416
+		$creationTask->setParameters(json_encode($parameters));
417
+		$creationTask->setDatabase($db);
418
+		$creationTask->save();
419
+
420
+		$creationTaskId = $creationTask->getId();
421
+
422
+		Logger::enqueuedJobQueue($db, $request);
423
+		$this->getNotificationHelper()->requestCloseQueued($request, 'Custom, Created');
424
+
425
+		SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
426
+
427
+		// forge this since it is actually a creation.
428
+		$this->processWelcome(EmailTemplate::ACTION_CREATED, $creationTaskId);
429
+	}
430 430
 }
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -54,8 +54,7 @@  discard block
 block discarded – undo
54 54
             if ($success) {
55 55
                 $this->redirect();
56 56
             }
57
-        }
58
-        else {
57
+        } else {
59 58
             $this->assignCSRFToken();
60 59
             $this->showCustomCloseForm($database, $request);
61 60
         }
@@ -311,8 +310,7 @@  discard block
 block discarded – undo
311 310
         if ($action == EmailTemplate::ACTION_CREATED) {
312 311
             $logCloseType = 'custom-y';
313 312
             $notificationCloseType = "Custom, Created";
314
-        }
315
-        else {
313
+        } else {
316 314
             $logCloseType = 'custom-n';
317 315
             $notificationCloseType = "Custom, Not Created";
318 316
         }
Please login to merge, or discard this patch.