Failed Conditions
Push — newinternal ( b66232...216d62 )
by Simon
16:33 queued 06:35
created
includes/Background/BackgroundTaskBase.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -233,6 +233,9 @@
 block discarded – undo
233 233
         Logger::backgroundJobComplete($this->getDatabase(), $this->getJob());
234 234
     }
235 235
 
236
+    /**
237
+     * @param string $reason
238
+     */
236 239
     protected function markCancelled($reason = null)
237 240
     {
238 241
         $this->job->setStatus(JobQueue::STATUS_CANCELLED);
Please login to merge, or discard this patch.
Indentation   +261 added lines, -261 removed lines patch added patch discarded remove patch
@@ -23,265 +23,265 @@
 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
-        $this->parameters = json_decode($this->job->getParameters());
189
-
190
-        if (json_last_error() !== JSON_ERROR_NONE) {
191
-            throw new ApplicationLogicException('JSON decode: ' . json_last_error_msg());
192
-        }
193
-
194
-        // Should we wait for a parent job?
195
-        if($this->job->getParent() !== null) {
196
-            /** @var JobQueue $parentJob */
197
-            $parentJob = JobQueue::getById($this->job->getParent(), $this->getDatabase());
198
-
199
-            if($parentJob === false) {
200
-                $this->markFailed("Parent job could not be found");
201
-                return;
202
-            }
203
-
204
-            switch ($parentJob->getStatus()) {
205
-                case JobQueue::STATUS_CANCELLED:
206
-                case JobQueue::STATUS_FAILED:
207
-                    $this->markCancelled('Parent job failed/cancelled');
208
-                    return;
209
-                case JobQueue::STATUS_WAITING:
210
-                case JobQueue::STATUS_READY:
211
-                case JobQueue::STATUS_RUNNING:
212
-                case JobQueue::STATUS_HELD:
213
-                    // Defer to next execution
214
-                    $this->job->setStatus(JobQueue::STATUS_READY);
215
-                    $this->job->save();
216
-                    return;
217
-                case JobQueue::STATUS_COMPLETE:
218
-                    // do nothing
219
-                    break;
220
-            }
221
-        }
222
-
223
-        $this->execute();
224
-    }
225
-
226
-    protected function markComplete()
227
-    {
228
-        $this->job->setStatus(JobQueue::STATUS_COMPLETE);
229
-        $this->job->setError(null);
230
-        $this->job->setAcknowledged(null);
231
-        $this->job->save();
232
-
233
-        Logger::backgroundJobComplete($this->getDatabase(), $this->getJob());
234
-    }
235
-
236
-    protected function markCancelled($reason = null)
237
-    {
238
-        $this->job->setStatus(JobQueue::STATUS_CANCELLED);
239
-        $this->job->setError($reason);
240
-        $this->job->setAcknowledged(null);
241
-        $this->job->save();
242
-
243
-        Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
244
-    }
245
-
246
-    protected function markFailed($reason = null)
247
-    {
248
-        $this->job->setStatus(JobQueue::STATUS_FAILED);
249
-        $this->job->setError($reason);
250
-        $this->job->setAcknowledged(0);
251
-        $this->job->save();
252
-
253
-        Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
254
-    }
255
-
256
-    /**
257
-     * @return User
258
-     */
259
-    public function getTriggerUser()
260
-    {
261
-        return $this->triggerUser;
262
-    }
263
-
264
-    /**
265
-     * @return Request
266
-     */
267
-    public function getRequest()
268
-    {
269
-        return $this->request;
270
-    }
271
-
272
-    /**
273
-     * @return EmailTemplate
274
-     */
275
-    public function getEmailTemplate()
276
-    {
277
-        return $this->emailTemplate;
278
-    }
279
-
280
-    /**
281
-     * @return mixed
282
-     */
283
-    public function getParameters()
284
-    {
285
-        return $this->parameters;
286
-    }
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
+		$this->parameters = json_decode($this->job->getParameters());
189
+
190
+		if (json_last_error() !== JSON_ERROR_NONE) {
191
+			throw new ApplicationLogicException('JSON decode: ' . json_last_error_msg());
192
+		}
193
+
194
+		// Should we wait for a parent job?
195
+		if($this->job->getParent() !== null) {
196
+			/** @var JobQueue $parentJob */
197
+			$parentJob = JobQueue::getById($this->job->getParent(), $this->getDatabase());
198
+
199
+			if($parentJob === false) {
200
+				$this->markFailed("Parent job could not be found");
201
+				return;
202
+			}
203
+
204
+			switch ($parentJob->getStatus()) {
205
+				case JobQueue::STATUS_CANCELLED:
206
+				case JobQueue::STATUS_FAILED:
207
+					$this->markCancelled('Parent job failed/cancelled');
208
+					return;
209
+				case JobQueue::STATUS_WAITING:
210
+				case JobQueue::STATUS_READY:
211
+				case JobQueue::STATUS_RUNNING:
212
+				case JobQueue::STATUS_HELD:
213
+					// Defer to next execution
214
+					$this->job->setStatus(JobQueue::STATUS_READY);
215
+					$this->job->save();
216
+					return;
217
+				case JobQueue::STATUS_COMPLETE:
218
+					// do nothing
219
+					break;
220
+			}
221
+		}
222
+
223
+		$this->execute();
224
+	}
225
+
226
+	protected function markComplete()
227
+	{
228
+		$this->job->setStatus(JobQueue::STATUS_COMPLETE);
229
+		$this->job->setError(null);
230
+		$this->job->setAcknowledged(null);
231
+		$this->job->save();
232
+
233
+		Logger::backgroundJobComplete($this->getDatabase(), $this->getJob());
234
+	}
235
+
236
+	protected function markCancelled($reason = null)
237
+	{
238
+		$this->job->setStatus(JobQueue::STATUS_CANCELLED);
239
+		$this->job->setError($reason);
240
+		$this->job->setAcknowledged(null);
241
+		$this->job->save();
242
+
243
+		Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
244
+	}
245
+
246
+	protected function markFailed($reason = null)
247
+	{
248
+		$this->job->setStatus(JobQueue::STATUS_FAILED);
249
+		$this->job->setError($reason);
250
+		$this->job->setAcknowledged(0);
251
+		$this->job->save();
252
+
253
+		Logger::backgroundJobIssue($this->getDatabase(), $this->getJob());
254
+	}
255
+
256
+	/**
257
+	 * @return User
258
+	 */
259
+	public function getTriggerUser()
260
+	{
261
+		return $this->triggerUser;
262
+	}
263
+
264
+	/**
265
+	 * @return Request
266
+	 */
267
+	public function getRequest()
268
+	{
269
+		return $this->request;
270
+	}
271
+
272
+	/**
273
+	 * @return EmailTemplate
274
+	 */
275
+	public function getEmailTemplate()
276
+	{
277
+		return $this->emailTemplate;
278
+	}
279
+
280
+	/**
281
+	 * @return mixed
282
+	 */
283
+	public function getParameters()
284
+	{
285
+		return $this->parameters;
286
+	}
287 287
 }
288 288
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Background/CreationTaskBase.php 2 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -105,6 +105,9 @@  discard block
 block discarded – undo
105 105
         return $this->getMediaWikiHelper()->checkAccountExists($name);
106 106
     }
107 107
 
108
+    /**
109
+     * @param string $reason
110
+     */
108 111
     protected function markFailed($reason = null)
109 112
     {
110 113
         $this->request->setStatus(RequestStatus::HOSPITAL);
@@ -116,7 +119,7 @@  discard block
 block discarded – undo
116 119
     }
117 120
 
118 121
     /**
119
-     * @param $user
122
+     * @param User $user
120 123
      *
121 124
      * @throws ApplicationLogicException
122 125
      */
Please login to merge, or discard this patch.
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -20,123 +20,123 @@
 block discarded – undo
20 20
 
21 21
 abstract class CreationTaskBase extends BackgroundTaskBase
