Passed
Push — smarty5 ( d2daf7...f9241d )
by Simon
08:18 queued 04:15
created
includes/Pages/PageUserManagement.php 1 patch
Indentation   +600 added lines, -600 removed lines patch added patch discarded remove patch
@@ -32,18 +32,18 @@  discard block
 block discarded – undo
32 32
  */
33 33
 class PageUserManagement extends InternalPageBase
34 34
 {
35
-    const OAUTH_STATE_NONE = 'none';
36
-    const OAUTH_STATE_PARTIAL = 'partial';
37
-    const OAUTH_STATE_FULL = 'full';
38
-
39
-    // FIXME: domains
40
-    /** @var string */
41
-    private $adminMailingList = '[email protected]';
42
-
43
-    private function getOAuthStatusMap(PdoDatabase $database): array
44
-    {
45
-        $oauthStatusQuery = $database->prepare(
46
-            <<<SQL
35
+	const OAUTH_STATE_NONE = 'none';
36
+	const OAUTH_STATE_PARTIAL = 'partial';
37
+	const OAUTH_STATE_FULL = 'full';
38
+
39
+	// FIXME: domains
40
+	/** @var string */
41
+	private $adminMailingList = '[email protected]';
42
+
43
+	private function getOAuthStatusMap(PdoDatabase $database): array
44
+	{
45
+		$oauthStatusQuery = $database->prepare(
46
+			<<<SQL
47 47
     SELECT u.id,
48 48
            CASE
49 49
                WHEN SUM(IF(ot.type = :access, 1, 0)) OVER (PARTITION BY ot.user) > 0 THEN :full
@@ -53,592 +53,592 @@  discard block
 block discarded – undo
53 53
     FROM user u 
54 54
     LEFT JOIN oauthtoken ot ON u.id = ot.user;
55 55
 SQL
56
-        );
57
-
58
-        $oauthStatusQuery->execute([
59
-            ':access' => OAuthUserHelper::TOKEN_ACCESS,
60
-            ':request' => OAuthUserHelper::TOKEN_REQUEST,
61
-            ':full' => self::OAUTH_STATE_FULL,
62
-            ':partial' => self::OAUTH_STATE_PARTIAL,
63
-            ':none' => self::OAUTH_STATE_NONE,
64
-        ]);
65
-        $oauthStatusRawData = $oauthStatusQuery->fetchAll(PDO::FETCH_ASSOC);
66
-        $oauthStatusQuery->closeCursor();
67
-        $oauthStatusMap = [];
68
-
69
-        foreach ($oauthStatusRawData as $row) {
70
-            $oauthStatusMap[(int)$row['id']] = $row['status'];
71
-        }
72
-
73
-        return $oauthStatusMap;
74
-    }
75
-
76
-    /**
77
-     * Main function for this page, when no specific actions are called.
78
-     */
79
-    protected function main()
80
-    {
81
-        $this->setHtmlTitle('User Management');
82
-
83
-        $database = $this->getDatabase();
84
-        $currentUser = User::getCurrent($database);
85
-
86
-        $userSearchRequest = WebRequest::getString('usersearch');
87
-        if ($userSearchRequest !== null) {
88
-            $searchedUser = User::getByUsername($userSearchRequest, $database);
89
-            if ($searchedUser !== false) {
90
-                $this->redirect('statistics/users', 'detail', ['user' => $searchedUser->getId()]);
91
-                return;
92
-            }
93
-        }
94
-
95
-        $this->assign('oauthStatusMap', $this->getOAuthStatusMap($database));
96
-
97
-        if (WebRequest::getBoolean("showAll")) {
98
-            $this->assign("showAll", true);
99
-
100
-            $deactivatedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_DEACTIVATED)->fetch();
101
-            $this->assign('deactivatedUsers', $deactivatedUsers);
102
-
103
-            UserSearchHelper::get($database)->getRoleMap($roleMap);
104
-        }
105
-        else {
106
-            $this->assign("showAll", false);
107
-            $this->assign('deactivatedUsers', array());
108
-
109
-            UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
110
-        }
111
-
112
-        $newUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch();
113
-        $normalUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch();
114
-        $adminUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch();
115
-        $checkUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch();
116
-        $stewards = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('steward')->fetch();
117
-        $toolRoots = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch();
118
-        $this->assign('newUsers', $newUsers);
119
-        $this->assign('normalUsers', $normalUsers);
120
-        $this->assign('adminUsers', $adminUsers);
121
-        $this->assign('checkUsers', $checkUsers);
122
-        $this->assign('stewards', $stewards);
123
-        $this->assign('toolRoots', $toolRoots);
124
-
125
-        $this->assign('roles', $roleMap);
126
-
127
-        $this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
128
-
129
-        $this->assign('canApprove', $this->barrierTest('approve', $currentUser));
130
-        $this->assign('canDeactivate', $this->barrierTest('deactivate', $currentUser));
131
-        $this->assign('canRename', $this->barrierTest('rename', $currentUser));
132
-        $this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
133
-        $this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
134
-
135
-        // FIXME: domains!
136
-        /** @var Domain $domain */
137
-        $domain = Domain::getById(1, $this->getDatabase());
138
-        $this->assign('mediawikiScriptPath', $domain->getWikiArticlePath());
139
-
140
-        $this->setTemplate("usermanagement/main.tpl");
141
-    }
142
-
143
-    #region Access control
144
-
145
-    /**
146
-     * Action target for editing the roles assigned to a user
147
-     *
148
-     * @throws ApplicationLogicException
149
-     * @throws SmartyException
150
-     * @throws OptimisticLockFailedException
151
-     * @throws Exception
152
-     */
153
-    protected function editRoles(): void
154
-    {
155
-        $this->setHtmlTitle('User Management');
156
-        $database = $this->getDatabase();
157
-        $domain = Domain::getCurrent($database);
158
-        $userId = WebRequest::getInt('user');
159
-
160
-        /** @var User|false $user */
161
-        $user = User::getById($userId, $database);
162
-
163
-        if ($user === false || $user->isCommunityUser()) {
164
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
165
-        }
166
-
167
-        $roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database, $domain->getId()));
168
-
169
-        // Dual-mode action
170
-        if (WebRequest::wasPosted()) {
171
-            $this->validateCSRFToken();
172
-
173
-            $reason = WebRequest::postString('reason');
174
-            if ($reason === false || trim($reason) === '') {
175
-                throw new ApplicationLogicException('No reason specified for roles change');
176
-            }
177
-
178
-            /** @var UserRole[] $delete */
179
-            $delete = array();
180
-            /** @var string[] $add */
181
-            $add = array();
182
-
183
-            /** @var UserRole[] $globalDelete */
184
-            $globalDelete = array();
185
-            /** @var string[] $globalAdd */
186
-            $globalAdd = array();
187
-
188
-            foreach ($roleData as $name => $r) {
189
-                if ($r['allowEdit'] !== 1) {
190
-                    // not allowed, to touch this, so ignore it
191
-                    continue;
192
-                }
193
-
194
-                $newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
195
-                if ($newValue !== $r['active']) {
196
-                    if ($newValue === 0) {
197
-                        if ($r['globalOnly']) {
198
-                            $globalDelete[] = $r['object'];
199
-                        }
200
-                        else {
201
-                            $delete[] = $r['object'];
202
-                        }
203
-                    }
204
-
205
-                    if ($newValue === 1) {
206
-                        if ($r['globalOnly']) {
207
-                            $globalAdd[] = $name;
208
-                        }
209
-                        else {
210
-                            $add[] = $name;
211
-                        }
212
-                    }
213
-                }
214
-            }
215
-
216
-            // Check there's something to do
217
-            if ((count($add) + count($delete) + count($globalAdd) + count($globalDelete)) === 0) {
218
-                $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
219
-                SessionAlert::warning('No changes made to roles.');
220
-
221
-                return;
222
-            }
223
-
224
-            $removed = array();
225
-            $globalRemoved = array();
226
-
227
-            foreach ($delete as $d) {
228
-                $removed[] = $d->getRole();
229
-                $d->delete();
230
-            }
231
-
232
-            foreach ($globalDelete as $d) {
233
-                $globalRemoved[] = $d->getRole();
234
-                $d->delete();
235
-            }
236
-
237
-            foreach ($add as $x) {
238
-                $a = new UserRole();
239
-                $a->setUser($user->getId());
240
-                $a->setRole($x);
241
-                $a->setDomain($domain->getId());
242
-                $a->setDatabase($database);
243
-                $a->save();
244
-            }
245
-
246
-            foreach ($globalAdd as $x) {
247
-                $a = new UserRole();
248
-                $a->setUser($user->getId());
249
-                $a->setRole($x);
250
-                $a->setDomain(null);
251
-                $a->setDatabase($database);
252
-                $a->save();
253
-            }
254
-
255
-            if ((count($add) + count($delete)) > 0) {
256
-                Logger::userRolesEdited($database, $user, $reason, $add, $removed, $domain->getId());
257
-            }
258
-
259
-            if ((count($globalAdd) + count($globalDelete)) > 0) {
260
-                Logger::userGlobalRolesEdited($database, $user, $reason, $globalAdd, $globalRemoved);
261
-            }
262
-
263
-            // dummy save for optimistic locking. If this fails, the entire txn will roll back.
264
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
265
-            $user->save();
266
-
267
-            $this->getNotificationHelper()->userRolesEdited($user, $reason);
268
-            SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
269
-
270
-            $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
271
-        }
272
-        else {
273
-            $this->assignCSRFToken();
274
-            $this->setTemplate('usermanagement/roleedit.tpl');
275
-            $this->assign('user', $user);
276
-            $this->assign('roleData', $roleData);
277
-        }
278
-    }
279
-
280
-    /**
281
-     * Action target for deactivating users
282
-     *
283
-     * @throws ApplicationLogicException
284
-     */
285
-    protected function deactivate()
286
-    {
287
-        $this->setHtmlTitle('User Management');
288
-
289
-        $database = $this->getDatabase();
290
-
291
-        $userId = WebRequest::getInt('user');
292
-
293
-        /** @var User $user */
294
-        $user = User::getById($userId, $database);
295
-
296
-        if ($user === false || $user->isCommunityUser()) {
297
-            throw new ApplicationLogicException('Sorry, the user you are trying to deactivate could not be found.');
298
-        }
299
-
300
-        if ($user->isDeactivated()) {
301
-            throw new ApplicationLogicException('Sorry, the user you are trying to deactivate is already deactivated.');
302
-        }
303
-
304
-        // Dual-mode action
305
-        if (WebRequest::wasPosted()) {
306
-            $this->validateCSRFToken();
307
-            $reason = WebRequest::postString('reason');
308
-
309
-            if ($reason === null || trim($reason) === '') {
310
-                throw new ApplicationLogicException('No reason provided');
311
-            }
312
-
313
-            $user->setStatus(User::STATUS_DEACTIVATED);
314
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
315
-            $user->save();
316
-            Logger::deactivatedUser($database, $user, $reason);
317
-
318
-            $this->getNotificationHelper()->userDeactivated($user);
319
-            SessionAlert::quick('Deactivated user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
320
-
321
-            // send email
322
-            $this->sendStatusChangeEmail(
323
-                'Your WP:ACC account has been deactivated',
324
-                'usermanagement/emails/deactivated.tpl',
325
-                $reason,
326
-                $user,
327
-                User::getCurrent($database)->getUsername()
328
-            );
329
-
330
-            $this->redirect('userManagement');
331
-
332
-            return;
333
-        }
334
-        else {
335
-            $this->assignCSRFToken();
336
-            $this->setTemplate('usermanagement/changelevel-reason.tpl');
337
-            $this->assign('user', $user);
338
-            $this->assign('status', User::STATUS_DEACTIVATED);
339
-            $this->assign("showReason", true);
340
-
341
-            if (WebRequest::getString('preload')) {
342
-                $this->assign('preload', WebRequest::getString('preload'));
343
-            }
344
-        }
345
-    }
346
-
347
-    /**
348
-     * Entry point for the approve action
349
-     *
350
-     * @throws ApplicationLogicException
351
-     */
352
-    protected function approve()
353
-    {
354
-        $this->setHtmlTitle('User Management');
355
-
356
-        $database = $this->getDatabase();
357
-
358
-        $userId = WebRequest::getInt('user');
359
-        $user = User::getById($userId, $database);
360
-
361
-        if ($user === false || $user->isCommunityUser()) {
362
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
363
-        }
364
-
365
-        if ($user->isActive()) {
366
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
367
-        }
368
-
369
-        // Dual-mode action
370
-        if (WebRequest::wasPosted()) {
371
-            $this->validateCSRFToken();
372
-            $user->setStatus(User::STATUS_ACTIVE);
373
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
374
-            $user->save();
375
-            Logger::approvedUser($database, $user);
376
-
377
-            $this->getNotificationHelper()->userApproved($user);
378
-            SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
379
-
380
-            // send email
381
-            $this->sendStatusChangeEmail(
382
-                'Your WP:ACC account has been approved',
383
-                'usermanagement/emails/approved.tpl',
384
-                null,
385
-                $user,
386
-                User::getCurrent($database)->getUsername()
387
-            );
388
-
389
-            $this->redirect("userManagement");
390
-
391
-            return;
392
-        }
393
-        else {
394
-            $this->assignCSRFToken();
395
-            $this->setTemplate("usermanagement/changelevel-reason.tpl");
396
-            $this->assign("user", $user);
397
-            $this->assign("status", "Active");
398
-            $this->assign("showReason", false);
399
-        }
400
-    }
401
-
402
-    #endregion
403
-
404
-    #region Renaming / Editing
405
-
406
-    /**
407
-     * Entry point for the rename action
408
-     *
409
-     * @throws ApplicationLogicException
410
-     */
411
-    protected function rename()
412
-    {
413
-        $this->setHtmlTitle('User Management');
414
-
415
-        $database = $this->getDatabase();
416
-
417
-        $userId = WebRequest::getInt('user');
418
-        $user = User::getById($userId, $database);
419
-
420
-        if ($user === false || $user->isCommunityUser()) {
421
-            throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
422
-        }
423
-
424
-        // Dual-mode action
425
-        if (WebRequest::wasPosted()) {
426
-            $this->validateCSRFToken();
427
-            $newUsername = WebRequest::postString('newname');
428
-
429
-            if ($newUsername === null || trim($newUsername) === "") {
430
-                throw new ApplicationLogicException('The new username cannot be empty');
431
-            }
432
-
433
-            if (User::getByUsername($newUsername, $database) != false) {
434
-                throw new ApplicationLogicException('The new username already exists');
435
-            }
436
-
437
-            $oldUsername = $user->getUsername();
438
-            $user->setUsername($newUsername);
439
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
440
-
441
-            $user->save();
442
-
443
-            $logEntryData = serialize(array(
444
-                'old' => $oldUsername,
445
-                'new' => $newUsername,
446
-            ));
447
-
448
-            Logger::renamedUser($database, $user, $logEntryData);
449
-
450
-            SessionAlert::quick("Changed User "
451
-                . htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
452
-                . " name to "
453
-                . htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
454
-
455
-            $this->getNotificationHelper()->userRenamed($user, $oldUsername);
456
-
457
-            // send an email to the user.
458
-            $this->assign('targetUsername', $user->getUsername());
459
-            $this->assign('toolAdmin', User::getCurrent($database)->getUsername());
460
-            $this->assign('oldUsername', $oldUsername);
461
-            $this->assign('mailingList', $this->adminMailingList);
462
-
463
-            // FIXME: domains!
464
-            /** @var Domain $domain */
465
-            $domain = Domain::getById(1, $database);
466
-            $this->getEmailHelper()->sendMail(
467
-                $this->adminMailingList,
468
-                $user->getEmail(),
469
-                'Your username on WP:ACC has been changed',
470
-                $this->fetchTemplate('usermanagement/emails/renamed.tpl')
471
-            );
472
-
473
-            $this->redirect("userManagement");
474
-
475
-            return;
476
-        }
477
-        else {
478
-            $this->assignCSRFToken();
479
-            $this->setTemplate('usermanagement/renameuser.tpl');
480
-            $this->assign('user', $user);
481
-        }
482
-    }
483
-
484
-    /**
485
-     * Entry point for the edit action
486
-     *
487
-     * @throws ApplicationLogicException
488
-     */
489
-    protected function editUser()
490
-    {
491
-        $this->setHtmlTitle('User Management');
492
-
493
-        $database = $this->getDatabase();
494
-
495
-        $userId = WebRequest::getInt('user');
496
-        $user = User::getById($userId, $database);
497
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
498
-
499
-        if ($user === false || $user->isCommunityUser()) {
500
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
501
-        }
502
-
503
-        // FIXME: domains
504
-        $prefs = new PreferenceManager($database, $user->getId(), 1);
505
-
506
-        // Dual-mode action
507
-        if (WebRequest::wasPosted()) {
508
-            $this->validateCSRFToken();
509
-            $newEmail = WebRequest::postEmail('user_email');
510
-            $newOnWikiName = WebRequest::postString('user_onwikiname');
511
-
512
-            if ($newEmail === null) {
513
-                throw new ApplicationLogicException('Invalid email address');
514
-            }
515
-
516
-            if ($this->validateUnusedEmail($newEmail, $userId)) {
517
-                throw new ApplicationLogicException('The specified email address is already in use.');
518
-            }
519
-
520
-            if (!($oauth->isFullyLinked() || $oauth->isPartiallyLinked())) {
521
-                if (trim($newOnWikiName) == "") {
522
-                    throw new ApplicationLogicException('New on-wiki username cannot be blank');
523
-                }
524
-
525
-                $user->setOnWikiName($newOnWikiName);
526
-            }
527
-
528
-            $user->setEmail($newEmail);
529
-
530
-            $prefs->setLocalPreference(PreferenceManager::PREF_CREATION_MODE, WebRequest::postInt('creationmode'));
531
-
532
-            $prefs->setLocalPreference(PreferenceManager::ADMIN_PREF_PREVENT_REACTIVATION, WebRequest::postBoolean('preventReactivation'));
533
-
534
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
535
-
536
-            $user->save();
537
-
538
-            Logger::userPreferencesChange($database, $user);
539
-            $this->getNotificationHelper()->userPrefChange($user);
540
-            SessionAlert::quick('Changes to user\'s preferences have been saved');
541
-
542
-            $this->redirect("userManagement");
543
-
544
-            return;
545
-        }
546
-        else {
547
-            $this->assignCSRFToken();
548
-            $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
549
-                $this->getSiteConfiguration());
550
-            $this->setTemplate('usermanagement/edituser.tpl');
551
-            $this->assign('user', $user);
552
-            $this->assign('oauth', $oauth);
553
-
554
-            $this->assign('preferredCreationMode', (int)$prefs->getPreference(PreferenceManager::PREF_CREATION_MODE));
555
-            $this->assign('emailSignature', $prefs->getPreference(PreferenceManager::PREF_EMAIL_SIGNATURE));
556
-
557
-            $this->assign('preventReactivation', $prefs->getPreference(PreferenceManager::ADMIN_PREF_PREVENT_REACTIVATION) ?? false);
558
-
559
-            $this->assign('canManualCreate',
560
-                $this->barrierTest(PreferenceManager::CREATION_MANUAL, $user, 'RequestCreation'));
561
-            $this->assign('canOauthCreate',
562
-                $this->barrierTest(PreferenceManager::CREATION_OAUTH, $user, 'RequestCreation'));
563
-            $this->assign('canBotCreate',
564
-                $this->barrierTest(PreferenceManager::CREATION_BOT, $user, 'RequestCreation'));
565
-        }
566
-    }
567
-
568
-    #endregion
569
-
570
-    private function validateUnusedEmail(string $email, int $userId) : bool {
571
-        $query = 'SELECT COUNT(id) FROM user WHERE email = :email AND id <> :uid';
572
-        $statement = $this->getDatabase()->prepare($query);
573
-        $statement->execute(array(':email' => $email, ':uid' => $userId));
574
-        $inUse = $statement->fetchColumn() > 0;
575
-        $statement->closeCursor();
576
-
577
-        return $inUse;
578
-    }
579
-
580
-    /**
581
-     * Sends a status change email to the user.
582
-     *
583
-     * @param string      $subject           The subject of the email
584
-     * @param string      $template          The smarty template to use
585
-     * @param string|null $reason            The reason for performing the status change
586
-     * @param User        $user              The user affected
587
-     * @param string      $toolAdminUsername The tool admin's username who is making the edit
588
-     */
589
-    private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
590
-    {
591
-        $this->assign('targetUsername', $user->getUsername());
592
-        $this->assign('toolAdmin', $toolAdminUsername);
593
-        $this->assign('actionReason', $reason);
594
-        $this->assign('mailingList', $this->adminMailingList);
595
-
596
-        // FIXME: domains!
597
-        /** @var Domain $domain */
598
-        $domain = Domain::getById(1, $this->getDatabase());
599
-        $this->getEmailHelper()->sendMail(
600
-            $this->adminMailingList,
601
-            $user->getEmail(),
602
-            $subject,
603
-            $this->fetchTemplate($template)
604
-        );
605
-    }
606
-
607
-    /**
608
-     * @param UserRole[] $activeRoles
609
-     *
610
-     * @return array
611
-     */
612
-    private function getRoleData($activeRoles)
613
-    {
614
-        $availableRoles = $this->getSecurityManager()->getAvailableRoles();
615
-
616
-        $currentUser = User::getCurrent($this->getDatabase());
617
-        $this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
618
-
619
-        $initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
620
-
621
-        $roleData = array();
622
-        foreach ($availableRoles as $role => $data) {
623
-            $intersection = array_intersect($data['editableBy'], $userRoles);
624
-
625
-            $roleData[$role] = $initialValue;
626
-            $roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
627
-            $roleData[$role]['description'] = $data['description'];
628
-            $roleData[$role]['globalOnly'] = $data['globalOnly'];
629
-        }
630
-
631
-        foreach ($activeRoles as $role) {
632
-            if (!isset($roleData[$role->getRole()])) {
633
-                // This value is no longer available in the configuration, allow changing (aka removing) it.
634
-                $roleData[$role->getRole()] = $initialValue;
635
-                $roleData[$role->getRole()]['allowEdit'] = 1;
636
-            }
637
-
638
-            $roleData[$role->getRole()]['object'] = $role;
639
-            $roleData[$role->getRole()]['active'] = 1;
640
-        }
641
-
642
-        return $roleData;
643
-    }
56
+		);
57
+
58
+		$oauthStatusQuery->execute([
59
+			':access' => OAuthUserHelper::TOKEN_ACCESS,
60
+			':request' => OAuthUserHelper::TOKEN_REQUEST,
61
+			':full' => self::OAUTH_STATE_FULL,
62
+			':partial' => self::OAUTH_STATE_PARTIAL,
63
+			':none' => self::OAUTH_STATE_NONE,
64
+		]);
65
+		$oauthStatusRawData = $oauthStatusQuery->fetchAll(PDO::FETCH_ASSOC);
66
+		$oauthStatusQuery->closeCursor();
67
+		$oauthStatusMap = [];
68
+
69
+		foreach ($oauthStatusRawData as $row) {
70
+			$oauthStatusMap[(int)$row['id']] = $row['status'];
71
+		}
72
+
73
+		return $oauthStatusMap;
74
+	}
75
+
76
+	/**
77
+	 * Main function for this page, when no specific actions are called.
78
+	 */
79
+	protected function main()
80
+	{
81
+		$this->setHtmlTitle('User Management');
82
+
83
+		$database = $this->getDatabase();
84
+		$currentUser = User::getCurrent($database);
85
+
86
+		$userSearchRequest = WebRequest::getString('usersearch');
87
+		if ($userSearchRequest !== null) {
88
+			$searchedUser = User::getByUsername($userSearchRequest, $database);
89
+			if ($searchedUser !== false) {
90
+				$this->redirect('statistics/users', 'detail', ['user' => $searchedUser->getId()]);
91
+				return;
92
+			}
93
+		}
94
+
95
+		$this->assign('oauthStatusMap', $this->getOAuthStatusMap($database));
96
+
97
+		if (WebRequest::getBoolean("showAll")) {
98
+			$this->assign("showAll", true);
99
+
100
+			$deactivatedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_DEACTIVATED)->fetch();
101
+			$this->assign('deactivatedUsers', $deactivatedUsers);
102
+
103
+			UserSearchHelper::get($database)->getRoleMap($roleMap);
104
+		}
105
+		else {
106
+			$this->assign("showAll", false);
107
+			$this->assign('deactivatedUsers', array());
108
+
109
+			UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
110
+		}
111
+
112
+		$newUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch();
113
+		$normalUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch();
114
+		$adminUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch();
115
+		$checkUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch();
116
+		$stewards = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('steward')->fetch();
117
+		$toolRoots = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch();
118
+		$this->assign('newUsers', $newUsers);
119
+		$this->assign('normalUsers', $normalUsers);
120
+		$this->assign('adminUsers', $adminUsers);
121
+		$this->assign('checkUsers', $checkUsers);
122
+		$this->assign('stewards', $stewards);
123
+		$this->assign('toolRoots', $toolRoots);
124
+
125
+		$this->assign('roles', $roleMap);
126
+
127
+		$this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
128
+
129
+		$this->assign('canApprove', $this->barrierTest('approve', $currentUser));
130
+		$this->assign('canDeactivate', $this->barrierTest('deactivate', $currentUser));
131
+		$this->assign('canRename', $this->barrierTest('rename', $currentUser));
132
+		$this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
133
+		$this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
134
+
135
+		// FIXME: domains!
136
+		/** @var Domain $domain */
137
+		$domain = Domain::getById(1, $this->getDatabase());
138
+		$this->assign('mediawikiScriptPath', $domain->getWikiArticlePath());
139
+
140
+		$this->setTemplate("usermanagement/main.tpl");
141
+	}
142
+
143
+	#region Access control
144
+
145
+	/**
146
+	 * Action target for editing the roles assigned to a user
147
+	 *
148
+	 * @throws ApplicationLogicException
149
+	 * @throws SmartyException
150
+	 * @throws OptimisticLockFailedException
151
+	 * @throws Exception
152
+	 */
153
+	protected function editRoles(): void
154
+	{
155
+		$this->setHtmlTitle('User Management');
156
+		$database = $this->getDatabase();
157
+		$domain = Domain::getCurrent($database);
158
+		$userId = WebRequest::getInt('user');
159
+
160
+		/** @var User|false $user */
161
+		$user = User::getById($userId, $database);
162
+
163
+		if ($user === false || $user->isCommunityUser()) {
164
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
165
+		}
166
+
167
+		$roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database, $domain->getId()));
168
+
169
+		// Dual-mode action
170
+		if (WebRequest::wasPosted()) {
171
+			$this->validateCSRFToken();
172
+
173
+			$reason = WebRequest::postString('reason');
174
+			if ($reason === false || trim($reason) === '') {
175
+				throw new ApplicationLogicException('No reason specified for roles change');
176
+			}
177
+
178
+			/** @var UserRole[] $delete */
179
+			$delete = array();
180
+			/** @var string[] $add */
181
+			$add = array();
182
+
183
+			/** @var UserRole[] $globalDelete */
184
+			$globalDelete = array();
185
+			/** @var string[] $globalAdd */
186
+			$globalAdd = array();
187
+
188
+			foreach ($roleData as $name => $r) {
189
+				if ($r['allowEdit'] !== 1) {
190
+					// not allowed, to touch this, so ignore it
191
+					continue;
192
+				}
193
+
194
+				$newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
195
+				if ($newValue !== $r['active']) {
196
+					if ($newValue === 0) {
197
+						if ($r['globalOnly']) {
198
+							$globalDelete[] = $r['object'];
199
+						}
200
+						else {
201
+							$delete[] = $r['object'];
202
+						}
203
+					}
204
+
205
+					if ($newValue === 1) {
206
+						if ($r['globalOnly']) {
207
+							$globalAdd[] = $name;
208
+						}
209
+						else {
210
+							$add[] = $name;
211
+						}
212
+					}
213
+				}
214
+			}
215
+
216
+			// Check there's something to do
217
+			if ((count($add) + count($delete) + count($globalAdd) + count($globalDelete)) === 0) {
218
+				$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
219
+				SessionAlert::warning('No changes made to roles.');
220
+
221
+				return;
222
+			}
223
+
224
+			$removed = array();
225
+			$globalRemoved = array();
226
+
227
+			foreach ($delete as $d) {
228
+				$removed[] = $d->getRole();
229
+				$d->delete();
230
+			}
231
+
232
+			foreach ($globalDelete as $d) {
233
+				$globalRemoved[] = $d->getRole();
234
+				$d->delete();
235
+			}
236
+
237
+			foreach ($add as $x) {
238
+				$a = new UserRole();
239
+				$a->setUser($user->getId());
240
+				$a->setRole($x);
241
+				$a->setDomain($domain->getId());
242
+				$a->setDatabase($database);
243
+				$a->save();
244
+			}
245
+
246
+			foreach ($globalAdd as $x) {
247
+				$a = new UserRole();
248
+				$a->setUser($user->getId());
249
+				$a->setRole($x);
250
+				$a->setDomain(null);
251
+				$a->setDatabase($database);
252
+				$a->save();
253
+			}
254
+
255
+			if ((count($add) + count($delete)) > 0) {
256
+				Logger::userRolesEdited($database, $user, $reason, $add, $removed, $domain->getId());
257
+			}
258
+
259
+			if ((count($globalAdd) + count($globalDelete)) > 0) {
260
+				Logger::userGlobalRolesEdited($database, $user, $reason, $globalAdd, $globalRemoved);
261
+			}
262
+
263
+			// dummy save for optimistic locking. If this fails, the entire txn will roll back.
264
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
265
+			$user->save();
266
+
267
+			$this->getNotificationHelper()->userRolesEdited($user, $reason);
268
+			SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
269
+
270
+			$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
271
+		}
272
+		else {
273
+			$this->assignCSRFToken();
274
+			$this->setTemplate('usermanagement/roleedit.tpl');
275
+			$this->assign('user', $user);
276
+			$this->assign('roleData', $roleData);
277
+		}
278
+	}
279
+
280
+	/**
281
+	 * Action target for deactivating users
282
+	 *
283
+	 * @throws ApplicationLogicException
284
+	 */
285
+	protected function deactivate()
286
+	{
287
+		$this->setHtmlTitle('User Management');
288
+
289
+		$database = $this->getDatabase();
290
+
291
+		$userId = WebRequest::getInt('user');
292
+
293
+		/** @var User $user */
294
+		$user = User::getById($userId, $database);
295
+
296
+		if ($user === false || $user->isCommunityUser()) {
297
+			throw new ApplicationLogicException('Sorry, the user you are trying to deactivate could not be found.');
298
+		}
299
+
300
+		if ($user->isDeactivated()) {
301
+			throw new ApplicationLogicException('Sorry, the user you are trying to deactivate is already deactivated.');
302
+		}
303
+
304
+		// Dual-mode action
305
+		if (WebRequest::wasPosted()) {
306
+			$this->validateCSRFToken();
307
+			$reason = WebRequest::postString('reason');
308
+
309
+			if ($reason === null || trim($reason) === '') {
310
+				throw new ApplicationLogicException('No reason provided');
311
+			}
312
+
313
+			$user->setStatus(User::STATUS_DEACTIVATED);
314
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
315
+			$user->save();
316
+			Logger::deactivatedUser($database, $user, $reason);
317
+
318
+			$this->getNotificationHelper()->userDeactivated($user);
319
+			SessionAlert::quick('Deactivated user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
320
+
321
+			// send email
322
+			$this->sendStatusChangeEmail(
323
+				'Your WP:ACC account has been deactivated',
324
+				'usermanagement/emails/deactivated.tpl',
325
+				$reason,
326
+				$user,
327
+				User::getCurrent($database)->getUsername()
328
+			);
329
+
330
+			$this->redirect('userManagement');
331
+
332
+			return;
333
+		}
334
+		else {
335
+			$this->assignCSRFToken();
336
+			$this->setTemplate('usermanagement/changelevel-reason.tpl');
337
+			$this->assign('user', $user);
338
+			$this->assign('status', User::STATUS_DEACTIVATED);
339
+			$this->assign("showReason", true);
340
+
341
+			if (WebRequest::getString('preload')) {
342
+				$this->assign('preload', WebRequest::getString('preload'));
343
+			}
344
+		}
345
+	}
346
+
347
+	/**
348
+	 * Entry point for the approve action
349
+	 *
350
+	 * @throws ApplicationLogicException
351
+	 */
352
+	protected function approve()
353
+	{
354
+		$this->setHtmlTitle('User Management');
355
+
356
+		$database = $this->getDatabase();
357
+
358
+		$userId = WebRequest::getInt('user');
359
+		$user = User::getById($userId, $database);
360
+
361
+		if ($user === false || $user->isCommunityUser()) {
362
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
363
+		}
364
+
365
+		if ($user->isActive()) {
366
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
367
+		}
368
+
369
+		// Dual-mode action
370
+		if (WebRequest::wasPosted()) {
371
+			$this->validateCSRFToken();
372
+			$user->setStatus(User::STATUS_ACTIVE);
373
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
374
+			$user->save();
375
+			Logger::approvedUser($database, $user);
376
+
377
+			$this->getNotificationHelper()->userApproved($user);
378
+			SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
379
+
380
+			// send email
381
+			$this->sendStatusChangeEmail(
382
+				'Your WP:ACC account has been approved',
383
+				'usermanagement/emails/approved.tpl',
384
+				null,
385
+				$user,
386
+				User::getCurrent($database)->getUsername()
387
+			);
388
+
389
+			$this->redirect("userManagement");
390
+
391
+			return;
392
+		}
393
+		else {
394
+			$this->assignCSRFToken();
395
+			$this->setTemplate("usermanagement/changelevel-reason.tpl");
396
+			$this->assign("user", $user);
397
+			$this->assign("status", "Active");
398
+			$this->assign("showReason", false);
399
+		}
400
+	}
401
+
402
+	#endregion
403
+
404
+	#region Renaming / Editing
405
+
406
+	/**
407
+	 * Entry point for the rename action
408
+	 *
409
+	 * @throws ApplicationLogicException
410
+	 */
411
+	protected function rename()
412
+	{
413
+		$this->setHtmlTitle('User Management');
414
+
415
+		$database = $this->getDatabase();
416
+
417
+		$userId = WebRequest::getInt('user');
418
+		$user = User::getById($userId, $database);
419
+
420
+		if ($user === false || $user->isCommunityUser()) {
421
+			throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
422
+		}
423
+
424
+		// Dual-mode action
425
+		if (WebRequest::wasPosted()) {
426
+			$this->validateCSRFToken();
427
+			$newUsername = WebRequest::postString('newname');
428
+
429
+			if ($newUsername === null || trim($newUsername) === "") {
430
+				throw new ApplicationLogicException('The new username cannot be empty');
431
+			}
432
+
433
+			if (User::getByUsername($newUsername, $database) != false) {
434
+				throw new ApplicationLogicException('The new username already exists');
435
+			}
436
+
437
+			$oldUsername = $user->getUsername();
438
+			$user->setUsername($newUsername);
439
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
440
+
441
+			$user->save();
442
+
443
+			$logEntryData = serialize(array(
444
+				'old' => $oldUsername,
445
+				'new' => $newUsername,
446
+			));
447
+
448
+			Logger::renamedUser($database, $user, $logEntryData);
449
+
450
+			SessionAlert::quick("Changed User "
451
+				. htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
452
+				. " name to "
453
+				. htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
454
+
455
+			$this->getNotificationHelper()->userRenamed($user, $oldUsername);
456
+
457
+			// send an email to the user.
458
+			$this->assign('targetUsername', $user->getUsername());
459
+			$this->assign('toolAdmin', User::getCurrent($database)->getUsername());
460
+			$this->assign('oldUsername', $oldUsername);
461
+			$this->assign('mailingList', $this->adminMailingList);
462
+
463
+			// FIXME: domains!
464
+			/** @var Domain $domain */
465
+			$domain = Domain::getById(1, $database);
466
+			$this->getEmailHelper()->sendMail(
467
+				$this->adminMailingList,
468
+				$user->getEmail(),
469
+				'Your username on WP:ACC has been changed',
470
+				$this->fetchTemplate('usermanagement/emails/renamed.tpl')
471
+			);
472
+
473
+			$this->redirect("userManagement");
474
+
475
+			return;
476
+		}
477
+		else {
478
+			$this->assignCSRFToken();
479
+			$this->setTemplate('usermanagement/renameuser.tpl');
480
+			$this->assign('user', $user);
481
+		}
482
+	}
483
+
484
+	/**
485
+	 * Entry point for the edit action
486
+	 *
487
+	 * @throws ApplicationLogicException
488
+	 */
489
+	protected function editUser()
490
+	{
491
+		$this->setHtmlTitle('User Management');
492
+
493
+		$database = $this->getDatabase();
494
+
495
+		$userId = WebRequest::getInt('user');
496
+		$user = User::getById($userId, $database);
497
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
498
+
499
+		if ($user === false || $user->isCommunityUser()) {
500
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
501
+		}
502
+
503
+		// FIXME: domains
504
+		$prefs = new PreferenceManager($database, $user->getId(), 1);
505
+
506
+		// Dual-mode action
507
+		if (WebRequest::wasPosted()) {
508
+			$this->validateCSRFToken();
509
+			$newEmail = WebRequest::postEmail('user_email');
510
+			$newOnWikiName = WebRequest::postString('user_onwikiname');
511
+
512
+			if ($newEmail === null) {
513
+				throw new ApplicationLogicException('Invalid email address');
514
+			}
515
+
516
+			if ($this->validateUnusedEmail($newEmail, $userId)) {
517
+				throw new ApplicationLogicException('The specified email address is already in use.');
518
+			}
519
+
520
+			if (!($oauth->isFullyLinked() || $oauth->isPartiallyLinked())) {
521
+				if (trim($newOnWikiName) == "") {
522
+					throw new ApplicationLogicException('New on-wiki username cannot be blank');
523
+				}
524
+
525
+				$user->setOnWikiName($newOnWikiName);
526
+			}
527
+
528
+			$user->setEmail($newEmail);
529
+
530
+			$prefs->setLocalPreference(PreferenceManager::PREF_CREATION_MODE, WebRequest::postInt('creationmode'));
531
+
532
+			$prefs->setLocalPreference(PreferenceManager::ADMIN_PREF_PREVENT_REACTIVATION, WebRequest::postBoolean('preventReactivation'));
533
+
534
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
535
+
536
+			$user->save();
537
+
538
+			Logger::userPreferencesChange($database, $user);
539
+			$this->getNotificationHelper()->userPrefChange($user);
540
+			SessionAlert::quick('Changes to user\'s preferences have been saved');
541
+
542
+			$this->redirect("userManagement");
543
+
544
+			return;
545
+		}
546
+		else {
547
+			$this->assignCSRFToken();
548
+			$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
549
+				$this->getSiteConfiguration());
550
+			$this->setTemplate('usermanagement/edituser.tpl');
551
+			$this->assign('user', $user);
552
+			$this->assign('oauth', $oauth);
553
+
554
+			$this->assign('preferredCreationMode', (int)$prefs->getPreference(PreferenceManager::PREF_CREATION_MODE));
555
+			$this->assign('emailSignature', $prefs->getPreference(PreferenceManager::PREF_EMAIL_SIGNATURE));
556
+
557
+			$this->assign('preventReactivation', $prefs->getPreference(PreferenceManager::ADMIN_PREF_PREVENT_REACTIVATION) ?? false);
558
+
559
+			$this->assign('canManualCreate',
560
+				$this->barrierTest(PreferenceManager::CREATION_MANUAL, $user, 'RequestCreation'));
561
+			$this->assign('canOauthCreate',
562
+				$this->barrierTest(PreferenceManager::CREATION_OAUTH, $user, 'RequestCreation'));
563
+			$this->assign('canBotCreate',
564
+				$this->barrierTest(PreferenceManager::CREATION_BOT, $user, 'RequestCreation'));
565
+		}
566
+	}
567
+
568
+	#endregion
569
+
570
+	private function validateUnusedEmail(string $email, int $userId) : bool {
571
+		$query = 'SELECT COUNT(id) FROM user WHERE email = :email AND id <> :uid';
572
+		$statement = $this->getDatabase()->prepare($query);
573
+		$statement->execute(array(':email' => $email, ':uid' => $userId));
574
+		$inUse = $statement->fetchColumn() > 0;
575
+		$statement->closeCursor();
576
+
577
+		return $inUse;
578
+	}
579
+
580
+	/**
581
+	 * Sends a status change email to the user.
582
+	 *
583
+	 * @param string      $subject           The subject of the email
584
+	 * @param string      $template          The smarty template to use
585
+	 * @param string|null $reason            The reason for performing the status change
586
+	 * @param User        $user              The user affected
587
+	 * @param string      $toolAdminUsername The tool admin's username who is making the edit
588
+	 */
589
+	private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
590
+	{
591
+		$this->assign('targetUsername', $user->getUsername());
592
+		$this->assign('toolAdmin', $toolAdminUsername);
593
+		$this->assign('actionReason', $reason);
594
+		$this->assign('mailingList', $this->adminMailingList);
595
+
596
+		// FIXME: domains!
597
+		/** @var Domain $domain */
598
+		$domain = Domain::getById(1, $this->getDatabase());
599
+		$this->getEmailHelper()->sendMail(
600
+			$this->adminMailingList,
601
+			$user->getEmail(),
602
+			$subject,
603
+			$this->fetchTemplate($template)
604
+		);
605
+	}
606
+
607
+	/**
608
+	 * @param UserRole[] $activeRoles
609
+	 *
610
+	 * @return array
611
+	 */
612
+	private function getRoleData($activeRoles)
613
+	{
614
+		$availableRoles = $this->getSecurityManager()->getAvailableRoles();
615
+
616
+		$currentUser = User::getCurrent($this->getDatabase());
617
+		$this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
618
+
619
+		$initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
620
+
621
+		$roleData = array();
622
+		foreach ($availableRoles as $role => $data) {
623
+			$intersection = array_intersect($data['editableBy'], $userRoles);
624
+
625
+			$roleData[$role] = $initialValue;
626
+			$roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
627
+			$roleData[$role]['description'] = $data['description'];
628
+			$roleData[$role]['globalOnly'] = $data['globalOnly'];
629
+		}
630
+
631
+		foreach ($activeRoles as $role) {
632
+			if (!isset($roleData[$role->getRole()])) {
633
+				// This value is no longer available in the configuration, allow changing (aka removing) it.
634
+				$roleData[$role->getRole()] = $initialValue;
635
+				$roleData[$role->getRole()]['allowEdit'] = 1;
636
+			}
637
+
638
+			$roleData[$role->getRole()]['object'] = $role;
639
+			$roleData[$role->getRole()]['active'] = 1;
640
+		}
641
+
642
+		return $roleData;
643
+	}
644 644
 }
