Passed
Push — dependabot/composer/php8/media... ( e6d0f9 )
by
unknown
34:23 queued 29:40
created
includes/API/Actions/StatusAction.php 1 patch
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -20,12 +20,12 @@  discard block
 block discarded – undo
20 20
  */
21 21
 class StatusAction extends XmlApiPageBase implements IXmlApiAction
22 22
 {
23
-    public function executeApiAction(DOMElement $apiDocument)
24
-    {
25
-        $statusElement = $this->document->createElement("status");
26
-        $apiDocument->appendChild($statusElement);
23
+	public function executeApiAction(DOMElement $apiDocument)
24
+	{
25
+		$statusElement = $this->document->createElement("status");
26
+		$apiDocument->appendChild($statusElement);
27 27
 
28
-        $query = $this->getDatabase()->prepare(<<<SQL
28
+		$query = $this->getDatabase()->prepare(<<<SQL
29 29
             SELECT /* Api/StatusAction */ COUNT(*) AS count
30 30
             FROM request
31 31
             WHERE
@@ -33,87 +33,87 @@  discard block
 block discarded – undo
33 33
                 AND queue = :queue
34 34
                 AND emailconfirm = 'Confirmed';
35 35
 SQL
36
-        );
37
-
38
-        $allQueues = RequestQueue::getAllQueues($this->getDatabase());
39
-
40
-        foreach ($allQueues as $value) {
41
-            $query->bindValue(":pstatus", RequestStatus::OPEN);
42
-            $query->bindValue(":queue", $value->getId());
43
-            $query->execute();
44
-            $sus = $query->fetchColumn();
45
-            $statusElement->setAttribute($value->getApiName(), $sus);
46
-            $query->closeCursor();
47
-        }
48
-
49
-        // hospital queue
50
-        // FIXME: domains
51
-        $search = RequestSearchHelper::get($this->getDatabase(), 1)->isHospitalised();
52
-
53
-        if ($this->getSiteConfiguration()->getEmailConfirmationEnabled()) {
54
-            $search->withConfirmedEmail();
55
-        }
56
-        $search->getRecordCount($hospitalCount);
57
-        $statusElement->setAttribute('x-hospital', $hospitalCount);
58
-
59
-        // job queue
60
-        // FIXME: domains
61
-        $search = RequestSearchHelper::get($this->getDatabase(), 1)
62
-            ->byStatus(RequestStatus::JOBQUEUE);
63
-
64
-        if ($this->getSiteConfiguration()->getEmailConfirmationEnabled()) {
65
-            $search->withConfirmedEmail();
66
-        }
67
-
68
-        $search->getRecordCount($jobQueueRequestCount);
69
-        $statusElement->setAttribute('x-jobqueue', $jobQueueRequestCount);
70
-
71
-        // bans
72
-        $query = $this->getDatabase()->prepare(<<<SQL
36
+		);
37
+
38
+		$allQueues = RequestQueue::getAllQueues($this->getDatabase());
39
+
40
+		foreach ($allQueues as $value) {
41
+			$query->bindValue(":pstatus", RequestStatus::OPEN);
42
+			$query->bindValue(":queue", $value->getId());
43
+			$query->execute();
44
+			$sus = $query->fetchColumn();
45
+			$statusElement->setAttribute($value->getApiName(), $sus);
46
+			$query->closeCursor();
47
+		}
48
+
49
+		// hospital queue
50
+		// FIXME: domains
51
+		$search = RequestSearchHelper::get($this->getDatabase(), 1)->isHospitalised();
52
+
53
+		if ($this->getSiteConfiguration()->getEmailConfirmationEnabled()) {
54
+			$search->withConfirmedEmail();
55
+		}
56
+		$search->getRecordCount($hospitalCount);
57
+		$statusElement->setAttribute('x-hospital', $hospitalCount);
58
+
59
+		// job queue
60
+		// FIXME: domains
61
+		$search = RequestSearchHelper::get($this->getDatabase(), 1)
62
+			->byStatus(RequestStatus::JOBQUEUE);
63
+
64
+		if ($this->getSiteConfiguration()->getEmailConfirmationEnabled()) {
65
+			$search->withConfirmedEmail();
66
+		}
67
+
68
+		$search->getRecordCount($jobQueueRequestCount);
69
+		$statusElement->setAttribute('x-jobqueue', $jobQueueRequestCount);
70
+
71
+		// bans
72
+		$query = $this->getDatabase()->prepare(<<<SQL
73 73
             SELECT /* Api/StatusAction */ COUNT(*) AS count
74 74
             FROM ban
75 75
             WHERE
76 76
                 (duration > UNIX_TIMESTAMP() OR duration is null)
77 77
                 AND active = 1;
78 78
 SQL
79
-        );
79
+		);
80 80
 
81
-        $query->execute();
82
-        $sus = $query->fetchColumn();
83
-        $statusElement->setAttribute("bans", $sus);
84
-        $query->closeCursor();
81
+		$query->execute();
82
+		$sus = $query->fetchColumn();
83
+		$statusElement->setAttribute("bans", $sus);
84
+		$query->closeCursor();
85 85
 
86
-        $query = $this->getDatabase()->prepare(<<<SQL
86
+		$query = $this->getDatabase()->prepare(<<<SQL
87 87
 SELECT /* Api/StatusAction */ COUNT(*) AS count
88 88
 FROM user WHERE status = :ulevel;
89 89
 SQL
90
-        );
90
+		);
91 91
 
92
-        $query->bindValue(":ulevel", "New");
93
-        $query->execute();
94
-        $sus = $query->fetchColumn();
95
-        $statusElement->setAttribute("usernew", $sus);
96
-        $query->closeCursor();
92
+		$query->bindValue(":ulevel", "New");
93
+		$query->execute();
94
+		$sus = $query->fetchColumn();
95
+		$statusElement->setAttribute("usernew", $sus);
96
+		$query->closeCursor();
97 97
 
98
-        $query = $this->getDatabase()->prepare(<<<SQL
98
+		$query = $this->getDatabase()->prepare(<<<SQL
99 99
 select /* Api/StatusAction */ COUNT(*) from user u
100 100
 inner join userrole ur on u.id = ur.user
101 101
 where u.status = 'Active' and ur.role = :ulevel
102 102
 SQL
103
-        );
104
-
105
-        $query->bindValue(":ulevel", "admin");
106
-        $query->execute();
107
-        $sus = $query->fetchColumn();
108
-        $statusElement->setAttribute("useradmin", $sus);
109
-        $query->closeCursor();
110
-
111
-        $query->bindValue(":ulevel", "user");
112
-        $query->execute();
113
-        $sus = $query->fetchColumn();
114
-        $statusElement->setAttribute("user", $sus);
115
-        $query->closeCursor();
116
-
117
-        return $apiDocument;
118
-    }
103
+		);
104
+
105
+		$query->bindValue(":ulevel", "admin");
106
+		$query->execute();
107
+		$sus = $query->fetchColumn();
108
+		$statusElement->setAttribute("useradmin", $sus);
109
+		$query->closeCursor();
110
+
111
+		$query->bindValue(":ulevel", "user");
112
+		$query->execute();
113
+		$sus = $query->fetchColumn();
114
+		$statusElement->setAttribute("user", $sus);
115
+		$query->closeCursor();
116
+
117
+		return $apiDocument;
118
+	}
119 119
 }
Please login to merge, or discard this patch.
includes/API/Actions/JsUsersAction.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -16,16 +16,16 @@
 block discarded – undo
16 16
 
17 17
 class JsUsersAction extends JsonApiPageBase implements IJsonApiAction
18 18
 {
19
-    public function executeApiAction()
20
-    {
21
-        $userSearchHelper = UserSearchHelper::get($this->getDatabase());
19
+	public function executeApiAction()
20
+	{
21
+		$userSearchHelper = UserSearchHelper::get($this->getDatabase());
22 22
 
23
-        if (WebRequest::getString('all') === null) {
24
-            $userSearchHelper->byStatus(User::STATUS_ACTIVE);
23
+		if (WebRequest::getString('all') === null) {
24
+			$userSearchHelper->byStatus(User::STATUS_ACTIVE);
25 25
 
26
-        }
26
+		}
27 27
 
28
-        $dataset = $userSearchHelper->fetchColumn('username');
29
-        return $dataset;
30
-    }
28
+		$dataset = $userSearchHelper->fetchColumn('username');
29
+		return $dataset;
30
+	}
31 31
 }