22 22
 {
23
-    /** @var Request */
24
-    private $request;
25
-    /**
26
-     * @var MediaWikiHelper
27
-     * Don't use this directly.
28
-     */
29
-    private $mwHelper = null;
30
-
31
-    public function execute()
32
-    {
33
-        $this->request = $this->getRequest();
34
-        $user = $this->getTriggerUser();
35
-
36
-        if ($this->request->getStatus() !== RequestStatus::JOBQUEUE) {
37
-            $this->markCancelled('Request is not deferred to the job queue');
38
-
39
-            return;
40
-        }
41
-
42
-        if ($this->request->getEmailSent() != 0) {
43
-            $this->markFailed('Request has already been sent an email');
44
-
45
-            return;
46
-        }
47
-
48
-        if ($this->getEmailTemplate() === null) {
49
-            $this->markFailed('No email template specified');
50
-
51
-            return;
52
-        }
53
-
54
-        try {
55
-            $this->performCreation($user);
56
-
57
-            $this->request->setStatus(RequestStatus::CLOSED);
58
-            $this->request->setReserved(null);
59
-            $this->request->save();
60
-
61
-            // Log the closure as the user
62
-            Logger::closeRequest($this->getDatabase(), $this->request, $this->getEmailTemplate()->getId(), null,
63
-                $this->getTriggerUser());
64
-
65
-            $requestEmailHelper = new RequestEmailHelper($this->getEmailHelper());
66
-            $requestEmailHelper->sendMail($this->request, $this->getEmailTemplate()->getText(), $this->getTriggerUser(),
67
-                false);
68
-
69
-            $this->getNotificationHelper()->requestClosed($this->request, $this->getEmailTemplate()->getName());
70
-        }
71
-        catch (Exception $ex) {
72
-            $this->markFailed($ex->getMessage());
73
-
74
-            return;
75
-        }
76
-
77
-        $this->markComplete();
78
-    }
79
-
80
-    /**
81
-     * @return IMediaWikiClient
82
-     */
83
-    protected abstract function getMediaWikiClient();
84
-
85
-    protected function getMediaWikiHelper(){
86
-        if($this->mwHelper === null) {
87
-            $this->mwHelper = new MediaWikiHelper($this->getMediaWikiClient(), $this->getSiteConfiguration());
88
-        }
89
-
90
-        return $this->mwHelper;
91
-    }
92
-
93
-    protected function getCreationReason(Request $request, User $user)
94
-    {
95
-        return 'Requested account at [[WP:ACC]], request #' . $request->getId();
96
-    }
97
-
98
-    /**
99
-     * @param string $name
100
-     *
101
-     * @return bool
102
-     */
103
-    protected function checkAccountExists($name)
104
-    {
105
-        return $this->getMediaWikiHelper()->checkAccountExists($name);
106
-    }
107
-
108
-    protected function markFailed($reason = null)
109
-    {
110
-        $this->request->setStatus(RequestStatus::HOSPITAL);
111
-        $this->request->save();
112
-
113
-        Logger::hospitalised($this->getDatabase(), $this->request);
114
-
115
-        parent::markFailed($reason);
116
-    }
117
-
118
-    /**
119
-     * @param $user
120
-     *
121
-     * @throws ApplicationLogicException
122
-     */
123
-    protected function performCreation($user)
124
-    {
125
-        $mw = $this->getMediaWikiHelper();
126
-
127
-        $reason = $this->getCreationReason($this->request, $user);
23
+	/** @var Request */
24
+	private $request;
25
+	/**
26
+	 * @var MediaWikiHelper
27
+	 * Don't use this directly.
28
+	 */
29
+	private $mwHelper = null;
30
+
31
+	public function execute()
32
+	{
33
+		$this->request = $this->getRequest();
34
+		$user = $this->getTriggerUser();
35
+
36
+		if ($this->request->getStatus() !== RequestStatus::JOBQUEUE) {
37
+			$this->markCancelled('Request is not deferred to the job queue');
38
+
39
+			return;
40
+		}
41
+
42
+		if ($this->request->getEmailSent() != 0) {
43
+			$this->markFailed('Request has already been sent an email');
44
+
45
+			return;
46
+		}
47
+
48
+		if ($this->getEmailTemplate() === null) {
49
+			$this->markFailed('No email template specified');
50
+
51
+			return;
52
+		}
53
+
54
+		try {
55
+			$this->performCreation($user);
56
+
57
+			$this->request->setStatus(RequestStatus::CLOSED);
58
+			$this->request->setReserved(null);
59
+			$this->request->save();
60
+
61
+			// Log the closure as the user
62
+			Logger::closeRequest($this->getDatabase(), $this->request, $this->getEmailTemplate()->getId(), null,
63
+				$this->getTriggerUser());
64
+
65
+			$requestEmailHelper = new RequestEmailHelper($this->getEmailHelper());
66
+			$requestEmailHelper->sendMail($this->request, $this->getEmailTemplate()->getText(), $this->getTriggerUser(),
67
+				false);
68
+
69
+			$this->getNotificationHelper()->requestClosed($this->request, $this->getEmailTemplate()->getName());
70
+		}
71
+		catch (Exception $ex) {
72
+			$this->markFailed($ex->getMessage());
73
+
74
+			return;
75
+		}
76
+
77
+		$this->markComplete();
78
+	}
79
+
80
+	/**
81
+	 * @return IMediaWikiClient
82
+	 */
83
+	protected abstract function getMediaWikiClient();
84
+
85
+	protected function getMediaWikiHelper(){
86
+		if($this->mwHelper === null) {
87
+			$this->mwHelper = new MediaWikiHelper($this->getMediaWikiClient(), $this->getSiteConfiguration());
88
+		}
89
+
90
+		return $this->mwHelper;
91
+	}
92
+
93
+	protected function getCreationReason(Request $request, User $user)
94
+	{
95
+		return 'Requested account at [[WP:ACC]], request #' . $request->getId();
96
+	}
97
+
98
+	/**
99
+	 * @param string $name
100
+	 *
101
+	 * @return bool
102
+	 */
103
+	protected function checkAccountExists($name)
104
+	{
105
+		return $this->getMediaWikiHelper()->checkAccountExists($name);
106
+	}
107
+
108
+	protected function markFailed($reason = null)
109
+	{
110
+		$this->request->setStatus(RequestStatus::HOSPITAL);
111
+		$this->request->save();
112
+
113
+		Logger::hospitalised($this->getDatabase(), $this->request);
114
+
115
+		parent::markFailed($reason);
116
+	}
117
+
118
+	/**
119
+	 * @param $user
120
+	 *
121
+	 * @throws ApplicationLogicException
122
+	 */
123
+	protected function performCreation($user)
124
+	{
125
+		$mw = $this->getMediaWikiHelper();
126
+
127
+		$reason = $this->getCreationReason($this->request, $user);
128 128
 
129
-        if ($this->checkAccountExists($this->request->getName())) {
130
-            throw new ApplicationLogicException('Account already exists');
131
-        }
129
+		if ($this->checkAccountExists($this->request->getName())) {
130
+			throw new ApplicationLogicException('Account already exists');
131
+		}
132 132
 
133
-        $mw->createAccount($this->request->getName(), $this->request->getEmail(), $reason);
133
+		$mw->createAccount($this->request->getName(), $this->request->getEmail(), $reason);
134 134
 
135
-        if (!$this->checkAccountExists($this->request->getName())) {
136
-            throw new ApplicationLogicException('Account creation appeared to succeed but account does not exist.');
137
-        }
135
+		if (!$this->checkAccountExists($this->request->getName())) {
136
+			throw new ApplicationLogicException('Account creation appeared to succeed but account does not exist.');
137
+		}
138 138
 
139
-        $this->request->setStatus(RequestStatus::CLOSED);
140
-        $this->request->save();
141
-    }
139
+		$this->request->setStatus(RequestStatus::CLOSED);
140
+		$this->request->save();
141
+	}
142 142
 }
143 143
\ No newline at end of file
Please login to merge, or discard this patch.
includes/DataObjects/JobQueue.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -225,7 +225,7 @@
 block discarded – undo
225 225
     }
226 226
 
227 227
     /**
228
-     * @return mixed
228
+     * @return string
229 229
      */
230 230
     public function getError()