Please login to merge, or discard this patch.
includes/Helpers/OAuthUserHelper.php 1 patch
Indentation   +452 added lines, -452 removed lines patch added patch discarded remove patch
@@ -26,460 +26,460 @@
 block discarded – undo
26 26
 
27 27
 class OAuthUserHelper implements IMediaWikiClient
28 28
 {
29
-    const TOKEN_REQUEST = 'request';
30
-    const TOKEN_ACCESS = 'access';
31
-    /** @var PDOStatement */
32
-    private static $tokenCountStatement = null;
33
-    /** @var PDOStatement */
34
-    private $getTokenStatement;
35
-    /**
36
-     * @var User
37
-     */
38
-    private $user;
39
-    /**
40
-     * @var PdoDatabase
41
-     */
42
-    private $database;
43
-    /**
44
-     * @var IOAuthProtocolHelper
45
-     */
46
-    private $oauthProtocolHelper;
47
-    /**
48
-     * @var bool|null Is the user linked to OAuth
49
-     */
50
-    private $linked;
51
-    private $partiallyLinked;
52
-    /** @var OAuthToken */
53
-    private $accessToken;
54
-    /** @var bool */
55
-    private $accessTokenLoaded = false;
56
-    /**
57
-     * @var OAuthIdentity
58
-     */
59
-    private $identity = null;
60
-    /**
61
-     * @var bool
62
-     */
63
-    private $identityLoaded = false;
64
-    /**
65
-     * @var SiteConfiguration
66
-     */
67
-    private $siteConfiguration;
68
-
69
-    private $legacyTokens;
70
-
71
-    #region Static methods
72
-
73
-    public static function findUserByRequestToken($requestToken, PdoDatabase $database)
74
-    {
75
-        $statement = $database->prepare(<<<'SQL'
29
+	const TOKEN_REQUEST = 'request';
30
+	const TOKEN_ACCESS = 'access';
31
+	/** @var PDOStatement */
32
+	private static $tokenCountStatement = null;
33
+	/** @var PDOStatement */
34
+	private $getTokenStatement;
35
+	/**
36
+	 * @var User
37
+	 */
38
+	private $user;
39
+	/**
40
+	 * @var PdoDatabase
41
+	 */
42
+	private $database;
43
+	/**
44
+	 * @var IOAuthProtocolHelper
45
+	 */
46
+	private $oauthProtocolHelper;
47
+	/**
48
+	 * @var bool|null Is the user linked to OAuth
49
+	 */
50
+	private $linked;
51
+	private $partiallyLinked;
52
+	/** @var OAuthToken */
53
+	private $accessToken;
54
+	/** @var bool */
55
+	private $accessTokenLoaded = false;
56
+	/**
57
+	 * @var OAuthIdentity
58
+	 */
59
+	private $identity = null;
60
+	/**
61
+	 * @var bool
62
+	 */
63
+	private $identityLoaded = false;
64
+	/**
65
+	 * @var SiteConfiguration
66
+	 */
67
+	private $siteConfiguration;
68
+
69
+	private $legacyTokens;
70
+
71
+	#region Static methods
72
+
73
+	public static function findUserByRequestToken($requestToken, PdoDatabase $database)
74
+	{
75
+		$statement = $database->prepare(<<<'SQL'
76 76
             SELECT u.* FROM user u 
77 77
             INNER JOIN oauthtoken t ON t.user = u.id 
78 78
             WHERE t.type = :type AND t.token = :token
79 79
 SQL
80
-        );
81
-        $statement->execute(array(':type' => self::TOKEN_REQUEST, ':token' => $requestToken));
82
-
83
-        /** @var User $user */
84
-        $user = $statement->fetchObject(User::class);
85
-        $statement->closeCursor();
86
-
87
-        if ($user === false) {
88
-            throw new ApplicationLogicException('Token not found in store, please try again');
89
-        }
90
-
91
-        $user->setDatabase($database);
92
-
93
-        return $user;
94
-    }
95
-
96
-    private static function userIsFullyLinked(User $user, PdoDatabase $database = null)
97
-    {
98
-        if (self::$tokenCountStatement === null && $database === null) {
99
-            throw new ApplicationLogicException('Static link request without initialised statement');
100
-        }
101
-
102
-        return self::runTokenCount($user->getId(), $database, self::TOKEN_ACCESS);
103
-    }
104
-
105
-    private static function userIsPartiallyLinked(User $user, PdoDatabase $database = null)
106
-    {
107
-        if (self::$tokenCountStatement === null && $database === null) {
108
-            throw new ApplicationLogicException('Static link request without initialised statement');
109
-        }
110
-
111
-        if (self::userIsFullyLinked($user, $database)) {
112
-            return false;
113
-        }
114
-
115
-        return self::runTokenCount($user->getId(), $database, self::TOKEN_REQUEST)
116
-            || $user->getOnWikiName() == null;
117
-    }
118
-
119
-    /**
120
-     * @param PdoDatabase $database
121
-     */
122
-    private static function prepareTokenCountStatement(PdoDatabase $database)
123
-    {
124
-        if (self::$tokenCountStatement === null) {
125
-            self::$tokenCountStatement = $database->prepare('SELECT COUNT(*) FROM oauthtoken WHERE user = :user AND type = :type');
126
-        }
127
-    }
128
-
129
-    private static function runTokenCount($userId, $database, $tokenType)
130
-    {
131
-        if (self::$tokenCountStatement === null) {
132
-            self::prepareTokenCountStatement($database);
133
-        }
134
-
135
-        self::$tokenCountStatement->execute(array(
136
-            ':user' => $userId,
137
-            ':type' => $tokenType,
138
-        ));
139
-
140
-        $tokenCount = self::$tokenCountStatement->fetchColumn();
141
-        $linked = $tokenCount > 0;
142
-        self::$tokenCountStatement->closeCursor();
143
-
144
-        return $linked;
145
-    }
146
-
147
-    #endregion Static methods
148
-
149
-    /**
150
-     * OAuthUserHelper constructor.
151
-     *
152
-     * @param User                 $user
153
-     * @param PdoDatabase          $database
154
-     * @param IOAuthProtocolHelper $oauthProtocolHelper
155
-     * @param SiteConfiguration    $siteConfiguration
156
-     */
157
-    public function __construct(
158
-        User $user,
159
-        PdoDatabase $database,
160
-        IOAuthProtocolHelper $oauthProtocolHelper,
161
-        SiteConfiguration $siteConfiguration
162
-    ) {
163
-        $this->user = $user;
164
-        $this->database = $database;
165
-        $this->oauthProtocolHelper = $oauthProtocolHelper;
166
-
167
-        $this->linked = null;
168
-        $this->partiallyLinked = null;
169
-        $this->siteConfiguration = $siteConfiguration;
170
-
171
-        self::prepareTokenCountStatement($database);
172
-        $this->getTokenStatement = $this->database->prepare('SELECT * FROM oauthtoken WHERE user = :user AND type = :type');
173
-
174
-        $this->legacyTokens = $this->siteConfiguration->getOauthLegacyConsumerTokens();
175
-    }
176
-
177
-    /**
178
-     * Determines if the user is fully connected to OAuth.
179
-     *
180
-     * @return bool
181
-     */
182
-    public function isFullyLinked()
183
-    {
184
-        if ($this->linked === null) {
185
-            $this->linked = self::userIsFullyLinked($this->user, $this->database);
186
-        }
187
-
188
-        return $this->linked;
189
-    }
190
-
191
-    /**
192
-     * Attempts to figure out if a user is partially linked to OAuth, and therefore needs to complete the OAuth
193
-     * procedure before configuring.
194
-     * @return bool
195
-     */
196
-    public function isPartiallyLinked()
197
-    {
198
-        if ($this->partiallyLinked === null) {
199
-            $this->partiallyLinked = self::userIsPartiallyLinked($this->user, $this->database);
200
-        }
201
-
202
-        return $this->partiallyLinked;
203
-    }
204
-
205
-    public function canCreateAccount()
206
-    {
207
-        return $this->isFullyLinked()
208
-            && $this->getIdentity(true)->getGrantBasic()
209
-            && $this->getIdentity(true)->getGrantHighVolume()
210
-            && $this->getIdentity(true)->getGrantCreateAccount();
211
-    }
212
-
213
-    public function canWelcome()
214
-    {
215
-        return $this->isFullyLinked()
216
-            && $this->getIdentity(true)->getGrantBasic()
217
-            && $this->getIdentity(true)->getGrantHighVolume()
218
-            && $this->getIdentity(true)->getGrantCreateEditMovePage();
219
-    }
220
-
221
-    /**
222
-     * @throws OAuthException
223
-     * @throws CurlException
224
-     * @throws OptimisticLockFailedException
225
-     * @throws Exception
226
-     */
227
-    public function refreshIdentity()
228
-    {
229
-        $this->loadIdentity();
230
-
231
-        if ($this->identity === null) {
232
-            $this->identity = new OAuthIdentity();
233
-            $this->identity->setUserId($this->user->getId());
234
-            $this->identity->setDatabase($this->database);
235
-        }
236
-
237
-        $token = $this->loadAccessToken();
238
-
239
-        try {
240
-            $rawTicket = $this->oauthProtocolHelper->getIdentityTicket($token->getToken(), $token->getSecret());
241
-        }
242
-        catch (Exception $ex) {
243
-            if (strpos($ex->getMessage(), "mwoauthdatastore-access-token-not-found") !== false) {
244
-                throw new OAuthException('No approved grants for this access token.', -1, $ex);
245
-            }
246
-
247
-            throw $ex;
248
-        }
249
-
250
-        $this->identity->populate($rawTicket);
251
-
252
-        if (!$this->identityIsValid()) {
253
-            throw new OAuthException('Identity ticket is not valid!');
254
-        }
255
-
256
-        $this->identity->save();
257
-
258
-        $this->user->setOnWikiName($this->identity->getUsername());
259
-        $this->user->save();
260
-    }
261
-
262
-    /**
263
-     * @return string
264
-     * @throws CurlException
265
-     */
266
-    public function getRequestToken()
267
-    {
268
-        $token = $this->oauthProtocolHelper->getRequestToken();
269
-
270
-        $this->partiallyLinked = true;
271
-        $this->linked = false;
272
-
273
-        $this->database
274
-            ->prepare('DELETE FROM oauthtoken WHERE user = :user AND type = :type')
275
-            ->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
276
-
277
-        $this->database
278
-            ->prepare('INSERT INTO oauthtoken (user, type, token, secret, expiry) VALUES (:user, :type, :token, :secret, DATE_ADD(NOW(), INTERVAL 1 DAY))')
279
-            ->execute(array(
280
-                ':user'   => $this->user->getId(),
281
-                ':type'   => self::TOKEN_REQUEST,
282
-                ':token'  => $token->key,
283
-                ':secret' => $token->secret,
284
-            ));
285
-
286
-        return $this->oauthProtocolHelper->getAuthoriseUrl($token->key);
287
-    }
288
-
289
-    /**
290
-     * @param $verificationToken
291
-     *
292
-     * @throws ApplicationLogicException
293
-     * @throws CurlException
294
-     * @throws OAuthException
295
-     * @throws OptimisticLockFailedException
296
-     */
297
-    public function completeHandshake($verificationToken)
298
-    {
299
-        $this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
300
-
301
-        /** @var OAuthToken $token */
302
-        $token = $this->getTokenStatement->fetchObject(OAuthToken::class);
303
-        $this->getTokenStatement->closeCursor();
304
-
305
-        if ($token === false) {
306
-            throw new ApplicationLogicException('Cannot find request token');
307
-        }
308
-
309
-        $token->setDatabase($this->database);
310
-
311
-        $accessToken = $this->oauthProtocolHelper->callbackCompleted($token->getToken(), $token->getSecret(),
312
-            $verificationToken);
313
-
314
-        $clearStatement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :u AND type = :t');
315
-        $clearStatement->execute(array(':u' => $this->user->getId(), ':t' => self::TOKEN_ACCESS));
316
-
317
-        $token->setToken($accessToken->key);
318
-        $token->setSecret($accessToken->secret);
319
-        $token->setType(self::TOKEN_ACCESS);
320
-        $token->setExpiry(null);
321
-        $token->save();
322
-
323
-        $this->partiallyLinked = false;
324
-        $this->linked = true;
325
-
326
-        $this->refreshIdentity();
327
-    }
328
-
329
-    public function detach()
330
-    {
331
-        $this->loadIdentity();
332
-
333
-        $this->identity->delete();
334
-        $statement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :user');
335
-        $statement->execute(array(':user' => $this->user->getId()));
336
-
337
-        $this->identity = null;
338
-        $this->linked = false;
339
-        $this->partiallyLinked = false;
340
-    }
341
-
342
-    /**
343
-     * @param bool $expiredOk
344
-     *
345
-     * @return OAuthIdentity
346
-     * @throws OAuthException
347
-     */
348
-    public function getIdentity($expiredOk = false)
349
-    {
350
-        $this->loadIdentity();
351
-
352
-        if (!$this->identityIsValid($expiredOk)) {
353
-            throw new OAuthException('Stored identity is not valid.');
354
-        }
355
-
356
-        return $this->identity;
357
-    }
358
-
359
-    public function doApiCall($params, $method)
360
-    {
361
-        // Ensure we're logged in
362
-        $params['assert'] = 'user';
363
-
364
-        $token = $this->loadAccessToken();
365
-        return $this->oauthProtocolHelper->apiCall($params, $token->getToken(), $token->getSecret(), $method);
366
-    }
367
-
368
-    /**
369
-     * @param bool $expiredOk
370
-     *
371
-     * @return bool
372
-     */
373
-    private function identityIsValid($expiredOk = false)
374
-    {
375
-        $this->loadIdentity();
376
-
377
-        if ($this->identity === null) {
378
-            return false;
379
-        }
380
-
381
-        if ($this->identity->getIssuedAtTime() === false
382
-            || $this->identity->getExpirationTime() === false
383
-            || $this->identity->getAudience() === false
384
-            || $this->identity->getIssuer() === false
385
-        ) {
386
-            // this isn't populated properly.
387
-            return false;
388
-        }
389
-
390
-        $issue = DateTimeImmutable::createFromFormat("U", $this->identity->getIssuedAtTime());
391
-        $now = new DateTimeImmutable();
392
-
393
-        if ($issue > $now) {
394
-            // wat.
395
-            return false;
396
-        }
397
-
398
-        if ($this->identityExpired() && !$expiredOk) {
399
-            // soz.
400
-            return false;
401
-        }
402
-
403
-        if ($this->identity->getAudience() !== $this->siteConfiguration->getOAuthConsumerToken()) {
404
-            // token not issued for us
405
-
406
-            // we allow cases where the cache is expired and the cache is for a legacy token
407
-            if (!($expiredOk && in_array($this->identity->getAudience(), $this->legacyTokens))) {
408
-                return false;
409
-            }
410
-        }
411
-
412
-        if ($this->identity->getIssuer() !== $this->siteConfiguration->getOauthMediaWikiCanonicalServer()) {
413
-            // token not issued by the right person
414
-            return false;
415
-        }
416
-
417
-        // can't find a reason to not trust it
418
-        return true;
419
-    }
420
-
421
-    /**
422
-     * @return bool
423
-     */
424
-    public function identityExpired()
425
-    {
426
-        // allowed max age
427
-        $gracePeriod = $this->siteConfiguration->getOauthIdentityGraceTime();
428
-
429
-        $expiry = DateTimeImmutable::createFromFormat("U", $this->identity->getExpirationTime());
430
-        $graceExpiry = $expiry->modify($gracePeriod);
431
-        $now = new DateTimeImmutable();
432
-
433
-        return $graceExpiry < $now;
434
-    }
435
-
436
-    /**
437
-     * Loads the OAuth identity from the database for the current user.
438
-     */
439
-    private function loadIdentity()
440
-    {
441
-        if ($this->identityLoaded) {
442
-            return;
443
-        }
444
-
445
-        $statement = $this->database->prepare('SELECT * FROM oauthidentity WHERE user = :user');
446
-        $statement->execute(array(':user' => $this->user->getId()));
447
-        /** @var OAuthIdentity $obj */
448
-        $obj = $statement->fetchObject(OAuthIdentity::class);
449
-
450
-        if ($obj === false) {
451
-            // failed to load identity.
452
-            $this->identityLoaded = true;
453
-            $this->identity = null;
454
-
455
-            return;
456
-        }
457
-
458
-        $obj->setDatabase($this->database);
459
-        $this->identityLoaded = true;
460
-        $this->identity = $obj;
461
-    }
462
-
463
-    /**
464
-     * @return OAuthToken
465
-     * @throws OAuthException
466
-     */
467
-    private function loadAccessToken()
468
-    {
469
-        if (!$this->accessTokenLoaded) {
470
-            $this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_ACCESS));
471
-            /** @var OAuthToken $token */
472
-            $token = $this->getTokenStatement->fetchObject(OAuthToken::class);
473
-            $this->getTokenStatement->closeCursor();
474
-
475
-            if ($token === false) {
476
-                throw new OAuthException('Access token not found!');
477
-            }
478
-
479
-            $this->accessToken = $token;
480
-            $this->accessTokenLoaded = true;
481
-        }
482
-
483
-        return $this->accessToken;
484
-    }
80
+		);
81
+		$statement->execute(array(':type' => self::TOKEN_REQUEST, ':token' => $requestToken));
82
+
83
+		/** @var User $user */
84
+		$user = $statement->fetchObject(User::class);
85
+		$statement->closeCursor();
86
+
87
+		if ($user === false) {
88
+			throw new ApplicationLogicException('Token not found in store, please try again');
89
+		}
90
+
91
+		$user->setDatabase($database);
92
+
93
+		return $user;
94
+	}
95
+
96
+	private static function userIsFullyLinked(User $user, PdoDatabase $database = null)
97
+	{
98
+		if (self::$tokenCountStatement === null && $database === null) {
99
+			throw new ApplicationLogicException('Static link request without initialised statement');
100
+		}
101
+
102
+		return self::runTokenCount($user->getId(), $database, self::TOKEN_ACCESS);
103
+	}
104
+
105
+	private static function userIsPartiallyLinked(User $user, PdoDatabase $database = null)
106
+	{
107
+		if (self::$tokenCountStatement === null && $database === null) {
108
+			throw new ApplicationLogicException('Static link request without initialised statement');
109
+		}
110
+
111
+		if (self::userIsFullyLinked($user, $database)) {
112
+			return false;
113
+		}
114
+
115
+		return self::runTokenCount($user->getId(), $database, self::TOKEN_REQUEST)
116
+			|| $user->getOnWikiName() == null;
117
+	}
118
+
119
+	/**
120
+	 * @param PdoDatabase $database
121
+	 */
122
+	private static function prepareTokenCountStatement(PdoDatabase $database)
123
+	{
124
+		if (self::$tokenCountStatement === null) {
125
+			self::$tokenCountStatement = $database->prepare('SELECT COUNT(*) FROM oauthtoken WHERE user = :user AND type = :type');
126
+		}
127
+	}
128
+
129
+	private static function runTokenCount($userId, $database, $tokenType)
130
+	{
131
+		if (self::$tokenCountStatement === null) {
132
+			self::prepareTokenCountStatement($database);
133
+		}
134
+
135
+		self::$tokenCountStatement->execute(array(
136
+			':user' => $userId,
137
+			':type' => $tokenType,
138
+		));
139
+
140
+		$tokenCount = self::$tokenCountStatement->fetchColumn();
141
+		$linked = $tokenCount > 0;
142
+		self::$tokenCountStatement->closeCursor();
143
+
144
+		return $linked;
145
+	}
146
+
147
+	#endregion Static methods
148
+
149
+	/**
150
+	 * OAuthUserHelper constructor.
151
+	 *
152
+	 * @param User                 $user
153
+	 * @param PdoDatabase          $database
154
+	 * @param IOAuthProtocolHelper $oauthProtocolHelper
155
+	 * @param SiteConfiguration    $siteConfiguration
156
+	 */
157
+	public function __construct(
158
+		User $user,
159
+		PdoDatabase $database,
160
+		IOAuthProtocolHelper $oauthProtocolHelper,
161
+		SiteConfiguration $siteConfiguration
162
+	) {
163
+		$this->user = $user;
164
+		$this->database = $database;
165
+		$this->oauthProtocolHelper = $oauthProtocolHelper;
166
+
167
+		$this->linked = null;
168
+		$this->partiallyLinked = null;
169
+		$this->siteConfiguration = $siteConfiguration;
170
+
171
+		self::prepareTokenCountStatement($database);
172
+		$this->getTokenStatement = $this->database->prepare('SELECT * FROM oauthtoken WHERE user = :user AND type = :type');
173
+
174
+		$this->legacyTokens = $this->siteConfiguration->getOauthLegacyConsumerTokens();
175
+	}
176
+
177
+	/**
178
+	 * Determines if the user is fully connected to OAuth.
179
+	 *
180
+	 * @return bool
181
+	 */
182
+	public function isFullyLinked()
183
+	{
184
+		if ($this->linked === null) {
185
+			$this->linked = self::userIsFullyLinked($this->user, $this->database);
186
+		}
187
+
188
+		return $this->linked;
189
+	}
190
+
191
+	/**
192
+	 * Attempts to figure out if a user is partially linked to OAuth, and therefore needs to complete the OAuth
193
+	 * procedure before configuring.
194
+	 * @return bool
195
+	 */
196
+	public function isPartiallyLinked()
197
+	{
198
+		if ($this->partiallyLinked === null) {
199
+			$this->partiallyLinked = self::userIsPartiallyLinked($this->user, $this->database);
200
+		}
201
+
202
+		return $this->partiallyLinked;
203
+	}
204
+
205
+	public function canCreateAccount()
206
+	{
207
+		return $this->isFullyLinked()
208
+			&& $this->getIdentity(true)->getGrantBasic()
209
+			&& $this->getIdentity(true)->getGrantHighVolume()
210
+			&& $this->getIdentity(true)->getGrantCreateAccount();
211
+	}
212
+
213
+	public function canWelcome()
214
+	{
215
+		return $this->isFullyLinked()
216
+			&& $this->getIdentity(true)->getGrantBasic()
217
+			&& $this->getIdentity(true)->getGrantHighVolume()
218
+			&& $this->getIdentity(true)->getGrantCreateEditMovePage();
219
+	}
220
+
221
+	/**
222
+	 * @throws OAuthException
223
+	 * @throws CurlException
224
+	 * @throws OptimisticLockFailedException
225
+	 * @throws Exception
226
+	 */
227
+	public function refreshIdentity()
228
+	{
229
+		$this->loadIdentity();
230
+
231
+		if ($this->identity === null) {
232
+			$this->identity = new OAuthIdentity();
233
+			$this->identity->setUserId($this->user->getId());
234
+			$this->identity->setDatabase($this->database);
235
+		}
236
+
237
+		$token = $this->loadAccessToken();
238
+
239
+		try {
240
+			$rawTicket = $this->oauthProtocolHelper->getIdentityTicket($token->getToken(), $token->getSecret());
241
+		}
242
+		catch (Exception $ex) {
243
+			if (strpos($ex->getMessage(), "mwoauthdatastore-access-token-not-found") !== false) {
244
+				throw new OAuthException('No approved grants for this access token.', -1, $ex);
245
+			}
246
+
247
+			throw $ex;
248
+		}
249
+
250
+		$this->identity->populate($rawTicket);
251
+
252
+		if (!$this->identityIsValid()) {
253
+			throw new OAuthException('Identity ticket is not valid!');
254
+		}
255
+
256
+		$this->identity->save();
257
+
258
+		$this->user->setOnWikiName($this->identity->getUsername());
259
+		$this->user->save();
260
+	}
261
+
262
+	/**
263
+	 * @return string
264
+	 * @throws CurlException
265
+	 */
266
+	public function getRequestToken()
267
+	{
268
+		$token = $this->oauthProtocolHelper->getRequestToken();
269
+
270
+		$this->partiallyLinked = true;
271
+		$this->linked = false;
272
+
273
+		$this->database
274
+			->prepare('DELETE FROM oauthtoken WHERE user = :user AND type = :type')
275
+			->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
276
+
277
+		$this->database
278
+			->prepare('INSERT INTO oauthtoken (user, type, token, secret, expiry) VALUES (:user, :type, :token, :secret, DATE_ADD(NOW(), INTERVAL 1 DAY))')
279
+			->execute(array(
280
+				':user'   => $this->user->getId(),
281
+				':type'   => self::TOKEN_REQUEST,
282
+				':token'  => $token->key,
283
+				':secret' => $token->secret,
284
+			));
285
+
286
+		return $this->oauthProtocolHelper->getAuthoriseUrl($token->key);
287
+	}
288
+
289
+	/**
290
+	 * @param $verificationToken
291
+	 *
292
+	 * @throws ApplicationLogicException
293
+	 * @throws CurlException
294
+	 * @throws OAuthException
295
+	 * @throws OptimisticLockFailedException
296
+	 */
297
+	public function completeHandshake($verificationToken)
298
+	{
299
+		$this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
300
+
301
+		/** @var OAuthToken $token */
302
+		$token = $this->getTokenStatement->fetchObject(OAuthToken::class);
303
+		$this->getTokenStatement->closeCursor();
304
+
305
+		if ($token === false) {
306
+			throw new ApplicationLogicException('Cannot find request token');
307
+		}
308
+
309
+		$token->setDatabase($this->database);
310
+
311
+		$accessToken = $this->oauthProtocolHelper->callbackCompleted($token->getToken(), $token->getSecret(),
312
+			$verificationToken);
313
+
314
+		$clearStatement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :u AND type = :t');
315
+		$clearStatement->execute(array(':u' => $this->user->getId(), ':t' => self::TOKEN_ACCESS));
316
+
317
+		$token->setToken($accessToken->key);
318
+		$token->setSecret($accessToken->secret);
319
+		$token->setType(self::TOKEN_ACCESS);
320
+		$token->setExpiry(null);
321
+		$token->save();
322
+
323
+		$this->partiallyLinked = false;
324
+		$this->linked = true;
325
+
326
+		$this->refreshIdentity();
327
+	}
328
+
329
+	public function detach()
330
+	{
331
+		$this->loadIdentity();
332
+
333
+		$this->identity->delete();
334
+		$statement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :user');
335
+		$statement->execute(array(':user' => $this->user->getId()));
336
+
337
+		$this->identity = null;
338
+		$this->linked = false;
339
+		$this->partiallyLinked = false;
340
+	}
341
+
342
+	/**
343
+	 * @param bool $expiredOk
344
+	 *
345
+	 * @return OAuthIdentity
346
+	 * @throws OAuthException
347
+	 */
348
+	public function getIdentity($expiredOk = false)
349
+	{
350
+		$this->loadIdentity();
351
+
352
+		if (!$this->identityIsValid($expiredOk)) {
353
+			throw new OAuthException('Stored identity is not valid.');
354
+		}
355
+
356
+		return $this->identity;
357
+	}
358
+
359
+	public function doApiCall($params, $method)
360
+	{
361
+		// Ensure we're logged in
362
+		$params['assert'] = 'user';
363
+
364
+		$token = $this->loadAccessToken();
365
+		return $this->oauthProtocolHelper->apiCall($params, $token->getToken(), $token->getSecret(), $method);
366
+	}
367
+
368
+	/**
369
+	 * @param bool $expiredOk
370
+	 *
371
+	 * @return bool
372
+	 */
373
+	private function identityIsValid($expiredOk = false)
374
+	{
375
+		$this->loadIdentity();
376
+
377
+		if ($this->identity === null) {
378
+			return false;
379
+		}
380
+
381
+		if ($this->identity->getIssuedAtTime() === false
382
+			|| $this->identity->getExpirationTime() === false
383
+			|| $this->identity->getAudience() === false
384
+			|| $this->identity->getIssuer() === false
385
+		) {
386
+			// this isn't populated properly.
387
+			return false;
388
+		}
389
+
390
+		$issue = DateTimeImmutable::createFromFormat("U", $this->identity->getIssuedAtTime());
391
+		$now = new DateTimeImmutable();
392
+
393
+		if ($issue > $now) {
394
+			// wat.
395
+			return false;
396
+		}
397
+
398
+		if ($this->identityExpired() && !$expiredOk) {
399
+			// soz.
400
+			return false;
401
+		}
402
+
403
+		if ($this->identity->getAudience() !== $this->siteConfiguration->getOAuthConsumerToken()) {
404
+			// token not issued for us
405
+
406
+			// we allow cases where the cache is expired and the cache is for a legacy token
407
+			if (!($expiredOk && in_array($this->identity->getAudience(), $this->legacyTokens))) {
408
+				return false;
409
+			}
410
+		}
411
+
412
+		if ($this->identity->getIssuer() !== $this->siteConfiguration->getOauthMediaWikiCanonicalServer()) {
413
+			// token not issued by the right person
414
+			return false;
415
+		}
416
+
417
+		// can't find a reason to not trust it
418
+		return true;
419
+	}
420
+
421
+	/**
422
+	 * @return bool
423
+	 */
424
+	public function identityExpired()
425
+	{
426
+		// allowed max age
427
+		$gracePeriod = $this->siteConfiguration->getOauthIdentityGraceTime();
428
+
429
+		$expiry = DateTimeImmutable::createFromFormat("U", $this->identity->getExpirationTime());
430
+		$graceExpiry = $expiry->modify($gracePeriod);
431
+		$now = new DateTimeImmutable();
432
+
433
+		return $graceExpiry < $now;
434
+	}
435
+
436
+	/**
437
+	 * Loads the OAuth identity from the database for the current user.
438
+	 */
439
+	private function loadIdentity()
440
+	{
441
+		if ($this->identityLoaded) {
442
+			return;
443
+		}
444
+
445
+		$statement = $this->database->prepare('SELECT * FROM oauthidentity WHERE user = :user');
446
+		$statement->execute(array(':user' => $this->user->getId()));
447
+		/** @var OAuthIdentity $obj */
448
+		$obj = $statement->fetchObject(OAuthIdentity::class);
449
+
450
+		if ($obj === false) {
451
+			// failed to load identity.
452
+			$this->identityLoaded = true;
453
+			$this->identity = null;
454
+
455
+			return;
456
+		}
457
+
458
+		$obj->setDatabase($this->database);
459
+		$this->identityLoaded = true;
460
+		$this->identity = $obj;
461
+	}
462
+
463
+	/**
464
+	 * @return OAuthToken
465
+	 * @throws OAuthException
466
+	 */
467
+	private function loadAccessToken()
468
+	{
469
+		if (!$this->accessTokenLoaded) {
470
+			$this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_ACCESS));
471
+			/** @var OAuthToken $token */
472
+			$token = $this->getTokenStatement->fetchObject(OAuthToken::class);
473
+			$this->getTokenStatement->closeCursor();
474
+
475
+			if ($token === false) {
476
+				throw new OAuthException('Access token not found!');
477
+			}
478
+
479
+			$this->accessToken = $token;
480
+			$this->accessTokenLoaded = true;
481
+		}
482
+
483
+		return $this->accessToken;
484
+	}
485 485
 }