Please login to merge, or discard this patch.
includes/API/Actions/JsTemplateConfirmsAction.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -14,19 +14,19 @@
 block discarded – undo
14 14
 
15 15
 class JsTemplateConfirmsAction extends JsonApiPageBase implements IJsonApiAction
16 16
 {
17
-    public function executeApiAction()
18
-    {
19
-        /** @var EmailTemplate[] $templates */
20
-        // FIXME: domains!
21
-        $templates = EmailTemplate::getAllActiveTemplates(null, $this->getDatabase(), 1);
17
+	public function executeApiAction()
18
+	{
19
+		/** @var EmailTemplate[] $templates */
20
+		// FIXME: domains!
21
+		$templates = EmailTemplate::getAllActiveTemplates(null, $this->getDatabase(), 1);
22 22
 
23
-        $dataset = [];
24
-        foreach ($templates as $tpl) {
25
-            if ($tpl->getJsquestion() != "") {
26
-                $dataset[$tpl->getId()] = $tpl->getJsquestion();
27
-            }
28
-        }
23
+		$dataset = [];
24
+		foreach ($templates as $tpl) {
25
+			if ($tpl->getJsquestion() != "") {
26
+				$dataset[$tpl->getId()] = $tpl->getJsquestion();
27
+			}
28
+		}
29 29
 
30
-        return $dataset;
31
-    }
30
+		return $dataset;
31
+	}
32 32
 }
Please login to merge, or discard this patch.
includes/Router/PublicRequestRouter.php 2 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -59,8 +59,7 @@
 block discarded – undo
59 59
         if (count($pathInfo) === 3 && $pathInfo[0] === 'r') {
60 60
             // this request should be routed to the dynamic request form handler
61 61
             return [PageRequestAccount::class, 'dynamic'];
62
-        }
63
-        else {
62
+        } else {
64 63
             return parent::getRouteFromPath($pathInfo);
65 64
         }
66 65
     }
Please login to merge, or discard this patch.
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -17,59 +17,59 @@
 block discarded – undo
17 17
 
18 18
 class PublicRequestRouter extends RequestRouter
19 19
 {
20
-    /**
21
-     * Gets the route map to be used by this request router.
22
-     *
23
-     * @return array
24
-     */
25
-    protected function getRouteMap()
26
-    {
27
-        return array(
28
-            // Page showing a message stating the request has been submitted to our internal queues
29
-            'requestSubmitted'          =>
30
-                array(
31
-                    'class'   => PageRequestSubmitted::class,
32
-                    'actions' => array(),
33
-                ),
34
-            // Page showing a message stating that email confirmation is required to continue
35
-            'emailConfirmationRequired' =>
36
-                array(
37
-                    'class'   => PageEmailConfirmationRequired::class,
38
-                    'actions' => array(),
39
-                ),
40
-            // Action page which handles email confirmation
41
-            'confirmEmail'              =>
42
-                array(
43
-                    'class'   => PageConfirmEmail::class,
44
-                    'actions' => array(),
45
-                ),
46
-            // Page showing the privacy statement
47
-            'privacy'                   =>
48
-                array(
49
-                    'class'   => PagePublicPrivacy::class,
50
-                    'actions' => array(),
51
-                ),
52
-        );
53
-    }
20
+	/**
21
+	 * Gets the route map to be used by this request router.
22
+	 *
23
+	 * @return array
24
+	 */
25
+	protected function getRouteMap()
26
+	{
27
+		return array(
28
+			// Page showing a message stating the request has been submitted to our internal queues
29
+			'requestSubmitted'          =>
30
+				array(
31
+					'class'   => PageRequestSubmitted::class,
32
+					'actions' => array(),
33
+				),
34
+			// Page showing a message stating that email confirmation is required to continue
35
+			'emailConfirmationRequired' =>
36
+				array(
37
+					'class'   => PageEmailConfirmationRequired::class,
38
+					'actions' => array(),
39
+				),
40
+			// Action page which handles email confirmation
41
+			'confirmEmail'              =>
42
+				array(
43
+					'class'   => PageConfirmEmail::class,
44
+					'actions' => array(),
45
+				),
46
+			// Page showing the privacy statement
47
+			'privacy'                   =>
48
+				array(
49
+					'class'   => PagePublicPrivacy::class,
50
+					'actions' => array(),
51
+				),
52
+		);
53
+	}
54 54
 
55
-    /**
56
-     * Gets the default route if no explicit route is requested.
57
-     *
58
-     * @return callable
59
-     */
60
-    protected function getDefaultRoute()
61
-    {
62
-        return array(PageRequestAccount::class, 'main');
63
-    }
55
+	/**
56
+	 * Gets the default route if no explicit route is requested.
57
+	 *
58
+	 * @return callable
59
+	 */
60
+	protected function getDefaultRoute()
61
+	{
62
+		return array(PageRequestAccount::class, 'main');
63
+	}
64 64
 
65
-    public function getRouteFromPath($pathInfo): array
66
-    {
67
-        if (count($pathInfo) === 3 && $pathInfo[0] === 'r') {
68
-            // this request should be routed to the dynamic request form handler
69
-            return [PageRequestAccount::class, 'dynamic'];
70
-        }
71
-        else {
72
-            return parent::getRouteFromPath($pathInfo);
73
-        }
74
-    }
65
+	public function getRouteFromPath($pathInfo): array
66
+	{
67
+		if (count($pathInfo) === 3 && $pathInfo[0] === 'r') {
68
+			// this request should be routed to the dynamic request form handler
69
+			return [PageRequestAccount::class, 'dynamic'];
70
+		}
71
+		else {
72
+			return parent::getRouteFromPath($pathInfo);
73
+		}
74
+	}
75 75
 }
76 76
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Background/Task/BotCreationTask.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -17,20 +17,20 @@
 block discarded – undo
17 17
 
18 18
 class BotCreationTask extends CreationTaskBase
19 19
 {
20
-    /**
21
-     * @return IMediaWikiClient
22
-     */
23
-    protected function getMediaWikiClient()
24
-    {
25
-        // FIXME: domains!
26
-        /** @var Domain $domain */
27
-        $domain = Domain::getById(1, $this->getDatabase());
20
+	/**
21
+	 * @return IMediaWikiClient
22
+	 */
23
+	protected function getMediaWikiClient()
24
+	{
25
+		// FIXME: domains!
26
+		/** @var Domain $domain */
27
+		$domain = Domain::getById(1, $this->getDatabase());
28 28
 
29
-        return new BotMediaWikiClient($this->getSiteConfiguration(), $domain);
30
-    }
29
+		return new BotMediaWikiClient($this->getSiteConfiguration(), $domain);
30
+	}
31 31
 
32
-    protected function getCreationReason(Request $request, User $user)
33
-    {
34
-        return parent::getCreationReason($request, $user) . ', on behalf of [[User:' . $user->getOnWikiName() . ']]';
35
-    }
32
+	protected function getCreationReason(Request $request, User $user)
33
+	{
34
+		return parent::getCreationReason($request, $user) . ', on behalf of [[User:' . $user->getOnWikiName() . ']]';
35
+	}
36 36
 }
37 37
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Background/Task/WelcomeUserTask.php 1 patch
Indentation   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -19,77 +19,77 @@
 block discarded – undo
19 19
 
20 20
 class WelcomeUserTask extends BackgroundTaskBase