231 231
     {
Please login to merge, or discard this patch.
Indentation   +253 added lines, -253 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 
18 18
 class JobQueue extends DataObject
19 19
 {
20
-    /*
20
+	/*
21 21
      * Status workflow is this:
22 22
      *
23 23
      * 1) Ready. The job has been added to the queue
@@ -26,78 +26,78 @@  discard block
 block discarded – undo
26 26
      * 3) Complete / Failed. The job has been processed
27 27
      *
28 28
      */
29
-    const STATUS_READY = 'ready';
30
-    const STATUS_WAITING = 'waiting';
31
-    const STATUS_RUNNING = 'running';
32
-    const STATUS_COMPLETE = 'complete';
33
-    const STATUS_CANCELLED = 'cancelled';
34
-    const STATUS_FAILED = 'failed';
35
-    const STATUS_HELD = 'held';
36
-
37
-    /** @var string */
38
-    private $task;
39
-    /** @var int */
40
-    private $user;
41
-    /** @var int */
42
-    private $request;
43
-    /** @var int */
44
-    private $emailtemplate;
45
-    /** @var string */
46
-    private $status;
47
-    /** @var string */
48
-    private $enqueue;
49
-    /** @var string */
50
-    private $parameters;
51
-    /** @var string */
52
-    private $error;
53
-    /** @var int */
54
-    private $acknowledged;
55
-    /** @var int */
56
-    private $parent;
57
-
58
-    /**
59
-     * This feels like the least bad place to put this method.
60
-     */
61
-    public static function getTaskDescriptions() {
62
-        return array(
63
-            BotCreationTask::class  => 'Create account (via bot)',
64
-            UserCreationTask::class => 'Create account (via OAuth)',
65
-            WelcomeUserTask::class  => 'Welcome user',
66
-        );
67
-    }
68
-
69
-    /**
70
-     * Saves a data object to the database, either updating or inserting a record.
71
-     * @return void
72
-     * @throws Exception
73
-     * @throws OptimisticLockFailedException
74
-     */
75
-    public function save()
76
-    {
77
-        if ($this->isNew()) {
78
-            // insert
79
-            $statement = $this->dbObject->prepare(<<<SQL
29
+	const STATUS_READY = 'ready';
30
+	const STATUS_WAITING = 'waiting';
31
+	const STATUS_RUNNING = 'running';
32
+	const STATUS_COMPLETE = 'complete';
33
+	const STATUS_CANCELLED = 'cancelled';
34
+	const STATUS_FAILED = 'failed';
35
+	const STATUS_HELD = 'held';
36
+
37
+	/** @var string */
38
+	private $task;
39
+	/** @var int */
40
+	private $user;
41
+	/** @var int */
42
+	private $request;
43
+	/** @var int */
44
+	private $emailtemplate;
45
+	/** @var string */
46
+	private $status;
47
+	/** @var string */
48
+	private $enqueue;
49
+	/** @var string */
50
+	private $parameters;
51
+	/** @var string */
52
+	private $error;
53
+	/** @var int */
54
+	private $acknowledged;
55
+	/** @var int */
56
+	private $parent;
57
+
58
+	/**
59
+	 * This feels like the least bad place to put this method.
60
+	 */
61
+	public static function getTaskDescriptions() {
62
+		return array(
63
+			BotCreationTask::class  => 'Create account (via bot)',
64
+			UserCreationTask::class => 'Create account (via OAuth)',
65
+			WelcomeUserTask::class  => 'Welcome user',
66
+		);
67
+	}
68
+
69
+	/**
70
+	 * Saves a data object to the database, either updating or inserting a record.
71
+	 * @return void
72
+	 * @throws Exception
73
+	 * @throws OptimisticLockFailedException
74
+	 */
75
+	public function save()
76
+	{
77
+		if ($this->isNew()) {
78
+			// insert
79
+			$statement = $this->dbObject->prepare(<<<SQL
80 80
                 INSERT INTO jobqueue (task, user, request, emailtemplate, parameters, parent) 
81 81
                 VALUES (:task, :user, :request, :emailtemplate, :parameters, :parent)
82 82
 SQL
83
-            );
84
-            $statement->bindValue(":task", $this->task);
85
-            $statement->bindValue(":user", $this->user);
86
-            $statement->bindValue(":request", $this->request);
87
-            $statement->bindValue(":emailtemplate", $this->emailtemplate);
88
-            $statement->bindValue(":parameters", $this->parameters);
89
-            $statement->bindValue(":parent", $this->parent);
90
-
91
-            if ($statement->execute()) {
92
-                $this->id = (int)$this->dbObject->lastInsertId();
93
-            }
94
-            else {
95
-                throw new Exception($statement->errorInfo());
96
-            }
97
-        }
98
-        else {
99
-            // update
100
-            $statement = $this->dbObject->prepare(<<<SQL
83
+			);
84
+			$statement->bindValue(":task", $this->task);
85
+			$statement->bindValue(":user", $this->user);
86
+			$statement->bindValue(":request", $this->request);
87
+			$statement->bindValue(":emailtemplate", $this->emailtemplate);
88
+			$statement->bindValue(":parameters", $this->parameters);
89
+			$statement->bindValue(":parent", $this->parent);
90
+
91
+			if ($statement->execute()) {
92
+				$this->id = (int)$this->dbObject->lastInsertId();
93
+			}
94
+			else {
95
+				throw new Exception($statement->errorInfo());
96
+			}
97
+		}
98
+		else {
99
+			// update
100
+			$statement = $this->dbObject->prepare(<<<SQL
101 101
                 UPDATE jobqueue SET 
102 102
                       status = :status
103 103
                     , error = :error
@@ -105,187 +105,187 @@  discard block
 block discarded – undo
105 105
                     , updateversion = updateversion + 1
106 106
                 WHERE id = :id AND updateversion = :updateversion;
107 107
 SQL
108
-            );
109
-
110
-            $statement->bindValue(":id", $this->id);
111
-            $statement->bindValue(":updateversion", $this->updateversion);
112
-
113
-            $statement->bindValue(":status", $this->status);
114
-            $statement->bindValue(":error", $this->error);
115
-            $statement->bindValue(":ack", $this->acknowledged);
116
-
117
-            if (!$statement->execute()) {
118
-                throw new Exception($statement->errorInfo());
119
-            }
120
-
121
-            if ($statement->rowCount() !== 1) {
122
-                throw new OptimisticLockFailedException();
123
-            }
124
-
125
-            $this->updateversion++;
126
-        }
127
-    }
128
-
129
-    #region Properties
130
-
131
-    /**
132
-     * @return string
133
-     */
134
-    public function getTask()
135
-    {
136
-        return $this->task;
137
-    }
138
-
139
-    /**
140
-     * @param string $task
141
-     */
142
-    public function setTask($task)
143
-    {
144
-        $this->task = $task;
145
-    }
146
-
147
-    /**
148
-     * @return int
149
-     */
150
-    public function getTriggerUserId()
151
-    {
152
-        return $this->user;
153
-    }
154
-
155
-    /**
156
-     * @param int $user
157
-     */
158
-    public function setTriggerUserId($user)
159
-    {
160
-        $this->user = $user;
161
-    }
162
-
163
-    /**
164
-     * @return int
165
-     */
166
-    public function getRequest()
167
-    {
168
-        return $this->request;
169
-    }
170
-
171
-    /**
172
-     * @param int $request
173
-     */
174
-    public function setRequest($request)
175
-    {
176
-        $this->request = $request;
177
-    }
178
-
179
-    /**
180
-     * @return string
181
-     */
182
-    public function getStatus()
183
-    {
184
-        return $this->status;
185
-    }
186
-
187
-    /**
188
-     * @param string $status
189
-     */
190
-    public function setStatus($status)
191
-    {
192
-        $this->status = $status;
193
-    }
194
-
195
-    /**
196
-     * @return string
197
-     */
198
-    public function getEnqueue()
199
-    {
200
-        return $this->enqueue;
201
-    }
202
-
203
-    /**
204
-     * @param string $enqueue
205
-     */
206
-    public function setEnqueue($enqueue)
207
-    {
208
-        $this->enqueue = $enqueue;
209
-    }
210
-
211
-    /**
212
-     * @return string
213
-     */
214
-    public function getParameters()
215
-    {
216
-        return $this->parameters;
217
-    }
218
-
219
-    /**
220
-     * @param string $parameters
221
-     */
222
-    public function setParameters($parameters)
223
-    {
224
-        $this->parameters = $parameters;
225
-    }
226
-
227
-    /**
228
-     * @return mixed
229
-     */
230
-    public function getError()
231
-    {
232
-        return $this->error;
233
-    }
234
-
235
-    /**
236
-     * @param mixed $error
237
-     */
238
-    public function setError($error)
239
-    {
240
-        $this->error = $error;
241
-    }
242
-
243
-    /**
244
-     * @return int
245
-     */
246
-    public function getAcknowledged()
247
-    {
248
-        return $this->acknowledged;
249
-    }
250
-
251
-    /**
252
-     * @param int $acknowledged
253
-     */
254
-    public function setAcknowledged($acknowledged)
255
-    {
256
-        $this->acknowledged = $acknowledged;
257
-    }
258
-
259
-    /**
260
-     * @return int
261
-     */
262
-    public function getParent()
263
-    {
264
-        return $this->parent;
265
-    }
266
-
267
-    /**
268
-     * @param int $parent
269
-     */
270
-    public function setParent($parent)
271
-    {
272
-        $this->parent = $parent;
273
-    }
274
-
275
-    /**
276
-     * @return int
277
-     */
278
-    public function getEmailTemplate()
279
-    {
280
-        return $this->emailtemplate;
281
-    }
282
-
283
-    /**
284
-     * @param int $emailTemplate
285
-     */
286
-    public function setEmailTemplate($emailTemplate)
287
-    {
288
-        $this->emailtemplate = $emailTemplate;
289
-    }
290
-    #endregion
108
+			);
109
+
110
+			$statement->bindValue(":id", $this->id);
111
+			$statement->bindValue(":updateversion", $this->updateversion);
112
+
113
+			$statement->bindValue(":status", $this->status);
114
+			$statement->bindValue(":error", $this->error);
115
+			$statement->bindValue(":ack", $this->acknowledged);
116
+
117
+			if (!$statement->execute()) {
118
+				throw new Exception($statement->errorInfo());
119
+			}
120
+
121
+			if ($statement->rowCount() !== 1) {
122
+				throw new OptimisticLockFailedException();
123
+			}
124
+
125
+			$this->updateversion++;
126
+		}
127
+	}
128
+
129
+	#region Properties
130
+
131
+	/**
132
+	 * @return string
133
+	 */
134
+	public function getTask()
135
+	{
136
+		return $this->task;
137
+	}
138
+
139
+	/**
140
+	 * @param string $task
141
+	 */
142
+	public function setTask($task)
143
+	{
144
+		$this->task = $task;
145
+	}
146
+
147
+	/**
148
+	 * @return int
149
+	 */
150
+	public function getTriggerUserId()
151
+	{
152
+		return $this->user;
153
+	}
154
+
155
+	/**
156
+	 * @param int $user
157
+	 */
158
+	public function setTriggerUserId($user)
159
+	{
160
+		$this->user = $user;
161
+	}
162
+
163
+	/**
164
+	 * @return int
165
+	 */
166
+	public function getRequest()
167
+	{
168
+		return $this->request;
169
+	}
170
+
171
+	/**
172
+	 * @param int $request
173
+	 */
174
+	public function setRequest($request)
175
+	{
176
+		$this->request = $request;
177
+	}
178
+
179
+	/**
180
+	 * @return string
181
+	 */
182
+	public function getStatus()
183
+	{
184
+		return $this->status;
185
+	}
186
+
187
+	/**
188
+	 * @param string $status
189
+	 */
190
+	public function setStatus($status)
191
+	{
192
+		$this->status = $status;
193
+	}
194
+
195
+	/**
196
+	 * @return string
197
+	 */
198
+	public function getEnqueue()
199
+	{
200
+		return $this->enqueue;
201
+	}
202
+
203
+	/**
204
+	 * @param string $enqueue
205
+	 */
206
+	public function setEnqueue($enqueue)
207
+	{
208
+		$this->enqueue = $enqueue;
209
+	}
210
+
211
+	/**
212
+	 * @return string
213
+	 */
214
+	public function getParameters()
215
+	{
216
+		return $this->parameters;
217
+	}
218
+
219
+	/**
220
+	 * @param string $parameters
221
+	 */
222
+	public function setParameters($parameters)
223
+	{
224
+		$this->parameters = $parameters;
225
+	}
226
+
227
+	/**
228
+	 * @return mixed
229
+	 */
230
+	public function getError()
231
+	{
232
+		return $this->error;
233
+	}
234
+
235
+	/**
236
+	 * @param mixed $error
237
+	 */
238
+	public function setError($error)
239
+	{
240
+		$this->error = $error;
241
+	}
242
+
243
+	/**
244
+	 * @return int
245
+	 */
246
+	public function getAcknowledged()
247
+	{
248
+		return $this->acknowledged;
249
+	}
250
+
251
+	/**
252
+	 * @param int $acknowledged
253
+	 */
254
+	public function setAcknowledged($acknowledged)
255
+	{
256
+		$this->acknowledged = $acknowledged;
257
+	}
258
+
259
+	/**
260
+	 * @return int
261
+	 */
262
+	public function getParent()
263
+	{
264
+		return $this->parent;
265
+	}
266
+
267
+	/**
268
+	 * @param int $parent
269
+	 */
270
+	public function setParent($parent)
271
+	{
272
+		$this->parent = $parent;
273
+	}
274
+
275
+	/**
276
+	 * @return int
277
+	 */
278
+	public function getEmailTemplate()
279
+	{
280
+		return $this->emailtemplate;
281
+	}
282
+
283
+	/**
284
+	 * @param int $emailTemplate
285
+	 */
286
+	public function setEmailTemplate($emailTemplate)
287
+	{
288
+		$this->emailtemplate = $emailTemplate;
289
+	}
290
+	#endregion
291 291
 }
292 292
\ No newline at end of file
Please login to merge, or discard this patch.
includes/DataObjects/OAuthToken.php 2 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
     #region properties
84 84
 
85 85
     /**
86
-     * @return mixed
86
+     * @return integer
87 87
      */
88 88
     public function getUserId()
89 89
     {
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
     }
100 100
 
101 101
     /**
102
-     * @return mixed
102
+     * @return string
103 103
      */
104 104
     public function getToken()
105 105
     {
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
     }
116 116
 
117 117
     /**
118
-     * @return mixed
118
+     * @return string
119 119
      */
120 120
     public function getSecret()
121 121
     {
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
     }
132 132
 
133 133
     /**
134
-     * @return mixed
134
+     * @return string
135 135
      */
136 136
     public function getType()
137 137
     {
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
     }
140 140
 
141 141
     /**
142
-     * @param mixed $type
142
+     * @param string $type
143 143
      */
144 144
     public function setType($type)
145 145
     {
Please login to merge, or discard this patch.
Indentation   +137 added lines, -137 removed lines patch added patch discarded remove patch
@@ -14,42 +14,42 @@  discard block
 block discarded – undo
14 14
 
15 15
 class OAuthToken extends DataObject
16 16
 {
17
-    /** @var int */
18
-    private $user;
19
-    /** @var string */
20
-    private $token;
21
-    /** @var string */
22
-    private $secret;
23
-    /** @var string */
24
-    private $type;
25
-    /** @var string */
26
-    private $expiry;
27
-
28
-    public function save()
29
-    {
30
-        if ($this->isNew()) {
31
-            // insert
32
-            $statement = $this->dbObject->prepare(<<<SQL
17
+	/** @var int */
18
+	private $user;
19
+	/** @var string */
20
+	private $token;
21
+	/** @var string */
22
+	private $secret;
23
+	/** @var string */
24
+	private $type;
25
+	/** @var string */
26
+	private $expiry;
27
+
28
+	public function save()
29
+	{
30
+		if ($this->isNew()) {
31
+			// insert
32
+			$statement = $this->dbObject->prepare(<<<SQL
33 33
                 INSERT INTO oauthtoken ( user, token, secret, type, expiry )
34 34
                 VALUES ( :user, :token, :secret, :type, :expiry );
35 35
 SQL
36
-            );
37
-            $statement->bindValue(":user", $this->user);
38
-            $statement->bindValue(":token", $this->token);
39
-            $statement->bindValue(":secret", $this->secret);
40
-            $statement->bindValue(":type", $this->type);
41
-            $statement->bindValue(":expiry", $this->expiry);
42
-
43
-            if ($statement->execute()) {
44
-                $this->id = (int)$this->dbObject->lastInsertId();
45
-            }
46
-            else {
47
-                throw new Exception($statement->errorInfo());
48
-            }
49
-        }
50
-        else {
51
-            // update
52
-            $statement = $this->dbObject->prepare(<<<SQL
36
+			);
37
+			$statement->bindValue(":user", $this->user);
38
+			$statement->bindValue(":token", $this->token);
39
+			$statement->bindValue(":secret", $this->secret);
40
+			$statement->bindValue(":type", $this->type);
41
+			$statement->bindValue(":expiry", $this->expiry);
42
+
43
+			if ($statement->execute()) {
44
+				$this->id = (int)$this->dbObject->lastInsertId();
45
+			}
46
+			else {
47
+				throw new Exception($statement->errorInfo());
48
+			}
49
+		}
50
+		else {
51
+			// update
52
+			$statement = $this->dbObject->prepare(<<<SQL
53 53
                 UPDATE oauthtoken
54 54
                 SET   token = :token
55 55
                     , secret = :secret
@@ -58,109 +58,109 @@  discard block
 block discarded – undo
58 58
                     , updateversion = updateversion + 1
59 59
                 WHERE id = :id AND updateversion = :updateversion;
60 60
 SQL
61
-            );
62
-
63
-            $statement->bindValue(':id', $this->id);
64
-            $statement->bindValue(':updateversion', $this->updateversion);
65
-
66
-            $statement->bindValue(":token", $this->token);
67
-            $statement->bindValue(":secret", $this->secret);
68
-            $statement->bindValue(":type", $this->type);
69
-            $statement->bindValue(":expiry", $this->expiry);
70
-
71
-            if (!$statement->execute()) {
72
-                throw new Exception($statement->errorInfo());
73
-            }
74
-
75
-            if ($statement->rowCount() !== 1) {
76
-                throw new OptimisticLockFailedException();
77
-            }
78
-
79
-            $this->updateversion++;
80
-        }
81
-    }
82
-
83
-    #region properties
84
-
85
-    /**
86
-     * @return mixed
87
-     */
88
-    public function getUserId()
89
-    {
90
-        return $this->user;
91
-    }
92
-
93
-    /**
94
-     * @param mixed $user
95
-     */
96
-    public function setUserId($user)
97
-    {
98
-        $this->user = $user;
99
-    }
100
-
101
-    /**
102
-     * @return mixed
103
-     */
104
-    public function getToken()
105
-    {
106
-        return $this->token;
107
-    }
108
-
109
-    /**
110
-     * @param mixed $token
111
-     */
112
-    public function setToken($token)
113
-    {
114
-        $this->token = $token;
115
-    }
116
-
117
-    /**
118
-     * @return mixed
119
-     */
120
-    public function getSecret()
121
-    {
122
-        return $this->secret;
123
-    }
124
-
125
-    /**
126
-     * @param mixed $secret
127
-     */
128
-    public function setSecret($secret)
129
-    {
130
-        $this->secret = $secret;
131
-    }
132
-
133
-    /**
134
-     * @return mixed
135
-     */
136
-    public function getType()
137
-    {
138
-        return $this->type;
139
-    }
140
-
141
-    /**
142
-     * @param mixed $type
143
-     */
144
-    public function setType($type)
145
-    {
146
-        $this->type = $type;
147
-    }
148
-
149
-    /**
150
-     * @return string
151
-     */
152
-    public function getExpiry()
153
-    {
154
-        return $this->expiry;
155
-    }
156
-
157
-    /**
158
-     * @param string $expiry
159
-     */
160
-    public function setExpiry($expiry)
161
-    {
162
-        $this->expiry = $expiry;
163
-    }
164
-    #endregion
61
+			);
62
+
63
+			$statement->bindValue(':id', $this->id);
64
+			$statement->bindValue(':updateversion', $this->updateversion);
65
+
66
+			$statement->bindValue(":token", $this->token);
67
+			$statement->bindValue(":secret", $this->secret);
68
+			$statement->bindValue(":type", $this->type);
69
+			$statement->bindValue(":expiry", $this->expiry);
70
+
71
+			if (!$statement->execute()) {
72
+				throw new Exception($statement->errorInfo());
73
+			}
74
+
75
+			if ($statement->rowCount() !== 1) {
76
+				throw new OptimisticLockFailedException();
77
+			}
78
+
79
+			$this->updateversion++;
80
+		}
81
+	}
82
+
83
+	#region properties
84
+
85
+	/**
86
+	 * @return mixed
87
+	 */
88
+	public function getUserId()
89
+	{
90
+		return $this->user;
91
+	}
92
+
93
+	/**
94
+	 * @param mixed $user
95
+	 */
96
+	public function setUserId($user)
97
+	{
98
+		$this->user = $user;
99
+	}
100
+
101
+	/**
102
+	 * @return mixed
103
+	 */
104
+	public function getToken()
105
+	{
106
+		return $this->token;
107
+	}
108
+
109
+	/**
110
+	 * @param mixed $token
111
+	 */
112
+	public function setToken($token)
113
+	{
114
+		$this->token = $token;
115
+	}
116
+
117
+	/**
118
+	 * @return mixed
119
+	 */
120
+	public function getSecret()
121
+	{
122
+		return $this->secret;
123
+	}
124
+
125
+	/**
126
+	 * @param mixed $secret
127
+	 */
128
+	public function setSecret($secret)
129
+	{
130
+		$this->secret = $secret;
131
+	}
132
+
133
+	/**
134
+	 * @return mixed
135
+	 */
136
+	public function getType()
137
+	{
138
+		return $this->type;
139
+	}
140
+
141
+	/**
142
+	 * @param mixed $type
143
+	 */
144
+	public function setType($type)
145
+	{
146
+		$this->type = $type;
147
+	}
148
+
149
+	/**
150
+	 * @return string
151
+	 */
152
+	public function getExpiry()
153
+	{
154
+		return $this->expiry;
155
+	}
156
+
157
+	/**
158
+	 * @param string $expiry
159
+	 */
160
+	public function setExpiry($expiry)
161
+	{
162
+		$this->expiry = $expiry;
163
+	}
164
+	#endregion
165 165
 
166 166
 }
167 167
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/BotMediaWikiClient.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@
 block discarded – undo
83 83
 
84 84
     /**
85 85
      * @param $apiParams
86
-     * @param $method
86
+     * @param string $method
87 87
      *
88 88
      * @return mixed
89 89
      * @throws ApplicationLogicException
Please login to merge, or discard this patch.
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -16,136 +16,136 @@
 block discarded – undo
16 16
 
17 17
 class BotMediaWikiClient implements IMediaWikiClient
18 18
 {
19
-    /**
20
-     * @var HttpHelper
21
-     */
22
-    private $httpHelper;
23
-    /** @var string */
24
-    private $mediawikiWebServiceEndpoint;
25
-    /** @var string */
26
-    private $creationBotUsername;
27
-    /** @var string */
28
-    private $creationBotPassword;
29
-    /** @var bool */
30
-    private $knownLoggedIn = false;
31
-
32
-    /**
33
-     * BotMediaWikiClient constructor.
34
-     *
35
-     * @param SiteConfiguration $siteConfiguration
36
-     */
37
-    public function __construct(SiteConfiguration $siteConfiguration)
38
-    {
39
-        $this->mediawikiWebServiceEndpoint = $siteConfiguration->getMediawikiWebServiceEndpoint();
40
-
41
-        $this->creationBotUsername = $siteConfiguration->getCreationBotUsername();
42
-        $this->creationBotPassword = $siteConfiguration->getCreationBotPassword();
43
-
44
-        $this->httpHelper = new HttpHelper(
45
-            $siteConfiguration->getUserAgent(),
46
-            $siteConfiguration->getCurlDisableVerifyPeer(),
47
-            $siteConfiguration->getCurlCookieJar()
48
-        );
49
-    }
50
-
51
-    function doApiCall($apiParams, $method = 'GET')
52
-    {
53
-        $this->ensureLoggedIn();
54
-        $apiParams['assert'] = 'user';
55
-
56
-        return $this->callApi($apiParams, $method);
57
-    }
58
-
59
-    private function ensureLoggedIn()
60
-    {
61
-        if ($this->knownLoggedIn) {
62
-            return;
63
-        }
64
-
65
-        $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
66
-        if (isset($userinfoResult->query->userinfo->anon)) {
67
-            // not logged in.
68
-            $this->logIn();
69
-
70
-            // retest
71
-            $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
72
-            if (isset($userinfoResult->query->userinfo->anon)) {
73
-                throw new MediaWikiApiException('Unable to log in.');
74
-            }
75
-            else {
76
-                $this->knownLoggedIn = true;
77
-            }
78
-        }
79
-        else {
80
-            $this->knownLoggedIn = true;
81
-        }
82
-    }
83
-
84
-    /**
85
-     * @param $apiParams
86
-     * @param $method
87
-     *
88
-     * @return mixed
89
-     * @throws ApplicationLogicException
90
-     * @throws CurlException
91
-     */
92
-    private function callApi($apiParams, $method)
93
-    {
94
-        $apiParams['format'] = 'json';
95
-
96
-        if ($method == 'GET') {
97
-            $data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
98
-        }
99
-        elseif ($method == 'POST') {
100
-            $data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
101
-        }
102
-        else {
103
-            throw new ApplicationLogicException('Unsupported HTTP Method');
104
-        }
105
-
106
-        if ($data === false) {
107
-            throw new CurlException('Curl error: ' . $this->httpHelper->getError());
108
-        }
109
-
110
-        $result = json_decode($data);
111
-
112
-        return $result;
113
-    }
114
-
115
-    private function logIn()
116
-    {
117
-        // get token
118
-        $tokenParams = array(
119
-            'action' => 'query',
120
-            'meta'   => 'tokens',
121
-            'type'   => 'login',
122
-        );
123
-
124
-        $response = $this->callApi($tokenParams, 'POST');
125
-
126
-        if (isset($response->error)) {
127
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
128
-        }
129
-
130
-        $token = $response->query->tokens->logintoken;
131
-
132
-        if ($token === null) {
133
-            throw new MediaWikiApiException('Edit token could not be acquired');
134
-        }
135
-
136
-        $params = array(
137
-            'action' => 'login',
138
-            'lgname' => $this->creationBotUsername,
139
-            'lgpassword' => $this->creationBotPassword,
140
-            'lgtoken' => $token,
141
-        );
142
-
143
-        $loginResponse = $this->callApi($params, 'POST');
144
-
145
-        if($loginResponse->login->result == 'Success'){
146
-            return;
147
-        }
148
-
149
-        throw new ApplicationLogicException(json_encode($loginResponse));
150
-    }
19
+	/**
20
+	 * @var HttpHelper
21
+	 */
22
+	private $httpHelper;
23
+	/** @var string */
24
+	private $mediawikiWebServiceEndpoint;
25
+	/** @var string */
26
+	private $creationBotUsername;
27
+	/** @var string */
28
+	private $creationBotPassword;
29
+	/** @var bool */
30
+	private $knownLoggedIn = false;
31
+
32
+	/**
33
+	 * BotMediaWikiClient constructor.
34
+	 *
35
+	 * @param SiteConfiguration $siteConfiguration
36
+	 */
37
+	public function __construct(SiteConfiguration $siteConfiguration)
38
+	{
39
+		$this->mediawikiWebServiceEndpoint = $siteConfiguration->getMediawikiWebServiceEndpoint();
40
+
41
+		$this->creationBotUsername = $siteConfiguration->getCreationBotUsername();
42
+		$this->creationBotPassword = $siteConfiguration->getCreationBotPassword();
43
+
44
+		$this->httpHelper = new HttpHelper(
45
+			$siteConfiguration->getUserAgent(),
46
+			$siteConfiguration->getCurlDisableVerifyPeer(),
47
+			$siteConfiguration->getCurlCookieJar()
48
+		);
49
+	}
50
+
51
+	function doApiCall($apiParams, $method = 'GET')
52
+	{
53
+		$this->ensureLoggedIn();
54
+		$apiParams['assert'] = 'user';
55
+
56
+		return $this->callApi($apiParams, $method);
57
+	}
58
+
59
+	private function ensureLoggedIn()
60
+	{
61
+		if ($this->knownLoggedIn) {
62
+			return;
63
+		}
64
+
65
+		$userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
66
+		if (isset($userinfoResult->query->userinfo->anon)) {
67
+			// not logged in.
68
+			$this->logIn();
69
+
70
+			// retest
71
+			$userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
72
+			if (isset($userinfoResult->query->userinfo->anon)) {
73
+				throw new MediaWikiApiException('Unable to log in.');
74
+			}
75
+			else {
76
+				$this->knownLoggedIn = true;
77
+			}
78
+		}
79
+		else {
80
+			$this->knownLoggedIn = true;
81
+		}
82
+	}
83
+
84
+	/**
85
+	 * @param $apiParams
86
+	 * @param $method
87
+	 *
88
+	 * @return mixed
89
+	 * @throws ApplicationLogicException
90
+	 * @throws CurlException
91
+	 */
92
+	private function callApi($apiParams, $method)
93
+	{
94
+		$apiParams['format'] = 'json';
95
+
96
+		if ($method == 'GET') {
97
+			$data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
98
+		}
99
+		elseif ($method == 'POST') {
100
+			$data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
101
+		}
102
+		else {
103
+			throw new ApplicationLogicException('Unsupported HTTP Method');
104
+		}
105
+
106
+		if ($data === false) {
107
+			throw new CurlException('Curl error: ' . $this->httpHelper->getError());
108
+		}
109
+
110
+		$result = json_decode($data);
111
+
112
+		return $result;
113
+	}
114
+
115
+	private function logIn()
116
+	{
117
+		// get token
118
+		$tokenParams = array(
119
+			'action' => 'query',
120
+			'meta'   => 'tokens',
121
+			'type'   => 'login',
122
+		);
123
+
124
+		$response = $this->callApi($tokenParams, 'POST');
125
+
126
+		if (isset($response->error)) {
127
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
128
+		}
129
+
130
+		$token = $response->query->tokens->logintoken;
131
+
132
+		if ($token === null) {
133
+			throw new MediaWikiApiException('Edit token could not be acquired');
134
+		}
135
+
136
+		$params = array(
137
+			'action' => 'login',
138
+			'lgname' => $this->creationBotUsername,
139
+			'lgpassword' => $this->creationBotPassword,
140
+			'lgtoken' => $token,
141
+		);
142
+
143
+		$loginResponse = $this->callApi($params, 'POST');
144
+
145
+		if($loginResponse->login->result == 'Success'){
146
+			return;
147
+		}
148
+
149
+		throw new ApplicationLogicException(json_encode($loginResponse));
150
+	}
151 151
 }
152 152
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/Interfaces/IMediaWikiClient.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -10,5 +10,8 @@
 block discarded – undo
10 10
 
11 11
 interface IMediaWikiClient
12 12
 {
13
+    /**
14
+     * @param string $method
15
+     */
13 16
     function doApiCall($params, $method);
14 17
 }
15 18
\ No newline at end of file
Please login to merge, or discard this patch.
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -10,5 +10,5 @@
 block discarded – undo
10 10
 
11 11
 interface IMediaWikiClient
12 12
 {
13
-    function doApiCall($params, $method);
13
+	function doApiCall($params, $method);
14 14
 }
15 15
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/OAuthUserHelper.php 2 patches
Doc Comments   +13 added lines, -1 removed lines patch added patch discarded remove patch
@@ -63,6 +63,10 @@  discard block
 block discarded – undo
63 63
     private $siteConfiguration;
64 64
 
65 65
     #region Static methods
66
+
67
+    /**
68
+     * @param null|string $requestToken
69
+     */
66 70
     public static function findUserByRequestToken($requestToken, PdoDatabase $database)
67 71
     {
68 72
         $statement = $database->prepare(<<<'SQL'
@@ -119,6 +123,11 @@  discard block
 block discarded – undo
119 123
         }
120 124
     }
121 125
 
126
+    /**
127
+     * @param integer $userId
128
+     * @param null|PdoDatabase $database
129
+     * @param string $tokenType
130
+     */
122 131
     private static function runTokenCount($userId, $database, $tokenType)
123 132
     {
124 133
         if (self::$tokenCountStatement === null) {
@@ -182,7 +191,7 @@  discard block
 block discarded – undo
182 191
     /**
183 192
      * Attempts to figure out if a user is partially linked to OAuth, and therefore needs to complete the OAuth
184 193
      * procedure before configuring.
185
-     * @return bool
194
+     * @return boolean|null
186 195
      */
187 196
     public function isPartiallyLinked()
188 197
     {
@@ -245,6 +254,9 @@  discard block
 block discarded – undo
245 254
         return $this->oauthProtocolHelper->getAuthoriseUrl($token->key);
246 255
     }
247 256
 
257
+    /**
258
+     * @param null|string $verificationToken
259
+     */
248 260
     public function completeHandshake($verificationToken)
249 261
     {
250 262
         $this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
Please login to merge, or discard this patch.
Indentation   +403 added lines, -403 removed lines patch added patch discarded remove patch
@@ -22,411 +22,411 @@
 block discarded – undo
22 22
 
23 23
 class OAuthUserHelper implements IMediaWikiClient
24 24
 {
25
-    const TOKEN_REQUEST = 'request';
26
-    const TOKEN_ACCESS = 'access';
27
-    /** @var PDOStatement */
28
-    private static $tokenCountStatement = null;
29
-    /** @var PDOStatement */
30
-    private $getTokenStatement;
31
-    /**
32
-     * @var User
33
-     */
34
-    private $user;
35
-    /**
36
-     * @var PdoDatabase
37
-     */
38
-    private $database;
39
-    /**
40
-     * @var IOAuthProtocolHelper
41
-     */
42
-    private $oauthProtocolHelper;
43
-    /**
44
-     * @var bool|null Is the user linked to OAuth
45
-     */
46
-    private $linked;
47
-    private $partiallyLinked;
48
-    /** @var OAuthToken */
49
-    private $accessToken;
50
-    /** @var bool */
51
-    private $accessTokenLoaded = false;
52
-    /**
53
-     * @var OAuthIdentity
54
-     */
55
-    private $identity = null;
56
-    /**
57
-     * @var bool
58
-     */
59
-    private $identityLoaded = false;
60
-    /**
61
-     * @var SiteConfiguration
62
-     */
63
-    private $siteConfiguration;
64
-
65
-    #region Static methods
66
-    public static function findUserByRequestToken($requestToken, PdoDatabase $database)
67
-    {
68
-        $statement = $database->prepare(<<<'SQL'
25
+	const TOKEN_REQUEST = 'request';
26
+	const TOKEN_ACCESS = 'access';
27
+	/** @var PDOStatement */
28
+	private static $tokenCountStatement = null;
29
+	/** @var PDOStatement */
30
+	private $getTokenStatement;
31
+	/**
32
+	 * @var User
33
+	 */
34
+	private $user;
35
+	/**
36
+	 * @var PdoDatabase
37
+	 */
38
+	private $database;
39
+	/**
40
+	 * @var IOAuthProtocolHelper
41
+	 */
42
+	private $oauthProtocolHelper;
43
+	/**
44
+	 * @var bool|null Is the user linked to OAuth
45
+	 */
46
+	private $linked;
47
+	private $partiallyLinked;
48
+	/** @var OAuthToken */
49
+	private $accessToken;
50
+	/** @var bool */
51
+	private $accessTokenLoaded = false;
52
+	/**
53
+	 * @var OAuthIdentity
54
+	 */
55
+	private $identity = null;
56
+	/**
57
+	 * @var bool
58
+	 */
59
+	private $identityLoaded = false;
60
+	/**
61
+	 * @var SiteConfiguration
62
+	 */
63
+	private $siteConfiguration;
64
+
65
+	#region Static methods
66
+	public static function findUserByRequestToken($requestToken, PdoDatabase $database)
67
+	{
68
+		$statement = $database->prepare(<<<'SQL'
69 69
             SELECT u.* FROM user u 
70 70
             INNER JOIN oauthtoken t ON t.user = u.id 
71 71
             WHERE t.type = :type AND t.token = :token
72 72
 SQL
73
-        );
74
-        $statement->execute(array(':type' => self::TOKEN_REQUEST, ':token' => $requestToken));
75
-
76
-        /** @var User $user */
77
-        $user = $statement->fetchObject(User::class);
78
-        $statement->closeCursor();
79
-
80
-        if ($user === false) {
81
-            throw new ApplicationLogicException('Token not found in store, please try again');
82
-        }
83
-
84
-        $user->setDatabase($database);
85
-
86
-        return $user;
87
-    }
88
-
89
-    public static function userIsFullyLinked(User $user, PdoDatabase $database = null)
90
-    {
91
-        if (self::$tokenCountStatement === null && $database === null) {
92
-            throw new ApplicationLogicException('Static link request without initialised statement');
93
-        }
94
-
95
-        return self::runTokenCount($user->getId(), $database, self::TOKEN_ACCESS);
96
-    }
97
-
98
-    public static function userIsPartiallyLinked(User $user, PdoDatabase $database = null)
99
-    {
100
-        if (self::$tokenCountStatement === null && $database === null) {
101
-            throw new ApplicationLogicException('Static link request without initialised statement');
102
-        }
103
-
104
-        if (self::userIsFullyLinked($user, $database)) {
105
-            return false;
106
-        }
107
-
108
-        return self::runTokenCount($user->getId(), $database, self::TOKEN_REQUEST)
109
-            || $user->getOnWikiName() == null;
110
-    }
111
-
112
-    /**
113
-     * @param PdoDatabase $database
114
-     */
115
-    public static function prepareTokenCountStatement(PdoDatabase $database)
116
-    {
117
-        if (self::$tokenCountStatement === null) {
118
-            self::$tokenCountStatement = $database->prepare('SELECT COUNT(*) FROM oauthtoken WHERE user = :user AND type = :type');
119
-        }
120
-    }
121
-
122
-    private static function runTokenCount($userId, $database, $tokenType)
123
-    {
124
-        if (self::$tokenCountStatement === null) {
125
-            self::prepareTokenCountStatement($database);
126
-        }
127
-
128
-        self::$tokenCountStatement->execute(array(
129
-            ':user' => $userId,
130
-            ':type' => $tokenType,
131
-        ));
132
-
133
-        $tokenCount = self::$tokenCountStatement->fetchColumn();
134
-        $linked = $tokenCount > 0;
135
-        self::$tokenCountStatement->closeCursor();
136
-
137
-        return $linked;
138
-    }
139
-
140
-    #endregion Static methods
141
-
142
-    /**
143
-     * OAuthUserHelper constructor.
144
-     *
145
-     * @param User                 $user
146
-     * @param PdoDatabase          $database
147
-     * @param IOAuthProtocolHelper $oauthProtocolHelper
148
-     * @param SiteConfiguration    $siteConfiguration
149
-     */
150
-    public function __construct(
151
-        User $user,
152
-        PdoDatabase $database,
153
-        IOAuthProtocolHelper $oauthProtocolHelper,
154
-        SiteConfiguration $siteConfiguration
155
-    ) {
156
-        $this->user = $user;
157
-        $this->database = $database;
158
-        $this->oauthProtocolHelper = $oauthProtocolHelper;
159
-
160
-        $this->linked = null;
161
-        $this->partiallyLinked = null;
162
-        $this->siteConfiguration = $siteConfiguration;
163
-
164
-        self::prepareTokenCountStatement($database);
165
-        $this->getTokenStatement = $this->database->prepare('SELECT * FROM oauthtoken WHERE user = :user AND type = :type');
166
-    }
167
-
168
-    /**
169
-     * Determines if the user is fully connected to OAuth.
170
-     *
171
-     * @return bool
172
-     */
173
-    public function isFullyLinked()
174
-    {
175
-        if ($this->linked === null) {
176
-            $this->linked = self::userIsFullyLinked($this->user, $this->database);
177
-        }
178
-
179
-        return $this->linked;
180
-    }
181
-
182
-    /**
183
-     * Attempts to figure out if a user is partially linked to OAuth, and therefore needs to complete the OAuth
184
-     * procedure before configuring.
185
-     * @return bool
186
-     */
187
-    public function isPartiallyLinked()
188
-    {
189
-        if ($this->partiallyLinked === null) {
190
-            $this->partiallyLinked = self::userIsPartiallyLinked($this->user, $this->database);
191
-        }
192
-
193
-        return $this->partiallyLinked;
194
-    }
195
-
196
-    /**
197
-     * @throws OAuthException
198
-     */
199
-    public function refreshIdentity()
200
-    {
201
-        $this->loadIdentity();
202
-
203
-        if ($this->identity === null) {
204
-            $this->identity = new OAuthIdentity();
205
-            $this->identity->setUserId($this->user->getId());
206
-            $this->identity->setDatabase($this->database);
207
-        }
208
-
209
-        $token = $this->loadAccessToken();
210
-
211
-        $rawTicket = $this->oauthProtocolHelper->getIdentityTicket($token->getToken(), $token->getSecret());
212
-
213
-        $this->identity->populate($rawTicket);
214
-
215
-        if (!$this->identityIsValid()) {
216
-            throw new OAuthException('Identity ticket is not valid!');
217
-        }
218
-
219
-        $this->identity->save();
220
-
221
-        $this->user->setOnWikiName($this->identity->getUsername());
222
-        $this->user->save();
223
-    }
224
-
225
-    public function getRequestToken()
226
-    {
227
-        $token = $this->oauthProtocolHelper->getRequestToken();
228
-
229
-        $this->partiallyLinked = true;
230
-        $this->linked = false;
231
-
232
-        $this->database
233
-            ->prepare('DELETE FROM oauthtoken WHERE user = :user AND type = :type')
234
-            ->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
235
-
236
-        $this->database
237
-            ->prepare('INSERT INTO oauthtoken (user, type, token, secret, expiry) VALUES (:user, :type, :token, :secret, DATE_ADD(NOW(), INTERVAL 1 DAY))')
238
-            ->execute(array(
239
-                ':user'   => $this->user->getId(),
240
-                ':type'   => self::TOKEN_REQUEST,
241
-                ':token'  => $token->key,
242
-                ':secret' => $token->secret,
243
-            ));
244
-
245
-        return $this->oauthProtocolHelper->getAuthoriseUrl($token->key);
246
-    }
247
-
248
-    public function completeHandshake($verificationToken)
249
-    {
250
-        $this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
251
-
252
-        /** @var OAuthToken $token */
253
-        $token = $this->getTokenStatement->fetchObject(OAuthToken::class);
254
-        $this->getTokenStatement->closeCursor();
255
-
256
-        if ($token === false) {
257
-            throw new ApplicationLogicException('Cannot find request token');
258
-        }
259
-
260
-        $token->setDatabase($this->database);
261
-
262
-        $accessToken = $this->oauthProtocolHelper->callbackCompleted($token->getToken(), $token->getSecret(),
263
-            $verificationToken);
264
-
265
-        $clearStatement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :u AND type = :t');
266
-        $clearStatement->execute(array(':u' => $this->user->getId(), ':t' => self::TOKEN_ACCESS));
267
-
268
-        $token->setToken($accessToken->key);
269
-        $token->setSecret($accessToken->secret);
270
-        $token->setType(self::TOKEN_ACCESS);
271
-        $token->setExpiry(null);
272
-        $token->save();
273
-
274
-        $this->partiallyLinked = false;
275
-        $this->linked = true;
276
-
277
-        $this->refreshIdentity();
278
-    }
279
-
280
-    public function detach()
281
-    {
282
-        $this->loadIdentity();
283
-
284
-        $this->identity->delete();
285
-        $statement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :user');
286
-        $statement->execute(array(':user' => $this->user->getId()));
287
-
288
-        $this->identity = null;
289
-        $this->linked = false;
290
-        $this->partiallyLinked = false;
291
-    }
292
-
293
-    /**
294
-     * @param bool $expiredOk
295
-     *
296
-     * @return OAuthIdentity
297
-     * @throws OAuthException
298
-     */
299
-    public function getIdentity($expiredOk = false)
300
-    {
301
-        $this->loadIdentity();
302
-
303
-        if (!$this->identityIsValid($expiredOk)) {
304
-            throw new OAuthException('Stored identity is not valid.');
305
-        }
306
-
307
-        return $this->identity;
308
-    }
309
-
310
-    public function doApiCall($params, $method)
311
-    {
312
-        // Ensure we're logged in
313
-        $params['assert'] = 'user';
314
-
315
-        $token = $this->loadAccessToken();
316
-        return $this->oauthProtocolHelper->apiCall($params, $token->getToken(), $token->getSecret(), $method);
317
-    }
318
-
319
-    /**
320
-     * @param bool $expiredOk
321
-     *
322
-     * @return bool
323
-     */
324
-    private function identityIsValid($expiredOk = false)
325
-    {
326
-        $this->loadIdentity();
327
-
328
-        if ($this->identity === null) {
329
-            return false;
330
-        }
331
-
332
-        if ($this->identity->getIssuedAtTime() === false
333
-            || $this->identity->getExpirationTime() === false
334
-            || $this->identity->getAudience() === false
335
-            || $this->identity->getIssuer() === false
336
-        ) {
337
-            // this isn't populated properly.
338
-            return false;
339
-        }
340
-
341
-        $issue = DateTimeImmutable::createFromFormat("U", $this->identity->getIssuedAtTime());
342
-        $now = new DateTimeImmutable();
343
-
344
-        if ($issue > $now) {
345
-            // wat.
346
-            return false;
347
-        }
348
-
349
-        if ($this->identityExpired() && !$expiredOk) {
350
-            // soz.
351
-            return false;
352
-        }
353
-
354
-        if ($this->identity->getAudience() !== $this->siteConfiguration->getOAuthConsumerToken()) {
355
-            // token not issued for us
356
-            return false;
357
-        }
358
-
359
-        if ($this->identity->getIssuer() !== $this->siteConfiguration->getOauthMediaWikiCanonicalServer()) {
360
-            // token not issued by the right person
361
-            return false;
362
-        }
363
-
364
-        // can't find a reason to not trust it
365
-        return true;
366
-    }
367
-
368
-    /**
369
-     * @return bool
370
-     */
371
-    public function identityExpired()
372
-    {
373
-        // allowed max age
374
-        $gracePeriod = $this->siteConfiguration->getOauthIdentityGraceTime();
375
-
376
-        $expiry = DateTimeImmutable::createFromFormat("U", $this->identity->getExpirationTime());
377
-        $graceExpiry = $expiry->modify($gracePeriod);
378
-        $now = new DateTimeImmutable();
379
-
380
-        return $graceExpiry < $now;
381
-    }
382
-
383
-    /**
384
-     * Loads the OAuth identity from the database for the current user.
385
-     */
386
-    private function loadIdentity()
387
-    {
388
-        if ($this->identityLoaded) {
389
-            return;
390
-        }
391
-
392
-        $statement = $this->database->prepare('SELECT * FROM oauthidentity WHERE user = :user');
393
-        $statement->execute(array(':user' => $this->user->getId()));
394
-        /** @var OAuthIdentity $obj */
395
-        $obj = $statement->fetchObject(OAuthIdentity::class);
396
-
397
-        if ($obj === false) {
398
-            // failed to load identity.
399
-            $this->identityLoaded = true;
400
-            $this->identity = null;
401
-
402
-            return;
403
-        }
404
-
405
-        $obj->setDatabase($this->database);
406
-        $this->identityLoaded = true;
407
-        $this->identity = $obj;
408
-    }
409
-
410
-    /**
411
-     * @return OAuthToken
412
-     * @throws OAuthException
413
-     */
414
-    private function loadAccessToken()
415
-    {
416
-        if (!$this->accessTokenLoaded) {
417
-            $this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_ACCESS));
418
-            /** @var OAuthToken $token */
419
-            $token = $this->getTokenStatement->fetchObject(OAuthToken::class);
420
-            $this->getTokenStatement->closeCursor();
421
-
422
-            if ($token === false) {
423
-                throw new OAuthException('Access token not found!');
424
-            }
425
-
426
-            $this->accessToken = $token;
427
-            $this->accessTokenLoaded = true;
428
-        }
429
-
430
-        return $this->accessToken;
431
-    }
73
+		);
74
+		$statement->execute(array(':type' => self::TOKEN_REQUEST, ':token' => $requestToken));
75
+
76
+		/** @var User $user */
77
+		$user = $statement->fetchObject(User::class);
78
+		$statement->closeCursor();
79
+
80
+		if ($user === false) {
81
+			throw new ApplicationLogicException('Token not found in store, please try again');
82
+		}
83
+
84
+		$user->setDatabase($database);
85
+
86
+		return $user;
87
+	}
88
+
89
+	public static function userIsFullyLinked(User $user, PdoDatabase $database = null)
90
+	{
91
+		if (self::$tokenCountStatement === null && $database === null) {
92
+			throw new ApplicationLogicException('Static link request without initialised statement');
93
+		}
94
+
95
+		return self::runTokenCount($user->getId(), $database, self::TOKEN_ACCESS);
96
+	}
97
+
98
+	public static function userIsPartiallyLinked(User $user, PdoDatabase $database = null)
99
+	{
100
+		if (self::$tokenCountStatement === null && $database === null) {
101
+			throw new ApplicationLogicException('Static link request without initialised statement');
102
+		}
103
+
104
+		if (self::userIsFullyLinked($user, $database)) {
105
+			return false;
106
+		}
107
+
108
+		return self::runTokenCount($user->getId(), $database, self::TOKEN_REQUEST)
109
+			|| $user->getOnWikiName() == null;
110
+	}
111
+
112
+	/**
113
+	 * @param PdoDatabase $database
114
+	 */
115
+	public static function prepareTokenCountStatement(PdoDatabase $database)
116
+	{
117
+		if (self::$tokenCountStatement === null) {
118
+			self::$tokenCountStatement = $database->prepare('SELECT COUNT(*) FROM oauthtoken WHERE user = :user AND type = :type');
119
+		}
120
+	}
121
+
122
+	private static function runTokenCount($userId, $database, $tokenType)
123
+	{
124
+		if (self::$tokenCountStatement === null) {
125
+			self::prepareTokenCountStatement($database);
126
+		}
127
+
128
+		self::$tokenCountStatement->execute(array(
129
+			':user' => $userId,
130
+			':type' => $tokenType,
131
+		));
132
+
133
+		$tokenCount = self::$tokenCountStatement->fetchColumn();
134
+		$linked = $tokenCount > 0;
135
+		self::$tokenCountStatement->closeCursor();
136
+
137
+		return $linked;
138
+	}
139
+
140
+	#endregion Static methods
141
+
142
+	/**
143
+	 * OAuthUserHelper constructor.
144
+	 *
145
+	 * @param User                 $user
146
+	 * @param PdoDatabase          $database
147
+	 * @param IOAuthProtocolHelper $oauthProtocolHelper
148
+	 * @param SiteConfiguration    $siteConfiguration
149
+	 */
150
+	public function __construct(
151
+		User $user,
152
+		PdoDatabase $database,
153
+		IOAuthProtocolHelper $oauthProtocolHelper,
154
+		SiteConfiguration $siteConfiguration
155
+	) {
156
+		$this->user = $user;
157
+		$this->database = $database;
158
+		$this->oauthProtocolHelper = $oauthProtocolHelper;
159
+
160
+		$this->linked = null;
161
+		$this->partiallyLinked = null;
162
+		$this->siteConfiguration = $siteConfiguration;
163
+
164
+		self::prepareTokenCountStatement($database);
165
+		$this->getTokenStatement = $this->database->prepare('SELECT * FROM oauthtoken WHERE user = :user AND type = :type');
166
+	}
167
+
168
+	/**
169
+	 * Determines if the user is fully connected to OAuth.
170
+	 *
171
+	 * @return bool
172
+	 */
173
+	public function isFullyLinked()
174
+	{
175
+		if ($this->linked === null) {
176
+			$this->linked = self::userIsFullyLinked($this->user, $this->database);
177
+		}
178
+
179
+		return $this->linked;
180
+	}
181
+
182
+	/**
183
+	 * Attempts to figure out if a user is partially linked to OAuth, and therefore needs to complete the OAuth
184
+	 * procedure before configuring.
185
+	 * @return bool
186
+	 */
187
+	public function isPartiallyLinked()
188
+	{
189
+		if ($this->partiallyLinked === null) {
190
+			$this->partiallyLinked = self::userIsPartiallyLinked($this->user, $this->database);
191
+		}
192
+
193
+		return $this->partiallyLinked;
194
+	}
195
+
196
+	/**
197
+	 * @throws OAuthException
198
+	 */
199
+	public function refreshIdentity()
200
+	{
201
+		$this->loadIdentity();
202
+
203
+		if ($this->identity === null) {
204
+			$this->identity = new OAuthIdentity();
205
+			$this->identity->setUserId($this->user->getId());
206
+			$this->identity->setDatabase($this->database);
207
+		}
208
+
209
+		$token = $this->loadAccessToken();
210
+
211
+		$rawTicket = $this->oauthProtocolHelper->getIdentityTicket($token->getToken(), $token->getSecret());
212
+
213
+		$this->identity->populate($rawTicket);
214
+
215
+		if (!$this->identityIsValid()) {
216
+			throw new OAuthException('Identity ticket is not valid!');
217
+		}
218
+
219
+		$this->identity->save();
220
+
221
+		$this->user->setOnWikiName($this->identity->getUsername());
222
+		$this->user->save();
223
+	}
224
+
225
+	public function getRequestToken()
226
+	{
227
+		$token = $this->oauthProtocolHelper->getRequestToken();
228
+
229
+		$this->partiallyLinked = true;
230
+		$this->linked = false;
231
+
232
+		$this->database
233
+			->prepare('DELETE FROM oauthtoken WHERE user = :user AND type = :type')
234
+			->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
235
+
236
+		$this->database
237
+			->prepare('INSERT INTO oauthtoken (user, type, token, secret, expiry) VALUES (:user, :type, :token, :secret, DATE_ADD(NOW(), INTERVAL 1 DAY))')
238
+			->execute(array(
239
+				':user'   => $this->user->getId(),
240
+				':type'   => self::TOKEN_REQUEST,
241
+				':token'  => $token->key,
242
+				':secret' => $token->secret,
243
+			));
244
+
245
+		return $this->oauthProtocolHelper->getAuthoriseUrl($token->key);
246
+	}
247
+
248
+	public function completeHandshake($verificationToken)
249
+	{
250
+		$this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
251
+
252
+		/** @var OAuthToken $token */
253
+		$token = $this->getTokenStatement->fetchObject(OAuthToken::class);
254
+		$this->getTokenStatement->closeCursor();
255
+
256
+		if ($token === false) {
257
+			throw new ApplicationLogicException('Cannot find request token');
258
+		}
259
+
260
+		$token->setDatabase($this->database);
261
+
262
+		$accessToken = $this->oauthProtocolHelper->callbackCompleted($token->getToken(), $token->getSecret(),
263
+			$verificationToken);
264
+
265
+		$clearStatement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :u AND type = :t');
266
+		$clearStatement->execute(array(':u' => $this->user->getId(), ':t' => self::TOKEN_ACCESS));
267
+
268
+		$token->setToken($accessToken->key);
269
+		$token->setSecret($accessToken->secret);
270
+		$token->setType(self::TOKEN_ACCESS);
271
+		$token->setExpiry(null);
272
+		$token->save();
273
+
274
+		$this->partiallyLinked = false;
275
+		$this->linked = true;
276
+
277
+		$this->refreshIdentity();
278
+	}
279
+
280
+	public function detach()
281
+	{
282
+		$this->loadIdentity();
283
+
284
+		$this->identity->delete();
285
+		$statement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :user');
286
+		$statement->execute(array(':user' => $this->user->getId()));
287
+
288
+		$this->identity = null;
289
+		$this->linked = false;
290
+		$this->partiallyLinked = false;
291
+	}
292
+
293
+	/**
294
+	 * @param bool $expiredOk
295
+	 *
296
+	 * @return OAuthIdentity
297
+	 * @throws OAuthException
298
+	 */
299
+	public function getIdentity($expiredOk = false)
300
+	{
301
+		$this->loadIdentity();
302
+
303
+		if (!$this->identityIsValid($expiredOk)) {
304
+			throw new OAuthException('Stored identity is not valid.');
305
+		}
306
+
307
+		return $this->identity;
308
+	}
309
+
310
+	public function doApiCall($params, $method)
311
+	{
312
+		// Ensure we're logged in
313
+		$params['assert'] = 'user';
314
+
315
+		$token = $this->loadAccessToken();
316
+		return $this->oauthProtocolHelper->apiCall($params, $token->getToken(), $token->getSecret(), $method);
317
+	}
318
+
319
+	/**
320
+	 * @param bool $expiredOk
321
+	 *
322
+	 * @return bool
323
+	 */
324
+	private function identityIsValid($expiredOk = false)
325
+	{
326
+		$this->loadIdentity();
327
+
328
+		if ($this->identity === null) {
329
+			return false;
330
+		}
331
+
332
+		if ($this->identity->getIssuedAtTime() === false
333
+			|| $this->identity->getExpirationTime() === false
334
+			|| $this->identity->getAudience() === false
335
+			|| $this->identity->getIssuer() === false
336
+		) {
337
+			// this isn't populated properly.
338
+			return false;
339
+		}
340
+
341
+		$issue = DateTimeImmutable::createFromFormat("U", $this->identity->getIssuedAtTime());
342
+		$now = new DateTimeImmutable();
343
+
344
+		if ($issue > $now) {
345
+			// wat.
346
+			return false;
347
+		}
348
+
349
+		if ($this->identityExpired() && !$expiredOk) {
350
+			// soz.
351
+			return false;
352
+		}
353
+
354
+		if ($this->identity->getAudience() !== $this->siteConfiguration->getOAuthConsumerToken()) {
355
+			// token not issued for us
356
+			return false;
357
+		}
358
+
359
+		if ($this->identity->getIssuer() !== $this->siteConfiguration->getOauthMediaWikiCanonicalServer()) {
360
+			// token not issued by the right person
361
+			return false;
362
+		}
363
+
364
+		// can't find a reason to not trust it
365
+		return true;
366
+	}
367
+
368
+	/**
369
+	 * @return bool
370
+	 */
371
+	public function identityExpired()
372
+	{
373
+		// allowed max age
374
+		$gracePeriod = $this->siteConfiguration->getOauthIdentityGraceTime();
375
+
376
+		$expiry = DateTimeImmutable::createFromFormat("U", $this->identity->getExpirationTime());
377
+		$graceExpiry = $expiry->modify($gracePeriod);
378
+		$now = new DateTimeImmutable();
379
+
380
+		return $graceExpiry < $now;
381
+	}
382
+
383
+	/**
384
+	 * Loads the OAuth identity from the database for the current user.
385
+	 */
386
+	private function loadIdentity()
387
+	{
388
+		if ($this->identityLoaded) {
389
+			return;
390
+		}
391
+
392
+		$statement = $this->database->prepare('SELECT * FROM oauthidentity WHERE user = :user');
393
+		$statement->execute(array(':user' => $this->user->getId()));
394
+		/** @var OAuthIdentity $obj */
395
+		$obj = $statement->fetchObject(OAuthIdentity::class);
396
+
397
+		if ($obj === false) {
398
+			// failed to load identity.
399
+			$this->identityLoaded = true;
400
+			$this->identity = null;
401
+
402
+			return;
403
+		}
404
+
405
+		$obj->setDatabase($this->database);
406
+		$this->identityLoaded = true;
407
+		$this->identity = $obj;
408
+	}
409
+
410
+	/**
411
+	 * @return OAuthToken
412
+	 * @throws OAuthException
413
+	 */
414
+	private function loadAccessToken()
415
+	{
416
+		if (!$this->accessTokenLoaded) {
417
+			$this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_ACCESS));
418
+			/** @var OAuthToken $token */
419
+			$token = $this->getTokenStatement->fetchObject(OAuthToken::class);
420
+			$this->getTokenStatement->closeCursor();
421
+
422
+			if ($token === false) {
423
+				throw new OAuthException('Access token not found!');
424
+			}
425
+
426
+			$this->accessToken = $token;
427
+			$this->accessTokenLoaded = true;
428
+		}
429
+
430
+		return $this->accessToken;
431
+	}
432 432
 }
