/
PermissionManager.php
1813 lines (1687 loc) 路 59.7 KB
/
PermissionManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
*/
namespace MediaWiki\Permissions;
use Article;
use InvalidArgumentException;
use LogicException;
use MediaWiki\Actions\ActionFactory;
use MediaWiki\Block\BlockErrorFormatter;
use MediaWiki\Block\DatabaseBlock;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\HookContainer\HookRunner;
use MediaWiki\Linker\LinkTarget;
use MediaWiki\MainConfigNames;
use MediaWiki\Page\PageIdentity;
use MediaWiki\Page\RedirectLookup;
use MediaWiki\Session\SessionManager;
use MediaWiki\SpecialPage\SpecialPageFactory;
use MediaWiki\Title\Title;
use MediaWiki\User\TempUser\TempUserConfig;
use MediaWiki\User\UserFactory;
use MediaWiki\User\UserGroupManager;
use MediaWiki\User\UserIdentity;
use Message;
use MessageSpecifier;
use NamespaceInfo;
use PermissionsError;
use RequestContext;
use SpecialPage;
use TitleFormatter;
use User;
use UserCache;
use Wikimedia\ScopedCallback;
/**
* A service class for checking permissions
* To obtain an instance, use MediaWikiServices::getInstance()->getPermissionManager().
*
* @since 1.33
*/
class PermissionManager {
/** @var string Does cheap permission checks from replica DBs (usable for GUI creation) */
public const RIGOR_QUICK = 'quick';
/** @var string Does cheap and expensive checks possibly from a replica DB */
public const RIGOR_FULL = 'full';
/** @var string Does cheap and expensive checks, using the primary DB as needed */
public const RIGOR_SECURE = 'secure';
/**
* @internal For use by ServiceWiring
*/
public const CONSTRUCTOR_OPTIONS = [
MainConfigNames::WhitelistRead,
MainConfigNames::WhitelistReadRegexp,
MainConfigNames::EmailConfirmToEdit,
MainConfigNames::BlockDisablesLogin,
MainConfigNames::EnablePartialActionBlocks,
MainConfigNames::GroupPermissions,
MainConfigNames::RevokePermissions,
MainConfigNames::AvailableRights,
MainConfigNames::NamespaceProtection,
MainConfigNames::RestrictionLevels,
MainConfigNames::DeleteRevisionsLimit,
];
/** @var ServiceOptions */
private $options;
/** @var SpecialPageFactory */
private $specialPageFactory;
/** @var RedirectLookup */
private $redirectLookup;
/** @var NamespaceInfo */
private $nsInfo;
/** @var GroupPermissionsLookup */
private $groupPermissionsLookup;
/** @var UserGroupManager */
private $userGroupManager;
/** @var string[]|null Cached results of getAllPermissions() */
private $allRights;
/** @var BlockErrorFormatter */
private $blockErrorFormatter;
/** @var HookRunner */
private $hookRunner;
/** @var UserCache */
private $userCache;
/** @var RestrictionStore */
private $restrictionStore;
/** @var TitleFormatter */
private $titleFormatter;
/** @var TempUserConfig */
private $tempUserConfig;
/** @var UserFactory */
private $userFactory;
/** @var ActionFactory */
private $actionFactory;
/** @var string[][] Cached user rights */
private $usersRights = [];
/**
* Temporary user rights, valid for the current request only.
* @var string[][][] userid => override group => rights
*/
private $temporaryUserRights = [];
/** @var bool[] Cached rights for isEveryoneAllowed, [ right => allowed ] */
private $cachedRights = [];
/**
* Array of Strings Core rights.
* Each of these should have a corresponding message of the form
* "right-$right".
* @showinitializer
*/
private const CORE_RIGHTS = [
'apihighlimits',
'applychangetags',
'autoconfirmed',
'autocreateaccount',
'autopatrol',
'bigdelete',
'block',
'blockemail',
'bot',
'browsearchive',
'changetags',
'createaccount',
'createpage',
'createtalk',
'delete',
'delete-redirect',
'deletechangetags',
'deletedhistory',
'deletedtext',
'deletelogentry',
'deleterevision',
'edit',
'editcontentmodel',
'editinterface',
'editprotected',
'editmyoptions',
'editmyprivateinfo',
'editmyusercss',
'editmyuserjson',
'editmyuserjs',
'editmyuserjsredirect',
'editmywatchlist',
'editsemiprotected',
'editsitecss',
'editsitejson',
'editsitejs',
'editusercss',
'edituserjson',
'edituserjs',
'hideuser',
'import',
'importupload',
'ipblock-exempt',
'managechangetags',
'markbotedits',
'mergehistory',
'minoredit',
'move',
'movefile',
'move-categorypages',
'move-rootuserpages',
'move-subpages',
'nominornewtalk',
'noratelimit',
'override-export-depth',
'pagelang',
'patrol',
'patrolmarks',
'protect',
'purge',
'read',
'renameuser',
'reupload',
'reupload-own',
'reupload-shared',
'rollback',
'sendemail',
'siteadmin',
'suppressionlog',
'suppressredirect',
'suppressrevision',
'unblockself',
'undelete',
'unwatchedpages',
'upload',
'upload_by_url',
'userrights',
'userrights-interwiki',
'viewmyprivateinfo',
'viewmywatchlist',
'viewsuppressed',
'writeapi',
];
/**
* @param ServiceOptions $options
* @param SpecialPageFactory $specialPageFactory
* @param NamespaceInfo $nsInfo
* @param GroupPermissionsLookup $groupPermissionsLookup
* @param UserGroupManager $userGroupManager
* @param BlockErrorFormatter $blockErrorFormatter
* @param HookContainer $hookContainer
* @param UserCache $userCache
* @param RedirectLookup $redirectLookup
* @param RestrictionStore $restrictionStore
* @param TitleFormatter $titleFormatter
* @param TempUserConfig $tempUserConfig
* @param UserFactory $userFactory
* @param ActionFactory $actionFactory
*/
public function __construct(
ServiceOptions $options,
SpecialPageFactory $specialPageFactory,
NamespaceInfo $nsInfo,
GroupPermissionsLookup $groupPermissionsLookup,
UserGroupManager $userGroupManager,
BlockErrorFormatter $blockErrorFormatter,
HookContainer $hookContainer,
UserCache $userCache,
RedirectLookup $redirectLookup,
RestrictionStore $restrictionStore,
TitleFormatter $titleFormatter,
TempUserConfig $tempUserConfig,
UserFactory $userFactory,
ActionFactory $actionFactory
) {
$options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
$this->options = $options;
$this->specialPageFactory = $specialPageFactory;
$this->nsInfo = $nsInfo;
$this->groupPermissionsLookup = $groupPermissionsLookup;
$this->userGroupManager = $userGroupManager;
$this->blockErrorFormatter = $blockErrorFormatter;
$this->hookRunner = new HookRunner( $hookContainer );
$this->userCache = $userCache;
$this->redirectLookup = $redirectLookup;
$this->restrictionStore = $restrictionStore;
$this->titleFormatter = $titleFormatter;
$this->tempUserConfig = $tempUserConfig;
$this->userFactory = $userFactory;
$this->actionFactory = $actionFactory;
}
/**
* Can $user perform $action on a page?
*
* The method replaced Title::userCan()
* The $user parameter need to be superseded by UserIdentity value in future
* The $title parameter need to be superseded by PageIdentity value in future
*
* @param string $action
* @param User $user
* @param LinkTarget $page
* @param string $rigor One of PermissionManager::RIGOR_ constants
* - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
* - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
* - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
*
* @return bool
*/
public function userCan( $action, User $user, LinkTarget $page, $rigor = self::RIGOR_SECURE ): bool {
return !count( $this->getPermissionErrorsInternal( $action, $user, $page, $rigor, true ) );
}
/**
* A convenience method for calling PermissionManager::userCan
* with PermissionManager::RIGOR_QUICK
*
* Suitable for use for nonessential UI controls in common cases, but
* _not_ for functional access control.
* May provide false positives, but should never provide a false negative.
*
* @see PermissionManager::userCan()
*
* @param string $action
* @param User $user
* @param LinkTarget $page
* @return bool
*/
public function quickUserCan( $action, User $user, LinkTarget $page ): bool {
return $this->userCan( $action, $user, $page, self::RIGOR_QUICK );
}
/**
* Can $user perform $action on a page?
*
* @todo FIXME: This *does not* check throttles (User::pingLimiter()).
*
* @param string $action Action that permission needs to be checked for
* @param User $user User to check
* @param LinkTarget $page
* @param string $rigor One of PermissionManager::RIGOR_ constants
* - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
* - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
* - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
* @param string[] $ignoreErrors Set this to a list of message keys
* whose corresponding errors may be ignored.
*
* @return array[] Array of arrays of the arguments to wfMessage to explain permissions problems.
* @phan-return non-empty-array[]
*/
public function getPermissionErrors(
$action,
User $user,
LinkTarget $page,
$rigor = self::RIGOR_SECURE,
$ignoreErrors = []
): array {
$errors = $this->getPermissionErrorsInternal( $action, $user, $page, $rigor );
// Remove the errors being ignored.
foreach ( $errors as $index => $error ) {
$errKey = is_array( $error ) ? $error[0] : $error;
if ( in_array( $errKey, $ignoreErrors ) ) {
unset( $errors[$index] );
}
if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
unset( $errors[$index] );
}
}
return array_values( $errors );
}
/**
* Like {@link getPermissionErrors}, but immediately throw if there are any errors.
*
* @param string $action Action that permission needs to be checked for
* @param User $user User to check
* @param LinkTarget $page
* @param string $rigor One of PermissionManager::RIGOR_ constants
* - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
* - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
* - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
* @param string[] $ignoreErrors Set this to a list of message keys
* whose corresponding errors may be ignored.
*
* @throws PermissionsError
*/
public function throwPermissionErrors(
$action,
User $user,
LinkTarget $page,
$rigor = self::RIGOR_SECURE,
$ignoreErrors = []
): void {
$permissionErrors = $this->getPermissionErrors(
$action, $user, $page, $rigor, $ignoreErrors );
if ( $permissionErrors !== [] ) {
throw new PermissionsError( $action, $permissionErrors );
}
}
/**
* Check if user is blocked from editing a particular article. If the user does not
* have a block, this will return false.
*
* @param User $user
* @param PageIdentity|LinkTarget $page Title to check
* @param bool $fromReplica Whether to check the replica DB instead of the primary DB
* @return bool
*/
public function isBlockedFrom( User $user, $page, $fromReplica = false ): bool {
$block = $user->getBlock( $fromReplica );
if ( !$block ) {
return false;
}
if ( $page instanceof PageIdentity ) {
$title = Title::newFromPageIdentity( $page );
} else {
$title = Title::newFromLinkTarget( $page );
}
$blocked = $user->isHidden();
if ( !$blocked ) {
// Special handling for a user's own talk page. The block is not aware
// of the user, so this must be done here.
if ( $title->equals( $user->getTalkPage() ) ) {
$blocked = $block->appliesToUsertalk( $title );
} else {
$blocked = $block->appliesToTitle( $title );
}
}
// only for the purpose of the hook. We really don't need this here.
$allowUsertalk = $block->isUsertalkEditAllowed();
// Allow extensions to let a blocked user access a particular page
$this->hookRunner->onUserIsBlockedFrom( $user, $title, $blocked, $allowUsertalk );
return $blocked;
}
/**
* Can $user perform $action on a page? This is an internal function,
* with multiple levels of checks depending on performance needs; see $rigor below.
* It does not check ReadOnlyMode::isReadOnly().
*
* @param string $action Action that permission needs to be checked for
* @param User $user User to check
* @param LinkTarget $page
* @param string $rigor One of PermissionManager::RIGOR_ constants
* - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
* - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
* - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
* @param bool $short Set this to true to stop after the first permission error.
* @return array[] Array of arrays of the arguments to wfMessage to explain permissions problems.
*/
private function getPermissionErrorsInternal(
$action,
User $user,
LinkTarget $page,
$rigor = self::RIGOR_SECURE,
$short = false
): array {
if ( !in_array( $rigor, [ self::RIGOR_QUICK, self::RIGOR_FULL, self::RIGOR_SECURE ] ) ) {
throw new InvalidArgumentException( "Invalid rigor parameter '$rigor'." );
}
// With RIGOR_QUICK we can assume automatic account creation will
// occur. At a higher rigor level, the caller is required to opt
// in by either setting the create intent or actually creating
// the account.
if ( $rigor === self::RIGOR_QUICK
&& !$user->isRegistered()
&& $this->tempUserConfig->isAutoCreateAction( $action )
) {
$user = $this->userFactory->newTempPlaceholder();
}
# Read has special handling
if ( $action === 'read' ) {
$checks = [
[ $this, 'checkPermissionHooks' ],
[ $this, 'checkReadPermissions' ],
[ $this, 'checkUserBlock' ], // for wgBlockDisablesLogin
];
# Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
# or checkUserConfigPermissions here as it will lead to duplicate
# error messages. This is okay to do since anywhere that checks for
# create will also check for edit, and those checks are called for edit.
} elseif ( $action === 'create' ) {
$checks = [
[ $this, 'checkQuickPermissions' ],
[ $this, 'checkPermissionHooks' ],
[ $this, 'checkPageRestrictions' ],
[ $this, 'checkCascadingSourcesRestrictions' ],
[ $this, 'checkActionPermissions' ],
[ $this, 'checkUserBlock' ],
];
} else {
// Exclude checkUserConfigPermissions on actions that cannot change the
// content of the configuration pages.
$skipUserConfigActions = [
// Allow patrolling per T21818
'patrol',
// Allow admins and oversighters to delete. For user pages we want to avoid the
// situation where an unprivileged user can post abusive content on
// their subpages and only very highly privileged users could remove it.
// See T200176.
'delete',
'deleterevision',
'suppressrevision',
// Allow admins and oversighters to view deleted content, even if they
// cannot restore it. See T202989
'deletedhistory',
'deletedtext',
'viewsuppressed',
];
$checks = [
[ $this, 'checkQuickPermissions' ],
[ $this, 'checkPermissionHooks' ],
[ $this, 'checkSpecialsAndNSPermissions' ],
[ $this, 'checkSiteConfigPermissions' ],
];
if ( !in_array( $action, $skipUserConfigActions, true ) ) {
$checks[] = [ $this, 'checkUserConfigPermissions' ];
}
$checks = [
...$checks,
[ $this, 'checkPageRestrictions' ],
[ $this, 'checkCascadingSourcesRestrictions' ],
[ $this, 'checkActionPermissions' ],
[ $this, 'checkUserBlock' ]
];
}
$errors = [];
foreach ( $checks as $method ) {
$errors = $method( $action, $user, $errors, $rigor, $short, $page );
if ( $short && $errors !== [] ) {
break;
}
}
// remove duplicate errors
$errors = array_unique( $errors, SORT_REGULAR );
if ( $errors ) {
$this->hookRunner->onPermissionErrorAudit( $page, $user, $action, $rigor, $errors );
}
return $errors;
}
/**
* Check various permission hooks
*
* @param string $action The action to check
* @param User $user User to check
* @param array $errors List of current errors
* @param string $rigor One of PermissionManager::RIGOR_ constants
* - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
* - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
* - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
* @param bool $short Short circuit on first error
* @param LinkTarget $page
* @return array List of errors
*/
private function checkPermissionHooks(
$action,
User $user,
$errors,
$rigor,
$short,
LinkTarget $page
): array {
// TODO: remove when LinkTarget usage will expand further
$title = Title::newFromLinkTarget( $page );
// Use getUserPermissionsErrors instead
$result = '';
if ( !$this->hookRunner->onUserCan( $title, $user, $action, $result ) ) {
return $result ? [] : [ [ 'badaccess-group0' ] ];
}
// Check getUserPermissionsErrors hook
if ( !$this->hookRunner->onGetUserPermissionsErrors( $title, $user, $action, $result ) ) {
$errors = $this->resultToError( $errors, $result );
}
// Check getUserPermissionsErrorsExpensive hook
if (
$rigor !== self::RIGOR_QUICK
&& !( $short && count( $errors ) > 0 )
&& !$this->hookRunner->onGetUserPermissionsErrorsExpensive(
$title, $user, $action, $result )
) {
$errors = $this->resultToError( $errors, $result );
}
return $errors;
}
/**
* Add the resulting error code to the errors array
*
* @param array $errors List of current errors
* @param array|string|MessageSpecifier|false $result Result of errors
* @return array List of errors
*/
private function resultToError( $errors, $result ): array {
if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
// A single array representing an error
$errors[] = $result;
} elseif ( is_array( $result ) && is_array( $result[0] ) ) {
// A nested array representing multiple errors
$errors = array_merge( $errors, $result );
} elseif ( $result !== '' && is_string( $result ) ) {
// A string representing a message-id
$errors[] = [ $result ];
} elseif ( $result instanceof MessageSpecifier ) {
// A message specifier representing an error
$errors[] = [ $result ];
} elseif ( $result === false ) {
// a generic "We don't want them to do that"
$errors[] = [ 'badaccess-group0' ];
}
return $errors;
}
/**
* Check that the user is allowed to read this page.
*
* @param string $action The action to check
* @param User $user User to check
* @param array $errors List of current errors
* @param string $rigor One of PermissionManager::RIGOR_ constants
* - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
* - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
* - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
* @param bool $short Short circuit on first error
* @param LinkTarget $page
* @return array List of errors
*/
private function checkReadPermissions(
$action,
User $user,
$errors,
$rigor,
$short,
LinkTarget $page
): array {
// TODO: remove when LinkTarget usage will expand further
$title = Title::newFromLinkTarget( $page );
$whiteListRead = $this->options->get( MainConfigNames::WhitelistRead );
$allowed = false;
if ( $this->isEveryoneAllowed( 'read' ) ) {
// Shortcut for public wikis, allows skipping quite a bit of code
$allowed = true;
} elseif ( $this->userHasRight( $user, 'read' ) ) {
// If the user is allowed to read pages, he is allowed to read all pages
$allowed = true;
} elseif ( $this->isSameSpecialPage( 'Userlogin', $page )
|| $this->isSameSpecialPage( 'PasswordReset', $page )
|| $this->isSameSpecialPage( 'Userlogout', $page )
) {
// Always grant access to the login page.
// Even anons need to be able to log in.
$allowed = true;
} elseif ( $this->isSameSpecialPage( 'RunJobs', $page ) ) {
// relies on HMAC key signature alone
$allowed = true;
} elseif ( is_array( $whiteListRead ) && count( $whiteListRead ) ) {
// Time to check the whitelist
// Only do these checks is there's something to check against
$name = $title->getPrefixedText();
$dbName = $title->getPrefixedDBkey();
// Check for explicit whitelisting with and without underscores
if ( in_array( $name, $whiteListRead, true )
|| in_array( $dbName, $whiteListRead, true )
) {
$allowed = true;
} elseif ( $page->getNamespace() === NS_MAIN ) {
// Old settings might have the title prefixed with
// a colon for main-namespace pages
if ( in_array( ':' . $name, $whiteListRead ) ) {
$allowed = true;
}
} elseif ( $title->isSpecialPage() ) {
// If it's a special page, ditch the subpage bit and check again
$name = $title->getDBkey();
[ $name, /* $subpage */ ] =
$this->specialPageFactory->resolveAlias( $name );
if ( $name ) {
$pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
if ( in_array( $pure, $whiteListRead, true ) ) {
$allowed = true;
}
}
}
}
$whitelistReadRegexp = $this->options->get( MainConfigNames::WhitelistReadRegexp );
if ( !$allowed && is_array( $whitelistReadRegexp )
&& !empty( $whitelistReadRegexp )
) {
$name = $title->getPrefixedText();
// Check for regex whitelisting
foreach ( $whitelistReadRegexp as $listItem ) {
if ( preg_match( $listItem, $name ) ) {
$allowed = true;
break;
}
}
}
if ( !$allowed ) {
# If the title is not whitelisted, give extensions a chance to do so...
$this->hookRunner->onTitleReadWhitelist( $title, $user, $allowed );
if ( !$allowed ) {
$errors[] = $this->missingPermissionError( $action, $short );
}
}
return $errors;
}
/**
* Get a description array for when an action isn't allowed to be performed.
*
* @param string $action The action to check
* @param bool $short Short circuit on first error
* @return array Array containing an error message key and any parameters
*/
private function missingPermissionError( string $action, bool $short ): array {
// We avoid expensive display logic for quickUserCan's and such
if ( $short ) {
return [ 'badaccess-group0' ];
}
// TODO: it would be a good idea to replace the method below with something else like
// maybe callback injection
return User::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
}
/**
* Whether a title resolves to the named special page.
*
* @param string $name The special page name
* @param LinkTarget $page
* @return bool
*/
private function isSameSpecialPage( $name, LinkTarget $page ): bool {
if ( $page->getNamespace() === NS_SPECIAL ) {
[ $pageName ] = $this->specialPageFactory->resolveAlias( $page->getDBkey() );
if ( $name === $pageName ) {
return true;
}
}
return false;
}
/**
* Check that the user isn't blocked from editing.
*
* @param string $action The action to check
* @param User $user User to check
* @param array $errors List of current errors
* @param string $rigor One of PermissionManager::RIGOR_ constants
* - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
* - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
* - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
* @param bool $short Short circuit on first error
* @param LinkTarget $page
* @return array List of errors
*/
private function checkUserBlock(
$action,
User $user,
$errors,
$rigor,
$short,
LinkTarget $page
): array {
// Unblocking handled in SpecialUnblock
if ( $rigor === self::RIGOR_QUICK || in_array( $action, [ 'unblock' ] ) ) {
return $errors;
}
// Optimize for a very common case
if ( $action === 'read' && !$this->options->get( MainConfigNames::BlockDisablesLogin ) ) {
return $errors;
}
if ( $this->options->get( MainConfigNames::EmailConfirmToEdit )
&& !$user->isEmailConfirmed()
&& $action === 'edit'
) {
$errors[] = [ 'confirmedittext' ];
}
if ( $rigor === self::RIGOR_SECURE ) {
$blockInfoFreshness = Authority::READ_LATEST;
$useReplica = false;
} else {
// RIGOR_FULL, RIGOR_QUICK
$blockInfoFreshness = Authority::READ_NORMAL;
$useReplica = true;
}
$block = $user->getBlock( $blockInfoFreshness );
if ( $action === 'createaccount' ) {
$applicableBlock = null;
if ( $block && $block->appliesToRight( 'createaccount' ) ) {
$applicableBlock = $block;
}
// T15611: if the IP address the user is trying to create an account from is
// blocked with createaccount disabled, prevent new account creation there even
// when the user is logged in
if ( !$this->userHasRight( $user, 'ipblock-exempt' ) ) {
$ipBlock = DatabaseBlock::newFromTarget(
null, $user->getRequest()->getIP()
);
if ( $ipBlock && $ipBlock->appliesToRight( 'createaccount' ) ) {
$applicableBlock = $ipBlock;
}
}
// @todo FIXME: Pass the relevant context into this function.
if ( $applicableBlock ) {
$context = RequestContext::getMain();
$message = $this->blockErrorFormatter->getMessage(
$applicableBlock,
$context->getUser(),
$context->getLanguage(),
$context->getRequest()->getIP()
);
$errors[] = array_merge( [ $message->getKey() ], $message->getParams() );
return $errors;
}
}
// If the user does not have a block, or the block they do have explicitly
// allows the action (like "read" or "upload").
if ( !$block || $block->appliesToRight( $action ) === false ) {
return $errors;
}
// Determine if the user is blocked from this action on this page.
// What gets passed into this method is a user right, not an action name.
// There is no way to instantiate an action by restriction. However, this
// will get the action where the restriction is the same. This may result
// in actions being blocked that shouldn't be.
$actionObj = null;
$title = Title::newFromLinkTarget( $page, 'clone' );
if ( $title->canExist() ) {
// TODO: this drags a ton of dependencies in, would be good to avoid Article
// instantiation and decouple it creating an ActionPermissionChecker interface
// Creating an action will perform several database queries to ensure that
// the action has not been overridden by the content type.
// FIXME: avoid use of RequestContext since it drags in User and Title dependencies
// probably we may use fake context object since it's unlikely that Action uses it
// anyway. It would be nice if we could avoid instantiating the Action at all.
$context = RequestContext::getMain();
$actionObj = $this->actionFactory->getAction(
$action,
Article::newFromTitle( $title, $context ),
$context
);
// Ensure that the retrieved action matches the restriction.
if ( $actionObj && $actionObj->getRestriction() !== $action ) {
$actionObj = null;
}
}
// If no action object is returned, assume that the action requires unblock
// which is the default.
if ( !$actionObj || $actionObj->requiresUnblock() ) {
if (
$this->isBlockedFrom( $user, $page, $useReplica ) ||
(
$this->options->get( MainConfigNames::EnablePartialActionBlocks ) &&
$block->appliesToRight( $action )
)
) {
// @todo FIXME: Pass the relevant context into this function.
$context = RequestContext::getMain();
$message = $this->blockErrorFormatter->getMessage(
$block,
$context->getUser(),
$context->getLanguage(),
$context->getRequest()->getIP()
);
$errors[] = array_merge( [ $message->getKey() ], $message->getParams() );
}
}
return $errors;
}
/**
* Run easy-to-test (or "quick") permissions checks for a given action.
*
* @param string $action The action to check
* @param User $user User to check
* @param array $errors List of current errors
* @param string $rigor One of PermissionManager::RIGOR_ constants
* - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
* - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
* - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
* @param bool $short Short circuit on first error
* @param LinkTarget $page
* @return array List of errors
*/
private function checkQuickPermissions(
$action,
User $user,
$errors,
$rigor,
$short,
LinkTarget $page
): array {
// TODO: remove when LinkTarget usage will expand further
$title = Title::newFromLinkTarget( $page );
if ( !$this->hookRunner->onTitleQuickPermissions( $title, $user, $action,
$errors, $rigor !== self::RIGOR_QUICK, $short )
) {
return $errors;
}
$isSubPage =
$this->nsInfo->hasSubpages( $title->getNamespace() ) &&
strpos( $title->getText(), '/' ) !== false;
if ( $action === 'create' ) {
if (
( $this->nsInfo->isTalk( $title->getNamespace() ) &&
!$this->userHasRight( $user, 'createtalk' ) ) ||
( !$this->nsInfo->isTalk( $title->getNamespace() ) &&
!$this->userHasRight( $user, 'createpage' ) )
) {
$errors[] = $user->isNamed() ? [ 'nocreate-loggedin' ] : [ 'nocreatetext' ];
}
} elseif ( $action === 'move' ) {
if ( !$this->userHasRight( $user, 'move-rootuserpages' )
&& $title->getNamespace() === NS_USER && !$isSubPage
) {
// Show user page-specific message only if the user can move other pages
$errors[] = [ 'cant-move-user-page' ];
}
// Check if user is allowed to move files if it's a file
if ( $title->getNamespace() === NS_FILE &&
!$this->userHasRight( $user, 'movefile' )
) {
$errors[] = [ 'movenotallowedfile' ];
}
// Check if user is allowed to move category pages if it's a category page
if ( $title->getNamespace() === NS_CATEGORY &&
!$this->userHasRight( $user, 'move-categorypages' )
) {
$errors[] = [ 'cant-move-category-page' ];
}
if ( !$this->userHasRight( $user, 'move' ) ) {
// User can't move anything
$userCanMove = $this->groupPermissionsLookup
->groupHasPermission( 'user', 'move' );
$namedCanMove = $this->groupPermissionsLookup
->groupHasPermission( 'named', 'move' );
$autoconfirmedCanMove = $this->groupPermissionsLookup
->groupHasPermission( 'autoconfirmed', 'move' );
if ( $user->isAnon()
&& ( $userCanMove || $namedCanMove || $autoconfirmedCanMove )
) {
// custom message if logged-in users without any special rights can move
$errors[] = [ 'movenologintext' ];
} elseif ( $user->isTemp() && ( $namedCanMove || $autoconfirmedCanMove ) ) {
// Temp user may be able to move if they log in as a proper account
$errors[] = [ 'movenologintext' ];
} else {
$errors[] = [ 'movenotallowed' ];
}
}
} elseif ( $action === 'move-target' ) {
if ( !$this->userHasRight( $user, 'move' ) ) {
// User can't move anything
$errors[] = [ 'movenotallowed' ];
} elseif ( !$this->userHasRight( $user, 'move-rootuserpages' )
&& $title->getNamespace() === NS_USER
&& !$isSubPage
) {
// Show user page-specific message only if the user can move other pages
$errors[] = [ 'cant-move-to-user-page' ];
} elseif ( !$this->userHasRight( $user, 'move-categorypages' )
&& $title->getNamespace() === NS_CATEGORY
) {
// Show category page-specific message only if the user can move other pages
$errors[] = [ 'cant-move-to-category-page' ];
}
} elseif ( !$this->userHasRight( $user, $action ) ) {
$errors[] = $this->missingPermissionError( $action, $short );
}