21 21
 {
22
-    /** @var Request */
23
-    private $request;
24
-
25
-    public function execute()
26
-    {
27
-        $database = $this->getDatabase();
28
-        $this->request = $this->getRequest();
29
-        $user = $this->getTriggerUser();
30
-        //FIXME: domains
31
-        $userPrefs = new PreferenceManager($database, $user->getId(), 1);
32
-
33
-        $welcomeTemplate = $userPrefs->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
34
-
35
-        if ($welcomeTemplate === null) {
36
-            $this->markFailed('Welcome template not specified');
37
-
38
-            return;
39
-        }
40
-
41
-        /** @var WelcomeTemplate $template */
42
-        $template = WelcomeTemplate::getById($welcomeTemplate, $database);
43
-
44
-        if ($template === false) {
45
-            $this->markFailed('Welcome template missing');
46
-
47
-            return;
48
-        }
49
-
50
-        $oauth = new OAuthUserHelper($user, $database, $this->getOauthProtocolHelper(),
51
-            $this->getSiteConfiguration());
52
-        $mediaWikiHelper = new MediaWikiHelper($oauth, $this->getSiteConfiguration());
53
-
54
-        if ($this->request->getStatus() !== RequestStatus::CLOSED) {
55
-            $this->markFailed('Request is currently open');
56
-
57
-            return;
58
-        }
59
-
60
-        if (!$mediaWikiHelper->checkAccountExists($this->request->getName())) {
61
-            $this->markFailed('Account does not exist!');
62
-
63
-            return;
64
-        }
65
-
66
-        $this->performWelcome($template, $this->request, $user, $mediaWikiHelper);
67
-        $this->markComplete();
68
-    }
69
-
70
-    /**
71
-     * Performs the welcome
72
-     *
73
-     * @param WelcomeTemplate $template
74
-     * @param Request         $request
75
-     * @param User            $user             The user who triggered the job
76
-     * @param MediaWikiHelper $mediaWikiHelper
77
-     */
78
-    private function performWelcome(
79
-        WelcomeTemplate $template,
80
-        Request $request,
81
-        User $user,
82
-        MediaWikiHelper $mediaWikiHelper
83
-    ) {
84
-        $templateText = $template->getBotCodeForWikiSave($request->getName(), $user->getOnWikiName());
85
-
86
-        $mediaWikiHelper->addTalkPageMessage($request->getName(), $template->getSectionHeader(), 'Welcoming user created through [[WP:ACC]]', $templateText);
87
-    }
88
-
89
-    protected function markFailed($reason = null, bool $acknowledged = false)
90
-    {
91
-        $this->getNotificationHelper()->requestWelcomeFailed($this->request, $this->getTriggerUser());
92
-
93
-        parent::markFailed($reason, $acknowledged);
94
-    }
22
+	/** @var Request */
23
+	private $request;
24
+
25
+	public function execute()
26
+	{
27
+		$database = $this->getDatabase();
28
+		$this->request = $this->getRequest();
29
+		$user = $this->getTriggerUser();
30
+		//FIXME: domains
31
+		$userPrefs = new PreferenceManager($database, $user->getId(), 1);
32
+
33
+		$welcomeTemplate = $userPrefs->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
34
+
35
+		if ($welcomeTemplate === null) {
36
+			$this->markFailed('Welcome template not specified');
37
+
38
+			return;
39
+		}
40
+
41
+		/** @var WelcomeTemplate $template */
42
+		$template = WelcomeTemplate::getById($welcomeTemplate, $database);
43
+
44
+		if ($template === false) {
45
+			$this->markFailed('Welcome template missing');
46
+
47
+			return;
48
+		}
49
+
50
+		$oauth = new OAuthUserHelper($user, $database, $this->getOauthProtocolHelper(),
51
+			$this->getSiteConfiguration());
52
+		$mediaWikiHelper = new MediaWikiHelper($oauth, $this->getSiteConfiguration());
53
+
54
+		if ($this->request->getStatus() !== RequestStatus::CLOSED) {
55
+			$this->markFailed('Request is currently open');
56
+
57
+			return;
58
+		}
59
+
60
+		if (!$mediaWikiHelper->checkAccountExists($this->request->getName())) {
61
+			$this->markFailed('Account does not exist!');
62
+
63
+			return;
64
+		}
65
+
66
+		$this->performWelcome($template, $this->request, $user, $mediaWikiHelper);
67
+		$this->markComplete();
68
+	}
69
+
70
+	/**
71
+	 * Performs the welcome
72
+	 *
73
+	 * @param WelcomeTemplate $template
74
+	 * @param Request         $request
75
+	 * @param User            $user             The user who triggered the job
76
+	 * @param MediaWikiHelper $mediaWikiHelper
77
+	 */
78
+	private function performWelcome(
79
+		WelcomeTemplate $template,
80
+		Request $request,
81
+		User $user,
82
+		MediaWikiHelper $mediaWikiHelper
83
+	) {
84
+		$templateText = $template->getBotCodeForWikiSave($request->getName(), $user->getOnWikiName());
85
+
86
+		$mediaWikiHelper->addTalkPageMessage($request->getName(), $template->getSectionHeader(), 'Welcoming user created through [[WP:ACC]]', $templateText);
87
+	}
88
+
89
+	protected function markFailed($reason = null, bool $acknowledged = false)
90
+	{
91
+		$this->getNotificationHelper()->requestWelcomeFailed($this->request, $this->getTriggerUser());
92
+
93
+		parent::markFailed($reason, $acknowledged);
94
+	}
95 95
 }
96 96
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Background/CreationTaskBase.php 1 patch
Indentation   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -21,156 +21,156 @@
 block discarded – undo
21 21
 
22 22
 abstract class CreationTaskBase extends BackgroundTaskBase