433 433
\ No newline at end of file
Please login to merge, or discard this patch.
includes/API/Actions/StatsAction.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -20,58 +20,58 @@
 block discarded – undo
20 20
  */
21 21
 class StatsAction extends ApiPageBase implements IApiAction
22 22
 {
23
-    /**
24
-     * The target user
25
-     * @var User $user
26
-     */
27
-    private $user;
23
+	/**
24
+	 * The target user
25
+	 * @var User $user
26
+	 */
27
+	private $user;
28 28
 
29
-    /**
30
-     * Summary of execute
31
-     *
32
-     * @param \DOMElement $apiDocument
33
-     *
34
-     * @return \DOMElement
35
-     * @throws ApiException
36
-     * @throws \Exception
37
-     */
38
-    public function executeApiAction(\DOMElement $apiDocument)
39
-    {
40
-        $username = WebRequest::getString('user');
41
-        $wikiusername = WebRequest::getString('wikiuser');
29
+	/**
30
+	 * Summary of execute
31
+	 *
32
+	 * @param \DOMElement $apiDocument
33
+	 *
34
+	 * @return \DOMElement
35
+	 * @throws ApiException
36
+	 * @throws \Exception
37
+	 */
38
+	public function executeApiAction(\DOMElement $apiDocument)
39
+	{
40
+		$username = WebRequest::getString('user');
41
+		$wikiusername = WebRequest::getString('wikiuser');
42 42
 
43
-        if ($username === null && $wikiusername === null) {
44
-            throw new ApiException("Please specify a username using either user or wikiuser parameters.");
45
-        }
43
+		if ($username === null && $wikiusername === null) {
44
+			throw new ApiException("Please specify a username using either user or wikiuser parameters.");
45
+		}
46 46
 
47
-        $userElement = $this->document->createElement("user");
48
-        $apiDocument->appendChild($userElement);
47
+		$userElement = $this->document->createElement("user");
48
+		$apiDocument->appendChild($userElement);
49 49
 
50
-        if ($username !== null) {
51
-            $user = User::getByUsername($username, $this->getDatabase());
52
-        }
53
-        else {
54
-            $user = User::getByOnWikiUsername($wikiusername, $this->getDatabase());
55
-        }
50
+		if ($username !== null) {
51
+			$user = User::getByUsername($username, $this->getDatabase());
52
+		}
53
+		else {
54
+			$user = User::getByOnWikiUsername($wikiusername, $this->getDatabase());
55
+		}
56 56
 
57
-        if ($user === false) {
58
-            $userElement->setAttribute("missing", "true");
57
+		if ($user === false) {
58
+			$userElement->setAttribute("missing", "true");
59 59
 
60
-            return $apiDocument;
61
-        }
60
+			return $apiDocument;
61
+		}
62 62
 
63
-        $this->user = $user;
63
+		$this->user = $user;
64 64
 
65
-        $oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(),
66
-            $this->getSiteConfiguration());
65
+		$oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(),
66
+			$this->getSiteConfiguration());
67 67
 
68
-        $userElement->setAttribute("username", $this->user->getUsername());
69
-        $userElement->setAttribute("status", $this->user->getStatus());
70
-        $userElement->setAttribute("lastactive", $this->user->getLastActive());
71
-        $userElement->setAttribute("welcome_template", $this->user->getWelcomeTemplate());
72
-        $userElement->setAttribute("onwikiname", $this->user->getOnWikiName());
73
-        $userElement->setAttribute("oauth", $oauth->isFullyLinked() ? "true" : "false");
68
+		$userElement->setAttribute("username", $this->user->getUsername());
69
+		$userElement->setAttribute("status", $this->user->getStatus());
70
+		$userElement->setAttribute("lastactive", $this->user->getLastActive());
71
+		$userElement->setAttribute("welcome_template", $this->user->getWelcomeTemplate());
72
+		$userElement->setAttribute("onwikiname", $this->user->getOnWikiName());
73
+		$userElement->setAttribute("oauth", $oauth->isFullyLinked() ? "true" : "false");
74 74
 
75
-        return $apiDocument;
76
-    }
75
+		return $apiDocument;
76
+	}
77 77
 }