Please login to merge, or discard this patch.
includes/Fragments/TemplateOutput.php 1 patch
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -19,130 +19,130 @@
 block discarded – undo
19 19
 
20 20
 trait TemplateOutput
21 21
 {
22
-    /** @var Smarty */
23
-    private $smarty;
24
-
25
-    /**
26
-     * @param string $pluginsDir
27
-     *
28
-     * @return void
29
-     * @throws Exception
30
-     */
31
-    private function loadPlugins(string $pluginsDir): void
32
-    {
33
-        /** @var DirectoryIterator $file */
34
-        foreach (new DirectoryIterator($pluginsDir) as $file) {
35
-            if ($file->isDot()) {
36
-                continue;
37
-            }
38
-
39
-            if ($file->getExtension() != 'php') {
40
-                continue;
41
-            }
42
-
43
-            require_once $file->getPathname();
44
-
45
-            list($type, $name) = explode('.', $file->getBasename('.php'), 2);
46
-
47
-            switch ($type) {
48
-                case 'modifier':
49
-                    $this->smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, $name, 'smarty_modifier_' . $name);
50
-                    break;
51
-                case 'function':
52
-                    $this->smarty->registerPlugin(Smarty::PLUGIN_FUNCTION, $name, 'smarty_function_' . $name);
53
-                    break;
54
-            }
55
-        }
56
-    }
57
-
58
-    /**
59
-     * @return SiteConfiguration
60
-     */
61
-    protected abstract function getSiteConfiguration();
62
-
63
-    /**
64
-     * Assigns a Smarty variable
65
-     *
66
-     * @param  array|string $name  the template variable name(s)
67
-     * @param  mixed        $value the value to assign
68
-     */
69
-    final protected function assign($name, $value)
70
-    {
71
-        $this->smarty->assign($name, $value);
72
-    }
73
-
74
-    /**
75
-     * Sets up the variables used by the main Smarty base template.
76
-     *
77
-     * This list is getting kinda long.
78
-     * @throws Exception
79
-     */
80
-    final protected function setUpSmarty()
81
-    {
82
-        $this->smarty = new Smarty();
83
-        $pluginsDir = $this->getSiteConfiguration()->getFilePath() . '/smarty-plugins';
84
-
85
-        // Dynamically load all plugins in the plugins directory
86
-        $this->loadPlugins($pluginsDir);
87
-
88
-        $this->assign('currentUser', User::getCommunity());
89
-        $this->assign('skin', 'auto');
90
-        $this->assign('currentDomain', null);
91
-        $this->assign('loggedIn', false);
92
-        $this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
93
-        $this->assign('resourceCacheEpoch', $this->getSiteConfiguration()->getResourceCacheEpoch());
94
-        $this->assign('serverPathInfo', WebRequest::pathInfo());
95
-
96
-        $this->assign('siteNoticeText', '');
97
-        $this->assign('siteNoticeVersion', 0);
98
-        $this->assign('siteNoticeState', 'd-none');
99
-        $this->assign('toolversion', Environment::getToolVersion());
100
-
101
-        // default these
102
-        $this->assign('onlineusers', array());
103
-        $this->assign('typeAheadBlock', '');
104
-        $this->assign('extraJs', array());
105
-
106
-        // nav menu access control
107
-        $this->assign('nav__canRequests', false);
108
-        $this->assign('nav__canLogs', false);
109
-        $this->assign('nav__canUsers', false);
110
-        $this->assign('nav__canSearch', false);
111
-        $this->assign('nav__canStats', false);
112
-        $this->assign('nav__canBan', false);
113
-        $this->assign('nav__canEmailMgmt', false);
114
-        $this->assign('nav__canWelcomeMgmt', false);
115
-        $this->assign('nav__canSiteNoticeMgmt', false);
116
-        $this->assign('nav__canUserMgmt', false);
117
-        $this->assign('nav__canViewRequest', false);
118
-        $this->assign('nav__canJobQueue', false);
119
-        $this->assign('nav__canFlaggedComments', false);
120
-        $this->assign('nav__canDomainMgmt', false);
121
-        $this->assign('nav__canQueueMgmt', false);
122
-        $this->assign('nav__canFormMgmt', false);
123
-        $this->assign('nav__canErrorLog', false);
124
-
125
-        // Navigation badges for concern areas.
126
-        $this->assign("nav__numAdmin", 0);
127
-        $this->assign("nav__numFlaggedComments", 0);
128
-        $this->assign("nav__numJobQueueFailed", 0);
129
-
130
-        // debug helpers
131
-        $this->assign('showDebugCssBreakpoints', $this->getSiteConfiguration()->getDebuggingCssBreakpointsEnabled());
132
-
133
-        $this->assign('page', $this);
134
-    }
135
-
136
-    /**
137
-     * Fetches a rendered Smarty template
138
-     *
139
-     * @param $template string Template file path, relative to /templates/
140
-     *
141
-     * @return string Templated HTML
142
-     * @throws Exception
143
-     */
144
-    final protected function fetchTemplate($template)
145
-    {
146
-        return $this->smarty->fetch($template);
147
-    }
22
+	/** @var Smarty */
23
+	private $smarty;
24
+
25
+	/**
26
+	 * @param string $pluginsDir
27
+	 *
28
+	 * @return void
29
+	 * @throws Exception
30
+	 */
31
+	private function loadPlugins(string $pluginsDir): void
32
+	{
33
+		/** @var DirectoryIterator $file */
34
+		foreach (new DirectoryIterator($pluginsDir) as $file) {
35
+			if ($file->isDot()) {
36
+				continue;
37
+			}
38
+
39
+			if ($file->getExtension() != 'php') {
40
+				continue;
41
+			}
42
+
43
+			require_once $file->getPathname();
44
+
45
+			list($type, $name) = explode('.', $file->getBasename('.php'), 2);
46
+
47
+			switch ($type) {
48
+				case 'modifier':
49
+					$this->smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, $name, 'smarty_modifier_' . $name);
50
+					break;
51
+				case 'function':
52
+					$this->smarty->registerPlugin(Smarty::PLUGIN_FUNCTION, $name, 'smarty_function_' . $name);
53
+					break;
54
+			}
55
+		}
56
+	}
57
+
58
+	/**
59
+	 * @return SiteConfiguration
60
+	 */
61
+	protected abstract function getSiteConfiguration();
62
+
63
+	/**
64
+	 * Assigns a Smarty variable
65
+	 *
66
+	 * @param  array|string $name  the template variable name(s)
67
+	 * @param  mixed        $value the value to assign
68
+	 */
69
+	final protected function assign($name, $value)
70
+	{
71
+		$this->smarty->assign($name, $value);
72
+	}
73
+
74
+	/**
75
+	 * Sets up the variables used by the main Smarty base template.
76
+	 *
77
+	 * This list is getting kinda long.
78
+	 * @throws Exception
79
+	 */
80
+	final protected function setUpSmarty()
81
+	{
82
+		$this->smarty = new Smarty();
83
+		$pluginsDir = $this->getSiteConfiguration()->getFilePath() . '/smarty-plugins';
84
+
85
+		// Dynamically load all plugins in the plugins directory
86
+		$this->loadPlugins($pluginsDir);
87
+
88
+		$this->assign('currentUser', User::getCommunity());
89
+		$this->assign('skin', 'auto');
90
+		$this->assign('currentDomain', null);
91
+		$this->assign('loggedIn', false);
92
+		$this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
93
+		$this->assign('resourceCacheEpoch', $this->getSiteConfiguration()->getResourceCacheEpoch());
94
+		$this->assign('serverPathInfo', WebRequest::pathInfo());
95
+
96
+		$this->assign('siteNoticeText', '');
97
+		$this->assign('siteNoticeVersion', 0);
98
+		$this->assign('siteNoticeState', 'd-none');
99
+		$this->assign('toolversion', Environment::getToolVersion());
100
+
101
+		// default these
102
+		$this->assign('onlineusers', array());
103
+		$this->assign('typeAheadBlock', '');
104
+		$this->assign('extraJs', array());
105
+
106
+		// nav menu access control
107
+		$this->assign('nav__canRequests', false);
108
+		$this->assign('nav__canLogs', false);
109
+		$this->assign('nav__canUsers', false);
110
+		$this->assign('nav__canSearch', false);
111
+		$this->assign('nav__canStats', false);
112
+		$this->assign('nav__canBan', false);
113
+		$this->assign('nav__canEmailMgmt', false);
114
+		$this->assign('nav__canWelcomeMgmt', false);
115
+		$this->assign('nav__canSiteNoticeMgmt', false);
116
+		$this->assign('nav__canUserMgmt', false);
117
+		$this->assign('nav__canViewRequest', false);
118
+		$this->assign('nav__canJobQueue', false);
119
+		$this->assign('nav__canFlaggedComments', false);
120
+		$this->assign('nav__canDomainMgmt', false);
121
+		$this->assign('nav__canQueueMgmt', false);
122
+		$this->assign('nav__canFormMgmt', false);
123
+		$this->assign('nav__canErrorLog', false);
124
+
125
+		// Navigation badges for concern areas.
126
+		$this->assign("nav__numAdmin", 0);
127
+		$this->assign("nav__numFlaggedComments", 0);
128
+		$this->assign("nav__numJobQueueFailed", 0);
129
+
130
+		// debug helpers
131
+		$this->assign('showDebugCssBreakpoints', $this->getSiteConfiguration()->getDebuggingCssBreakpointsEnabled());
132
+
133
+		$this->assign('page', $this);
134
+	}
135
+
136
+	/**
137
+	 * Fetches a rendered Smarty template
138
+	 *
139
+	 * @param $template string Template file path, relative to /templates/
140
+	 *
141
+	 * @return string Templated HTML
142
+	 * @throws Exception
143
+	 */
144
+	final protected function fetchTemplate($template)
145
+	{
146
+		return $this->smarty->fetch($template);
147
+	}
148 148
 }
Please login to merge, or discard this patch.