23 23
 {
24
-    /** @var Request */
25
-    private $request;
26
-    /**
27
-     * @var MediaWikiHelper
28
-     * Don't use this directly.
29
-     */
30
-    private $mwHelper = null;
31
-
32
-    public function execute()
33
-    {
34
-        $this->request = $this->getRequest();
35
-        $user = $this->getTriggerUser();
36
-        $parameters = $this->getParameters();
37
-
38
-        if ($this->request->getStatus() !== RequestStatus::JOBQUEUE) {
39
-            $this->markCancelled('Request is not deferred to the job queue');
40
-
41
-            return;
42
-        }
43
-
44
-        if ($this->request->getEmailSent() != 0 && !isset($parameters->emailText)) {
45
-            $this->markFailed('Request has already been sent a templated email');
46
-
47
-            return;
48
-        }
49
-
50
-        if ($this->request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
51
-            $this->markFailed('Private data of request has been purged.');
52
-
53
-            return;
54
-        }
55
-
56
-        $emailText = null;
57
-        $ccMailingList = null;
58
-        $logTarget = null;
59
-
60
-        if (isset($parameters->emailText) && isset($parameters->ccMailingList)) {
61
-            $emailText = $parameters->emailText;
62
-            $ccMailingList = $parameters->ccMailingList;
63
-            $logTarget = "custom-y";
64
-        }
65
-
66
-        if ($this->getEmailTemplate() !== null) {
67
-            $emailText = $this->getEmailTemplate()->getText();
68
-            $ccMailingList = false;
69
-            $logTarget = $this->getEmailTemplate()->getId();
70
-        }
71
-
72
-        if ($emailText === null || $ccMailingList === null) {
73
-            $this->markFailed('Unable to get closure email text');
74
-
75
-            return;
76
-        }
77
-
78
-        try {
79
-            $this->performCreation($user);
80
-
81
-            $this->request->setStatus(RequestStatus::CLOSED);
82
-            $this->request->setQueue(null);
83
-            $this->request->setReserved(null);
84
-            $this->request->setEmailSent(true);
85
-            $this->request->save();
86
-
87
-            // Log the closure as the user
88
-            $logComment = $this->getEmailTemplate() === null ? $emailText : null;
89
-            Logger::closeRequest($this->getDatabase(), $this->request, $logTarget, $logComment, $this->getTriggerUser());
90
-
91
-            $requestEmailHelper = new RequestEmailHelper($this->getEmailHelper());
92
-            $requestEmailHelper->sendMail($this->request, $emailText, $this->getTriggerUser(), $ccMailingList);
93
-        }
94
-        catch (Exception $ex) {
95
-            if (mb_strlen($ex->getMessage()) > 255) {
96
-                ExceptionHandler::logExceptionToDisk($ex, $this->getSiteConfiguration());
97
-            }
98
-
99
-            $this->markFailed(substr($ex->getMessage(), 0, 255));
100
-
101
-            return;
102
-        }
103
-
104
-        $this->markComplete();
105
-    }
106
-
107
-    /**
108
-     * @return IMediaWikiClient
109
-     */
110
-    protected abstract function getMediaWikiClient();
111
-
112
-    protected function getMediaWikiHelper()
113
-    {
114
-        if ($this->mwHelper === null) {
115
-            $this->mwHelper = new MediaWikiHelper($this->getMediaWikiClient(), $this->getSiteConfiguration());
116
-        }
117
-
118
-        return $this->mwHelper;
119
-    }
120
-
121
-    /** @noinspection PhpUnusedParameterInspection */
122
-    protected function getCreationReason(Request $request, User $user)
123
-    {
124
-        return 'Requested account at [[WP:ACC]], request #' . $request->getId();
125
-    }
126
-
127
-    /**
128
-     * @param string $name
129
-     *
130
-     * @return bool
131
-     */
132
-    protected function checkAccountExists($name)
133
-    {
134
-        return $this->getMediaWikiHelper()->checkAccountExists($name);
135
-    }
136
-
137
-    protected function markFailed($reason = null, bool $acknowledged = false)
138
-    {
139
-        $this->request->setStatus(RequestStatus::HOSPITAL);
140
-        $this->request->setQueue(null);
141
-        $this->request->save();
142
-
143
-        $this->getNotificationHelper()->requestCreationFailed($this->request, $this->getTriggerUser());
144
-
145
-        Logger::hospitalised($this->getDatabase(), $this->request);
146
-
147
-        // auto-acknowledge failed creation tasks, as these land in the hospital queue anyway.
148
-        parent::markFailed($reason, true);
149
-        Logger::backgroundJobAcknowledged($this->getDatabase(), $this->getJob(), "Auto-acknowledged due to request deferral to hospital queue");
150
-    }
151
-
152
-    /**
153
-     * @param $user
154
-     *
155
-     * @throws ApplicationLogicException
156
-     */
157
-    protected function performCreation($user)
158
-    {
159
-        $mw = $this->getMediaWikiHelper();
160
-
161
-        $reason = $this->getCreationReason($this->request, $user);
162
-
163
-        if ($this->checkAccountExists($this->request->getName())) {
164
-            throw new ApplicationLogicException('Account already exists');
165
-        }
166
-
167
-        $mw->createAccount($this->request->getName(), $this->request->getEmail(), $reason);
168
-
169
-        if (!$this->checkAccountExists($this->request->getName())) {
170
-            throw new ApplicationLogicException('Account creation appeared to succeed but account does not exist.');
171
-        }
172
-
173
-        $this->request->setStatus(RequestStatus::CLOSED);
174
-        $this->request->save();
175
-    }
24
+	/** @var Request */
25
+	private $request;
26
+	/**
27
+	 * @var MediaWikiHelper
28
+	 * Don't use this directly.
29
+	 */
30
+	private $mwHelper = null;
31
+
32
+	public function execute()
33
+	{
34
+		$this->request = $this->getRequest();
35
+		$user = $this->getTriggerUser();
36
+		$parameters = $this->getParameters();
37
+
38
+		if ($this->request->getStatus() !== RequestStatus::JOBQUEUE) {
39
+			$this->markCancelled('Request is not deferred to the job queue');
40
+
41
+			return;
42
+		}
43
+
44
+		if ($this->request->getEmailSent() != 0 && !isset($parameters->emailText)) {
45
+			$this->markFailed('Request has already been sent a templated email');
46
+
47
+			return;
48
+		}
49
+
50
+		if ($this->request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
51
+			$this->markFailed('Private data of request has been purged.');
52
+
53
+			return;
54
+		}
55
+
56
+		$emailText = null;
57
+		$ccMailingList = null;
58
+		$logTarget = null;
59
+
60
+		if (isset($parameters->emailText) && isset($parameters->ccMailingList)) {
61
+			$emailText = $parameters->emailText;
62
+			$ccMailingList = $parameters->ccMailingList;
63
+			$logTarget = "custom-y";
64
+		}
65
+
66
+		if ($this->getEmailTemplate() !== null) {
67
+			$emailText = $this->getEmailTemplate()->getText();
68
+			$ccMailingList = false;
69
+			$logTarget = $this->getEmailTemplate()->getId();
70
+		}
71
+
72
+		if ($emailText === null || $ccMailingList === null) {
73
+			$this->markFailed('Unable to get closure email text');
74
+
75
+			return;
76
+		}
77
+
78
+		try {
79
+			$this->performCreation($user);
80
+
81
+			$this->request->setStatus(RequestStatus::CLOSED);
82
+			$this->request->setQueue(null);
83
+			$this->request->setReserved(null);
84
+			$this->request->setEmailSent(true);
85
+			$this->request->save();
86
+
87
+			// Log the closure as the user
88
+			$logComment = $this->getEmailTemplate() === null ? $emailText : null;
89
+			Logger::closeRequest($this->getDatabase(), $this->request, $logTarget, $logComment, $this->getTriggerUser());
90
+
91
+			$requestEmailHelper = new RequestEmailHelper($this->getEmailHelper());
92
+			$requestEmailHelper->sendMail($this->request, $emailText, $this->getTriggerUser(), $ccMailingList);
93
+		}
94
+		catch (Exception $ex) {
95
+			if (mb_strlen($ex->getMessage()) > 255) {
96
+				ExceptionHandler::logExceptionToDisk($ex, $this->getSiteConfiguration());
97
+			}
98
+
99
+			$this->markFailed(substr($ex->getMessage(), 0, 255));
100
+
101
+			return;
102
+		}
103
+
104
+		$this->markComplete();
105
+	}
106
+
107
+	/**
108
+	 * @return IMediaWikiClient
109
+	 */
110
+	protected abstract function getMediaWikiClient();
111
+
112
+	protected function getMediaWikiHelper()
113
+	{
114
+		if ($this->mwHelper === null) {
115
+			$this->mwHelper = new MediaWikiHelper($this->getMediaWikiClient(), $this->getSiteConfiguration());
116
+		}
117
+
118
+		return $this->mwHelper;
119
+	}
120
+
121
+	/** @noinspection PhpUnusedParameterInspection */
122
+	protected function getCreationReason(Request $request, User $user)
123
+	{
124
+		return 'Requested account at [[WP:ACC]], request #' . $request->getId();
125
+	}
126
+
127
+	/**
128
+	 * @param string $name
129
+	 *
130
+	 * @return bool
131
+	 */
132
+	protected function checkAccountExists($name)
133
+	{
134
+		return $this->getMediaWikiHelper()->checkAccountExists($name);
135
+	}
136
+
137
+	protected function markFailed($reason = null, bool $acknowledged = false)
138
+	{
139
+		$this->request->setStatus(RequestStatus::HOSPITAL);
140
+		$this->request->setQueue(null);
141
+		$this->request->save();
142
+
143
+		$this->getNotificationHelper()->requestCreationFailed($this->request, $this->getTriggerUser());
144
+
145
+		Logger::hospitalised($this->getDatabase(), $this->request);
146
+
147
+		// auto-acknowledge failed creation tasks, as these land in the hospital queue anyway.
148
+		parent::markFailed($reason, true);
149
+		Logger::backgroundJobAcknowledged($this->getDatabase(), $this->getJob(), "Auto-acknowledged due to request deferral to hospital queue");
150
+	}
151
+
152
+	/**
153
+	 * @param $user
154
+	 *
155
+	 * @throws ApplicationLogicException
156
+	 */
157
+	protected function performCreation($user)
158
+	{
159
+		$mw = $this->getMediaWikiHelper();
160
+
161
+		$reason = $this->getCreationReason($this->request, $user);
162
+
163
+		if ($this->checkAccountExists($this->request->getName())) {
164
+			throw new ApplicationLogicException('Account already exists');
165
+		}
166
+
167
+		$mw->createAccount($this->request->getName(), $this->request->getEmail(), $reason);
168
+
169
+		if (!$this->checkAccountExists($this->request->getName())) {
170
+			throw new ApplicationLogicException('Account creation appeared to succeed but account does not exist.');
171
+		}
172
+
173
+		$this->request->setStatus(RequestStatus::CLOSED);
174
+		$this->request->save();
175
+	}
176 176
 }
177 177
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Background/BackgroundTaskBase.php 1 patch
Indentation   +264 added lines, -264 removed lines patch added patch discarded remove patch
@@ -23,268 +23,268 @@
 block discarded – undo
23 23
 
24 24
 abstract class BackgroundTaskBase