Please login to merge, or discard this patch.
includes/Helpers/Interfaces/IOAuthProtocolHelper.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -19,52 +19,52 @@
 block discarded – undo
19 19
 
20 20
 interface IOAuthProtocolHelper
21 21
 {
22
-    /**
23
-     * @return stdClass
24
-     *
25
-     * @throws Exception
26
-     * @throws CurlException
27
-     */
28
-    public function getRequestToken();
22
+	/**
23
+	 * @return stdClass
24
+	 *
25
+	 * @throws Exception
26
+	 * @throws CurlException
27
+	 */
28
+	public function getRequestToken();
29 29
 
30
-    /**
31
-     * @param string $requestToken
32
-     *
33
-     * @return string
34
-     */
35
-    public function getAuthoriseUrl($requestToken);
30
+	/**
31
+	 * @param string $requestToken
32
+	 *
33
+	 * @return string
34
+	 */
35
+	public function getAuthoriseUrl($requestToken);
36 36
 
37
-    /**
38
-     * @param string $oauthRequestToken
39
-     * @param string $oauthRequestSecret
40
-     * @param string $oauthVerifier
41
-     *
42
-     * @return stdClass
43
-     * @throws CurlException
44
-     * @throws Exception
45
-     */
46
-    public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
37
+	/**
38
+	 * @param string $oauthRequestToken
39
+	 * @param string $oauthRequestSecret
40
+	 * @param string $oauthVerifier
41
+	 *
42
+	 * @return stdClass
43
+	 * @throws CurlException
44
+	 * @throws Exception
45
+	 */
46
+	public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
47 47
 
48
-    /**
49
-     * @param string $oauthAccessToken
50
-     * @param string $oauthAccessSecret
51
-     *
52
-     * @return stdClass
53
-     * @throws CurlException
54
-     * @throws Exception
55
-     */
56
-    public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
48
+	/**
49
+	 * @param string $oauthAccessToken
50
+	 * @param string $oauthAccessSecret
51
+	 *
52
+	 * @return stdClass
53
+	 * @throws CurlException
54
+	 * @throws Exception
55
+	 */
56
+	public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
57 57
 
58
-    /**
59
-     * @param array  $apiParams    array of parameters to send to the API
60
-     * @param string $accessToken  user's access token
61
-     * @param string $accessSecret user's secret
62
-     * @param string $method       HTTP method
63
-     *
64
-     * @return stdClass
65
-     * @throws ApplicationLogicException
66
-     * @throws CurlException
67
-     * @throws Exception
68
-     */
69
-    public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
58
+	/**
59
+	 * @param array  $apiParams    array of parameters to send to the API
60
+	 * @param string $accessToken  user's access token
61
+	 * @param string $accessSecret user's secret
62
+	 * @param string $method       HTTP method
63
+	 *
64
+	 * @return stdClass
65
+	 * @throws ApplicationLogicException
66
+	 * @throws CurlException
67
+	 * @throws Exception
68
+	 */
69
+	public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
70 70
 }
71 71
\ No newline at end of file
Please login to merge, or discard this patch.