25 25
 {
26
-    /** @var JobQueue */
27
-    private $job;
28
-    /** @var PdoDatabase */
29
-    private $database;
30
-    /** @var IOAuthProtocolHelper */
31
-    private $oauthProtocolHelper;
32
-    /** @var SiteConfiguration */
33
-    private $siteConfiguration;
34
-    /** @var IEmailHelper */
35
-    private $emailHelper;
36
-    /** @var HttpHelper */
37
-    private $httpHelper;
38
-    /** @var IrcNotificationHelper */
39
-    private $notificationHelper;
40
-    /** @var User */
41
-    private $triggerUser;
42
-    /** @var Request */
43
-    private $request;
44
-    /** @var EmailTemplate */
45
-    private $emailTemplate = null;
46
-    /** @var mixed */
47
-    private $parameters;
48
-
49
-    /**
50
-     * @return JobQueue
51
-     */
52
-    public function getJob()
53
-    {
54
-        return $this->job;
55
-    }
56
-
57
-    /**
58
-     * @param JobQueue $job
59
-     */
60
-    public function setJob(JobQueue $job)
61
-    {
62
-        $this->job = $job;
63
-    }
64
-
65
-    /**
66
-     * @return PdoDatabase
67
-     */
68
-    public function getDatabase()
69
-    {
70
-        return $this->database;
71
-    }
72
-
73
-    /**
74
-     * @param PdoDatabase $database
75
-     */
76
-    public function setDatabase(PdoDatabase $database)
77
-    {
78
-        $this->database = $database;
79
-    }
80
-
81
-    /**
82
-     * @return IOAuthProtocolHelper
83
-     */
84
-    public function getOauthProtocolHelper()
85
-    {
86
-        return $this->oauthProtocolHelper;
87
-    }
88
-
89
-    /**
90
-     * @param IOAuthProtocolHelper $oauthProtocolHelper
91
-     */
92
-    public function setOauthProtocolHelper(IOAuthProtocolHelper $oauthProtocolHelper)
93
-    {
94
-        $this->oauthProtocolHelper = $oauthProtocolHelper;
95
-    }
96
-
97
-    /**
98
-     * @return SiteConfiguration
99
-     */
100
-    public function getSiteConfiguration()
101
-    {
102
-        return $this->siteConfiguration;
103
-    }
104
-
105
-    /**
106
-     * @param SiteConfiguration $siteConfiguration
107
-     */
108
-    public function setSiteConfiguration(SiteConfiguration $siteConfiguration)
109
-    {
110
-        $this->siteConfiguration = $siteConfiguration;
111
-    }
112
-
113
-    /**
114
-     * @return HttpHelper
115
-     */
116
-    public function getHttpHelper()
117
-    {
118
-        return $this->httpHelper;
119
-    }
120
-
121
-    /**
122
-     * @param HttpHelper $httpHelper
123
-     */
124
-    public function setHttpHelper(HttpHelper $httpHelper)
125
-    {
126
-        $this->httpHelper = $httpHelper;
127
-    }
128
-
129
-    /**
130
-     * @return IEmailHelper
131
-     */
132
-    public function getEmailHelper()
133
-    {
134
-        return $this->emailHelper;
135
-    }
136
-
137
-    /**
138
-     * @param IEmailHelper $emailHelper
139
-     */
140
-    public function setEmailHelper(IEmailHelper $emailHelper)
141
-    {
142
-        $this->emailHelper = $emailHelper;
143
-    }
144
-
145
-    /**
146
-     * @return IrcNotificationHelper
147
-     */
148
-    public function getNotificationHelper()
149
-    {
150
-        return $this->notificationHelper;
151
-    }
152
-
153
-    /**
154
-     * @param IrcNotificationHelper $notificationHelper
155
-     */
156
-    public function setNotificationHelper($notificationHelper)
157
-    {
158
-        $this->notificationHelper = $notificationHelper;
159
-    }
160
-
161
-    /**
162
-     * @return void
163
-     */
164
-    protected abstract function execute();
165
-
166
-    public function run()
167
-    {
168
-        $this->triggerUser = User::getById($this->job->getTriggerUserId(), $this->getDatabase());
169
-
170
-        if ($this->triggerUser === false) {
171
-            throw new ApplicationLogicException('Cannot locate trigger user');
172
-        }
173
-
174
-        $this->request = Request::getById($this->job->getRequest(), $this->getDatabase());
175
-
176
-        if ($this->request === false) {
177
-            throw new ApplicationLogicException('Cannot locate request');
178
-        }
179
-
180
-        if ($this->job->getEmailTemplate() !== null) {
181
-            $this->emailTemplate = EmailTemplate::getById($this->job->getEmailTemplate(), $this->getDatabase());
182
-
183
-            if ($this->emailTemplate === false) {
184
-                throw new ApplicationLogicException('Cannot locate email template');
185
-            }
186
-        }
187
-
188
-        if ($this->job->getParameters() !== null) {
189
-            $this->parameters = json_decode($this->job->getParameters());
190
-
191
-            if (json_last_error() !== JSON_ERROR_NONE) {
192
-                throw new ApplicationLogicException('JSON decode: ' . json_last_error_msg());
193
-            }
194
-        }
195
-
196
-        // Should we wait for a parent job?
197
-        if ($this->job->getParent() !== null) {
198
-            /** @var JobQueue $parentJob */
199
-            $parentJob = JobQueue::getById($this->job->getParent(), $this->getDatabase());
200
-
201
-            if ($parentJob === false) {
202
-                $this->markFailed("Parent job could not be found");
203
-                return;
204
-            }
205
-
206
-            switch ($parentJob->getStatus()) {
207
-                case JobQueue::STATUS_CANCELLED:
208
-                case JobQueue::STATUS_FAILED:
209
-                    $this->markCancelled('Parent job failed/cancelled');
210
-                    return;
211
-                case JobQueue::STATUS_WAITING:
212
-                case JobQueue::STATUS_READY:
213
-                case JobQueue::STATUS_QUEUED:
214
-                case JobQueue::STATUS_RUNNING:
215
-                case JobQueue::STATUS_HELD:
216
-                    // Defer to next execution
217
-                    $this->job->setStatus(JobQueue::STATUS_READY);
218
-                    $this->job->save();
219
-                    return;
220
-                case JobQueue::STATUS_COMPLETE:
221
-                    // do nothing
222
-                    break;
223
-            }
224
-        }
225
-
226
-        $this->execute();
227
-    }
228
-
229
-    protected function markComplete()
230
-    {
231
-        $this->job->setStatus(JobQueue::STATUS_COMPLETE);
232
-        $this->job->setError(null);
233
-        $this->job->setAcknowledged(null);
234
-        $this->job->save();
235
-
236
-        Logger::backgroundJobComplete($this->getDatabase(), $this->getJob());
237
-    }
238
-
239
-    protected function markCancelled($reason = null)
240
-    {
241
-        $this->job->setStatus(JobQueue::STATUS_CANCELLED);
242
-        $this->job->setError($reason);
243
-        $this->job->setAcknowledged(null);
244
-        $this->job->save();
245
-
246
-        Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
247
-    }
248
-
249
-    protected function markFailed($reason = null, bool $acknowledged = false)
250
-    {
251
-        $this->job->setStatus(JobQueue::STATUS_FAILED);
252
-        $this->job->setError($reason);
253
-        $this->job->setAcknowledged($acknowledged ? 1 : 0);
254
-        $this->job->save();
255
-
256
-        Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
257
-    }
258
-
259
-    /**
260
-     * @return User
261
-     */
262
-    public function getTriggerUser()
263
-    {
264
-        return $this->triggerUser;
265
-    }
266
-
267
-    /**
268
-     * @return Request
269
-     */
270
-    public function getRequest()
271
-    {
272
-        return $this->request;
273
-    }
274
-
275
-    /**
276
-     * @return EmailTemplate
277
-     */
278
-    public function getEmailTemplate()
279
-    {
280
-        return $this->emailTemplate;
281
-    }
282
-
283
-    /**
284
-     * @return mixed
285
-     */
286
-    public function getParameters()
287
-    {
288
-        return $this->parameters;
289
-    }
26
+	/** @var JobQueue */
27
+	private $job;
28
+	/** @var PdoDatabase */
29
+	private $database;
30
+	/** @var IOAuthProtocolHelper */
31
+	private $oauthProtocolHelper;
32
+	/** @var SiteConfiguration */
33
+	private $siteConfiguration;
34
+	/** @var IEmailHelper */
35
+	private $emailHelper;
36
+	/** @var HttpHelper */
37
+	private $httpHelper;
38
+	/** @var IrcNotificationHelper */
39
+	private $notificationHelper;
40
+	/** @var User */
41
+	private $triggerUser;
42
+	/** @var Request */
43
+	private $request;
44
+	/** @var EmailTemplate */
45
+	private $emailTemplate = null;
46
+	/** @var mixed */
47
+	private $parameters;
48
+
49
+	/**
50
+	 * @return JobQueue
51
+	 */
52
+	public function getJob()
53
+	{
54
+		return $this->job;
55
+	}
56
+
57
+	/**
58
+	 * @param JobQueue $job
59
+	 */
60
+	public function setJob(JobQueue $job)
61
+	{
62
+		$this->job = $job;
63
+	}
64
+
65
+	/**
66
+	 * @return PdoDatabase
67
+	 */
68
+	public function getDatabase()
69
+	{
70
+		return $this->database;
71
+	}
72
+
73
+	/**
74
+	 * @param PdoDatabase $database
75
+	 */
76
+	public function setDatabase(PdoDatabase $database)
77
+	{
78
+		$this->database = $database;
79
+	}
80
+
81
+	/**
82
+	 * @return IOAuthProtocolHelper
83
+	 */
84
+	public function getOauthProtocolHelper()
85
+	{
86
+		return $this->oauthProtocolHelper;
87
+	}
88
+
89
+	/**
90
+	 * @param IOAuthProtocolHelper $oauthProtocolHelper
91
+	 */
92
+	public function setOauthProtocolHelper(IOAuthProtocolHelper $oauthProtocolHelper)
93
+	{
94
+		$this->oauthProtocolHelper = $oauthProtocolHelper;
95
+	}
96
+
97
+	/**
98
+	 * @return SiteConfiguration
99
+	 */
100
+	public function getSiteConfiguration()
101
+	{
102
+		return $this->siteConfiguration;
103
+	}
104
+
105
+	/**
106
+	 * @param SiteConfiguration $siteConfiguration
107
+	 */
108
+	public function setSiteConfiguration(SiteConfiguration $siteConfiguration)
109
+	{
110
+		$this->siteConfiguration = $siteConfiguration;
111
+	}
112
+
113
+	/**
114
+	 * @return HttpHelper
115
+	 */
116
+	public function getHttpHelper()
117
+	{
118
+		return $this->httpHelper;
119
+	}
120
+
121
+	/**
122
+	 * @param HttpHelper $httpHelper
123
+	 */
124
+	public function setHttpHelper(HttpHelper $httpHelper)
125
+	{
126
+		$this->httpHelper = $httpHelper;
127
+	}
128
+
129
+	/**
130
+	 * @return IEmailHelper
131
+	 */
132
+	public function getEmailHelper()
133
+	{
134
+		return $this->emailHelper;
135
+	}
136
+
137
+	/**
138
+	 * @param IEmailHelper $emailHelper
139
+	 */
140
+	public function setEmailHelper(IEmailHelper $emailHelper)
141
+	{
142
+		$this->emailHelper = $emailHelper;
143
+	}
144
+
145
+	/**
146
+	 * @return IrcNotificationHelper
147
+	 */
148
+	public function getNotificationHelper()
149
+	{
150
+		return $this->notificationHelper;
151
+	}
152
+
153
+	/**
154
+	 * @param IrcNotificationHelper $notificationHelper
155
+	 */
156
+	public function setNotificationHelper($notificationHelper)
157
+	{
158
+		$this->notificationHelper = $notificationHelper;
159
+	}
160
+
161
+	/**
162
+	 * @return void
163
+	 */
164
+	protected abstract function execute();
165
+
166
+	public function run()
167
+	{
168
+		$this->triggerUser = User::getById($this->job->getTriggerUserId(), $this->getDatabase());
169
+
170
+		if ($this->triggerUser === false) {
171
+			throw new ApplicationLogicException('Cannot locate trigger user');
172
+		}
173
+
174
+		$this->request = Request::getById($this->job->getRequest(), $this->getDatabase());
175
+
176
+		if ($this->request === false) {
177
+			throw new ApplicationLogicException('Cannot locate request');
178
+		}
179
+
180
+		if ($this->job->getEmailTemplate() !== null) {
181
+			$this->emailTemplate = EmailTemplate::getById($this->job->getEmailTemplate(), $this->getDatabase());
182
+
183
+			if ($this->emailTemplate === false) {
184
+				throw new ApplicationLogicException('Cannot locate email template');
185
+			}
186
+		}
187
+
188
+		if ($this->job->getParameters() !== null) {
189
+			$this->parameters = json_decode($this->job->getParameters());
190
+
191
+			if (json_last_error() !== JSON_ERROR_NONE) {
192
+				throw new ApplicationLogicException('JSON decode: ' . json_last_error_msg());
193
+			}
194
+		}
195
+
196
+		// Should we wait for a parent job?
197
+		if ($this->job->getParent() !== null) {
198
+			/** @var JobQueue $parentJob */
199
+			$parentJob = JobQueue::getById($this->job->getParent(), $this->getDatabase());
200
+
201
+			if ($parentJob === false) {
202
+				$this->markFailed("Parent job could not be found");
203
+				return;
204
+			}
205
+
206
+			switch ($parentJob->getStatus()) {
207
+				case JobQueue::STATUS_CANCELLED:
208
+				case JobQueue::STATUS_FAILED:
209
+					$this->markCancelled('Parent job failed/cancelled');
210
+					return;
211
+				case JobQueue::STATUS_WAITING:
212
+				case JobQueue::STATUS_READY:
213
+				case JobQueue::STATUS_QUEUED:
214
+				case JobQueue::STATUS_RUNNING:
215
+				case JobQueue::STATUS_HELD:
216
+					// Defer to next execution
217
+					$this->job->setStatus(JobQueue::STATUS_READY);
218
+					$this->job->save();
219
+					return;
220
+				case JobQueue::STATUS_COMPLETE:
221
+					// do nothing
222
+					break;
223
+			}
224
+		}
225
+
226
+		$this->execute();
227
+	}
228
+
229
+	protected function markComplete()
230
+	{
231
+		$this->job->setStatus(JobQueue::STATUS_COMPLETE);
232
+		$this->job->setError(null);
233
+		$this->job->setAcknowledged(null);
234
+		$this->job->save();
235
+
236
+		Logger::backgroundJobComplete($this->getDatabase(), $this->getJob());
237
+	}
238
+
239
+	protected function markCancelled($reason = null)
240
+	{
241
+		$this->job->setStatus(JobQueue::STATUS_CANCELLED);
242
+		$this->job->setError($reason);
243
+		$this->job->setAcknowledged(null);
244
+		$this->job->save();
245
+
246
+		Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
247
+	}
248
+
249
+	protected function markFailed($reason = null, bool $acknowledged = false)
250
+	{
251
+		$this->job->setStatus(JobQueue::STATUS_FAILED);
252
+		$this->job->setError($reason);
253
+		$this->job->setAcknowledged($acknowledged ? 1 : 0);
254
+		$this->job->save();
255
+
256
+		Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
257
+	}
258
+
259
+	/**
260
+	 * @return User
261
+	 */
262
+	public function getTriggerUser()
263
+	{
264
+		return $this->triggerUser;
265
+	}
266
+
267
+	/**
268
+	 * @return Request
269
+	 */
270
+	public function getRequest()
271
+	{
272
+		return $this->request;
273
+	}
274
+
275
+	/**
276
+	 * @return EmailTemplate
277
+	 */
278
+	public function getEmailTemplate()
279
+	{
280
+		return $this->emailTemplate;
281
+	}
282
+
283
+	/**
284
+	 * @return mixed
285
+	 */
286
+	public function getParameters()
287
+	{
288
+		return $this->parameters;
289
+	}
290 290
 }
Please login to merge, or discard this patch.
includes/Helpers/MediaWikiHelper.php 2 patches
Indentation   +266 added lines, -266 removed lines patch added patch discarded remove patch
@@ -15,270 +15,270 @@
 block discarded – undo
15 15
 
16 16
 class MediaWikiHelper
17 17
 {
18
-    /**
19
-     * @var IMediaWikiClient
20
-     */
21
-    private $mediaWikiClient;
22
-    /**
23
-     * @var SiteConfiguration
24
-     */
25
-    private $siteConfiguration;
26
-
27
-    /**
28
-     * MediaWikiHelper constructor.
29
-     *
30
-     * @param IMediaWikiClient  $mediaWikiClient
31
-     * @param SiteConfiguration $siteConfiguration
32
-     */
33
-    public function __construct(IMediaWikiClient $mediaWikiClient, SiteConfiguration $siteConfiguration)
34
-    {
35
-        $this->mediaWikiClient = $mediaWikiClient;
36
-        $this->siteConfiguration = $siteConfiguration;
37
-    }
38
-
39
-    /**
40
-     * @todo handle override antispoof and titleblacklist issues
41
-     *
42
-     * @param string $username
43
-     * @param string $emailAddress
44
-     * @param string $reason
45
-     *
46
-     * @throws Exception
47
-     * @throws MediaWikiApiException
48
-     */
49
-    public function createAccount($username, $emailAddress, $reason)
50
-    {
51
-        // get token
52
-        $tokenParams = array(
53
-            'action' => 'query',
54
-            'meta'   => 'tokens',
55
-            'type'   => 'createaccount',
56
-        );
57
-
58
-        $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
59
-
60
-        if (isset($response->error)) {
61
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
62
-        }
63
-
64
-        $token = $response->query->tokens->createaccounttoken;
65
-
66
-        $callback = $this->siteConfiguration->getBaseUrl() . '/internal.php/oauth/createCallback';
67
-
68
-        $checkboxFields = array();
69
-        $requiredFields = array();
70
-        $this->getCreationFieldData($requiredFields, $checkboxFields);
71
-
72
-        $apiCallData = array(
73
-            'action'              => 'createaccount',
74
-            'createreturnurl'     => $callback,
75
-            'createtoken'         => $token,
76
-            'createmessageformat' => 'html',
77
-        );
78
-
79
-        $createParams = array_fill_keys($requiredFields, '') + $apiCallData;
80
-
81
-        $createParams['username'] = $username;
82
-        $createParams['mailpassword'] = true;
83
-        $createParams['email'] = $emailAddress;
84
-        $createParams['reason'] = $reason;
85
-
86
-        $createResponse = $this->mediaWikiClient->doApiCall($createParams, 'POST');
87
-
88
-        if (isset($createResponse->error)) {
89
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
90
-        }
91
-
92
-        if (!isset($createResponse->createaccount) || !isset($createResponse->createaccount->status)) {
93
-            throw new MediaWikiApiException('Unknown error creating account');
94
-        }
95
-
96
-        if ($createResponse->createaccount->status === 'FAIL') {
97
-            throw new MediaWikiApiException($createResponse->createaccount->message);
98
-        }
99
-
100
-        if ($createResponse->createaccount->status === 'PASS') {
101
-            // success!
102
-            return;
103
-        }
104
-
105
-        throw new Exception('API result reported status of ' . $createResponse->createaccount->status);
106
-    }
107
-
108
-    /**
109
-     * @param string $username
110
-     * @param string $title
111
-     * @param        $summary
112
-     * @param string $message
113
-     * @param bool   $createOnly
114
-     *
115
-     * @throws MediaWikiApiException
116
-     */
117
-    public function addTalkPageMessage($username, $title, $summary, $message, $createOnly = true)
118
-    {
119
-        // get token
120
-        $tokenParams = array(
121
-            'action' => 'query',
122
-            'meta'   => 'tokens',
123
-            'type'   => 'csrf',
124
-        );
125
-
126
-        $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
127
-
128
-        if (isset($response->error)) {
129
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
130
-        }
131
-
132
-        $token = $response->query->tokens->csrftoken;
133
-
134
-        if ($token === null) {
135
-            throw new MediaWikiApiException('Edit token could not be acquired');
136
-        }
137
-
138
-        $editParameters = array(
139
-            'action'       => 'edit',
140
-            'title'        => 'User talk:' . $username,
141
-            'section'      => 'new',
142
-            'sectiontitle' => $title,
143
-            'summary'      => $summary,
144
-            'text'         => $message,
145
-            'token'        => $token,
146
-        );
147
-
148
-        if ($createOnly) {
149
-            $editParameters['createonly'] = true;
150
-        }
151
-
152
-        $response = $this->mediaWikiClient->doApiCall($editParameters, 'POST');
153
-
154
-        if (!isset($response->edit)) {
155
-            if (isset($response->error)) {
156
-                throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
157
-            }
158
-
159
-            throw new MediaWikiApiException('Unknown error encountered during editing.');
160
-        }
161
-
162
-        $editResponse = $response->edit;
163
-        if ($editResponse->result === "Success") {
164
-            return;
165
-        }
166
-
167
-        throw new MediaWikiApiException('Edit status unsuccessful: ' . $editResponse->result);
168
-    }
169
-
170
-    public function getCreationFieldData(&$requiredFields, &$checkboxFields)
171
-    {
172
-        // get token
173
-        $params = array(
174
-            'action'         => 'query',
175
-            'meta'           => 'authmanagerinfo',
176
-            'amirequestsfor' => 'create',
177
-        );
178
-
179
-        $response = $this->mediaWikiClient->doApiCall($params, 'GET');
180
-
181
-        if (isset($response->error)) {
182
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
183
-        }
184
-
185
-        $requests = $response->query->authmanagerinfo->requests;
186
-
187
-        // We don't want to deal with these providers ever.
188
-        $discardList = array(
189
-            // Requires a username and password
190
-            'MediaWiki\\Auth\\PasswordAuthenticationRequest',
191
-        );
192
-
193
-        // We require these providers to function
194
-        $requireList = array(
195
-            'MediaWiki\\Auth\\TemporaryPasswordAuthenticationRequest',
196
-            'MediaWiki\\Auth\\UsernameAuthenticationRequest',
197
-            'MediaWiki\\Auth\\UserDataAuthenticationRequest',
198
-            'MediaWiki\\Auth\\CreationReasonAuthenticationRequest',
199
-        );
200
-
201
-        $requiredFields = array();
202
-        // Keep checkbox fields separate, since "required" actually means optional as absent == false.
203
-        $checkboxFields = array();
204
-
205
-        foreach ($requests as $req) {
206
-            // Immediately discard anything that is on the discard list.
207
-            if (in_array($req->id, $discardList)) {
208
-                continue;
209
-            }
210
-
211
-            $required = false;
212
-
213
-            if ($req->required === 'primary-required' && !in_array($req->id, $requireList)) {
214
-                // Only want one.
215
-                continue;
216
-            }
217
-
218
-            if (in_array($req->id, $requireList)) {
219
-                unset($requireList[$req->id]);
220
-                $required = true;
221
-            }
222
-
223
-            if ($req->required === 'required') {
224
-                $required = true;
225
-            }
226
-
227
-            if ($required) {
228
-                foreach ($req->fields as $name => $data) {
229
-                    if ($data->type === 'checkbox') {
230
-                        $checkboxFields[] = $name;
231
-                    }
232
-                    else {
233
-                        $requiredFields[] = $name;
234
-                    }
235
-                }
236
-            }
237
-        }
238
-    }
239
-
240
-    /**
241
-     * @param string $username
242
-     * @return bool
243
-     */
244
-    public function checkAccountExists($username)
245
-    {
246
-        $parameters = array(
247
-            'action'  => 'query',
248
-            'list'    => 'users',
249
-            'format'  => 'php',
250
-            'ususers' => $username,
251
-        );
252
-
253
-        $apiResult = $this->mediaWikiClient->doApiCall($parameters, 'GET');
254
-
255
-        $entry = $apiResult->query->users[0];
256
-        $exists = !isset($entry->missing);
257
-
258
-        return $exists;
259
-    }
260
-
261
-    /**
262
-     * Gets the HTML for the provided wiki-markup
263
-     *
264
-     * @param string $wikiText
265
-     *
266
-     * @return string
267
-     */
268
-    public function getHtmlForWikiText($wikiText)
269
-    {
270
-        $parameters = array(
271
-            'action'             => 'parse',
272
-            'pst'                => true,
273
-            'contentmodel'       => 'wikitext',
274
-            'disablelimitreport' => true,
275
-            'disabletoc'         => true,
276
-            'disableeditsection' => true,
277
-            'text'               => $wikiText,
278
-        );
279
-
280
-        $apiResult = $this->mediaWikiClient->doApiCall($parameters, 'GET');
281
-
282
-        return $apiResult->parse->text->{'*'};
283
-    }
18
+	/**
19
+	 * @var IMediaWikiClient
20
+	 */
21
+	private $mediaWikiClient;
22
+	/**
23
+	 * @var SiteConfiguration
24
+	 */
25
+	private $siteConfiguration;
26
+
27
+	/**
28
+	 * MediaWikiHelper constructor.
29
+	 *
30
+	 * @param IMediaWikiClient  $mediaWikiClient
31
+	 * @param SiteConfiguration $siteConfiguration
32
+	 */
33
+	public function __construct(IMediaWikiClient $mediaWikiClient, SiteConfiguration $siteConfiguration)
34
+	{
35
+		$this->mediaWikiClient = $mediaWikiClient;
36
+		$this->siteConfiguration = $siteConfiguration;
37
+	}
38
+
39
+	/**
40
+	 * @todo handle override antispoof and titleblacklist issues
41
+	 *
42
+	 * @param string $username
43
+	 * @param string $emailAddress
44
+	 * @param string $reason
45
+	 *
46
+	 * @throws Exception
47
+	 * @throws MediaWikiApiException
48
+	 */
49
+	public function createAccount($username, $emailAddress, $reason)
50
+	{
51
+		// get token
52
+		$tokenParams = array(
53
+			'action' => 'query',
54
+			'meta'   => 'tokens',
55
+			'type'   => 'createaccount',
56
+		);
57
+
58
+		$response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
59
+
60
+		if (isset($response->error)) {
61
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
62
+		}
63
+
64
+		$token = $response->query->tokens->createaccounttoken;
65
+
66
+		$callback = $this->siteConfiguration->getBaseUrl() . '/internal.php/oauth/createCallback';
67
+
68
+		$checkboxFields = array();
69
+		$requiredFields = array();
70
+		$this->getCreationFieldData($requiredFields, $checkboxFields);
71
+
72
+		$apiCallData = array(
73
+			'action'              => 'createaccount',
74
+			'createreturnurl'     => $callback,
75
+			'createtoken'         => $token,
76
+			'createmessageformat' => 'html',
77
+		);
78
+
79
+		$createParams = array_fill_keys($requiredFields, '') + $apiCallData;
80
+
81
+		$createParams['username'] = $username;
82
+		$createParams['mailpassword'] = true;
83
+		$createParams['email'] = $emailAddress;
84
+		$createParams['reason'] = $reason;
85
+
86
+		$createResponse = $this->mediaWikiClient->doApiCall($createParams, 'POST');
87
+
88
+		if (isset($createResponse->error)) {
89
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
90
+		}
91
+
92
+		if (!isset($createResponse->createaccount) || !isset($createResponse->createaccount->status)) {
93
+			throw new MediaWikiApiException('Unknown error creating account');
94
+		}
95
+
96
+		if ($createResponse->createaccount->status === 'FAIL') {
97
+			throw new MediaWikiApiException($createResponse->createaccount->message);
98
+		}
99
+
100
+		if ($createResponse->createaccount->status === 'PASS') {
101
+			// success!
102
+			return;
103
+		}
104
+
105
+		throw new Exception('API result reported status of ' . $createResponse->createaccount->status);
106
+	}
107
+
108
+	/**
109
+	 * @param string $username
110
+	 * @param string $title
111
+	 * @param        $summary
112
+	 * @param string $message
113
+	 * @param bool   $createOnly
114
+	 *
115
+	 * @throws MediaWikiApiException
116
+	 */
117
+	public function addTalkPageMessage($username, $title, $summary, $message, $createOnly = true)
118
+	{
119
+		// get token
120
+		$tokenParams = array(
121
+			'action' => 'query',
122
+			'meta'   => 'tokens',
123
+			'type'   => 'csrf',
124
+		);
125
+
126
+		$response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
127
+
128
+		if (isset($response->error)) {
129
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
130
+		}
131
+
132
+		$token = $response->query->tokens->csrftoken;
133
+
134
+		if ($token === null) {
135
+			throw new MediaWikiApiException('Edit token could not be acquired');
136
+		}
137
+
138
+		$editParameters = array(
139
+			'action'       => 'edit',
140
+			'title'        => 'User talk:' . $username,
141
+			'section'      => 'new',
142
+			'sectiontitle' => $title,
143
+			'summary'      => $summary,
144
+			'text'         => $message,
145
+			'token'        => $token,
146
+		);
147
+
148
+		if ($createOnly) {
149
+			$editParameters['createonly'] = true;
150
+		}
151
+
152
+		$response = $this->mediaWikiClient->doApiCall($editParameters, 'POST');
153
+
154
+		if (!isset($response->edit)) {
155
+			if (isset($response->error)) {
156
+				throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
157
+			}
158
+
159
+			throw new MediaWikiApiException('Unknown error encountered during editing.');
160
+		}
161
+
162
+		$editResponse = $response->edit;
163
+		if ($editResponse->result === "Success") {
164
+			return;
165
+		}
166
+
167
+		throw new MediaWikiApiException('Edit status unsuccessful: ' . $editResponse->result);
168
+	}
169
+
170
+	public function getCreationFieldData(&$requiredFields, &$checkboxFields)
171
+	{
172
+		// get token
173
+		$params = array(
174
+			'action'         => 'query',
175
+			'meta'           => 'authmanagerinfo',
176
+			'amirequestsfor' => 'create',
177
+		);
178
+
179
+		$response = $this->mediaWikiClient->doApiCall($params, 'GET');
180
+
181
+		if (isset($response->error)) {
182
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
183
+		}
184
+
185
+		$requests = $response->query->authmanagerinfo->requests;
186
+
187
+		// We don't want to deal with these providers ever.
188
+		$discardList = array(
189
+			// Requires a username and password
190
+			'MediaWiki\\Auth\\PasswordAuthenticationRequest',
191
+		);
192
+
193
+		// We require these providers to function
194
+		$requireList = array(
195
+			'MediaWiki\\Auth\\TemporaryPasswordAuthenticationRequest',
196
+			'MediaWiki\\Auth\\UsernameAuthenticationRequest',
197
+			'MediaWiki\\Auth\\UserDataAuthenticationRequest',
198
+			'MediaWiki\\Auth\\CreationReasonAuthenticationRequest',
199
+		);
200
+
201
+		$requiredFields = array();
202
+		// Keep checkbox fields separate, since "required" actually means optional as absent == false.
203
+		$checkboxFields = array();
204
+
205
+		foreach ($requests as $req) {
206
+			// Immediately discard anything that is on the discard list.
207
+			if (in_array($req->id, $discardList)) {
208
+				continue;
209
+			}
210
+
211
+			$required = false;
212
+
213
+			if ($req->required === 'primary-required' && !in_array($req->id, $requireList)) {
214
+				// Only want one.
215
+				continue;
216
+			}
217
+
218
+			if (in_array($req->id, $requireList)) {
219
+				unset($requireList[$req->id]);
220
+				$required = true;
221
+			}
222
+
223
+			if ($req->required === 'required') {
224
+				$required = true;
225
+			}
226
+
227
+			if ($required) {
228
+				foreach ($req->fields as $name => $data) {
229
+					if ($data->type === 'checkbox') {
230
+						$checkboxFields[] = $name;
231
+					}
232
+					else {
233
+						$requiredFields[] = $name;
234
+					}
235
+				}
236
+			}
237
+		}
238
+	}
239
+
240
+	/**
241
+	 * @param string $username
242
+	 * @return bool
243
+	 */
244
+	public function checkAccountExists($username)
245
+	{
246
+		$parameters = array(
247
+			'action'  => 'query',
248
+			'list'    => 'users',
249
+			'format'  => 'php',
250
+			'ususers' => $username,
251
+		);
252
+
253
+		$apiResult = $this->mediaWikiClient->doApiCall($parameters, 'GET');
254
+
255
+		$entry = $apiResult->query->users[0];
256
+		$exists = !isset($entry->missing);
257
+
258
+		return $exists;
259
+	}
260
+
261
+	/**
262
+	 * Gets the HTML for the provided wiki-markup
263
+	 *
264
+	 * @param string $wikiText
265
+	 *
266
+	 * @return string
267
+	 */
268
+	public function getHtmlForWikiText($wikiText)
269
+	{
270
+		$parameters = array(
271
+			'action'             => 'parse',
272
+			'pst'                => true,
273
+			'contentmodel'       => 'wikitext',
274
+			'disablelimitreport' => true,
275
+			'disabletoc'         => true,
276
+			'disableeditsection' => true,
277
+			'text'               => $wikiText,
278
+		);
279
+
280
+		$apiResult = $this->mediaWikiClient->doApiCall($parameters, 'GET');
281
+
282
+		return $apiResult->parse->text->{'*'};
283
+	}
284 284
 }
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -228,8 +228,7 @@
 block discarded – undo
228 228
                 foreach ($req->fields as $name => $data) {
229 229
                     if ($data->type === 'checkbox') {
230 230
                         $checkboxFields[] = $name;
231
-                    }
232
-                    else {
231
+                    } else {
233 232
                         $requiredFields[] = $name;
234 233
                     }
235 234
                 }
Please login to merge, or discard this patch.