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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
|
<?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 Action;
use Article;
use Exception;
use MediaWiki\Block\BlockErrorFormatter;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\HookContainer\HookRunner;
use MediaWiki\Linker\LinkTarget;
use MediaWiki\Revision\RevisionLookup;
use MediaWiki\Revision\RevisionRecord;
use MediaWiki\Session\SessionManager;
use MediaWiki\SpecialPage\SpecialPageFactory;
use MediaWiki\User\UserIdentity;
use MessageSpecifier;
use NamespaceInfo;
use RequestContext;
use SpecialPage;
use Title;
use User;
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 master as needed */
public const RIGOR_SECURE = 'secure';
/**
* @since 1.34
* @var array
*/
public const CONSTRUCTOR_OPTIONS = [
'WhitelistRead',
'WhitelistReadRegexp',
'EmailConfirmToEdit',
'BlockDisablesLogin',
'GroupPermissions',
'RevokePermissions',
'AvailableRights',
'NamespaceProtection',
'RestrictionLevels'
];
/** @var ServiceOptions */
private $options;
/** @var SpecialPageFactory */
private $specialPageFactory;
/** @var RevisionLookup */
private $revisionLookup;
/** @var NamespaceInfo */
private $nsInfo;
/** @var string[]|null Cached results of getAllRights() */
private $allRights;
/** @var BlockErrorFormatter */
private $blockErrorFormatter;
/** @var HookRunner */
private $hookRunner;
/** @var string[][] Cached user rights */
private $usersRights = null;
/**
* 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 $coreRights = [
'apihighlimits',
'applychangetags',
'autoconfirmed',
'autocreateaccount',
'autopatrol',
'bigdelete',
'block',
'blockemail',
'bot',
'browsearchive',
'changetags',
'createaccount',
'createpage',
'createtalk',
'delete',
'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',
'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 RevisionLookup $revisionLookup
* @param NamespaceInfo $nsInfo
* @param BlockErrorFormatter $blockErrorFormatter
* @param HookContainer $hookContainer
*/
public function __construct(
ServiceOptions $options,
SpecialPageFactory $specialPageFactory,
RevisionLookup $revisionLookup,
NamespaceInfo $nsInfo,
BlockErrorFormatter $blockErrorFormatter,
HookContainer $hookContainer
) {
$options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
$this->options = $options;
$this->specialPageFactory = $specialPageFactory;
$this->revisionLookup = $revisionLookup;
$this->nsInfo = $nsInfo;
$this->blockErrorFormatter = $blockErrorFormatter;
$this->hookRunner = new HookRunner( $hookContainer );
}
/**
* Can $user perform $action on a page?
*
* The method is intended to replace 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
*
* @see Title::userCan()
*
* @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 master as needed
*
* @return bool
*/
public function userCan( $action, User $user, LinkTarget $page, $rigor = self::RIGOR_SECURE ) {
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 ) {
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 master as needed
* @param array $ignoreErrors Array of Strings 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.
*/
public function getPermissionErrors(
$action,
User $user,
LinkTarget $page,
$rigor = self::RIGOR_SECURE,
$ignoreErrors = []
) {
$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 $errors;
}
/**
* 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 LinkTarget $page Title to check
* @param bool $fromReplica Whether to check the replica DB instead of the master
*
* @return bool
*/
public function isBlockedFrom( User $user, LinkTarget $page, $fromReplica = false ) {
$block = $user->getBlock( $fromReplica );
if ( !$block ) {
return false;
}
// TODO: remove upon further migration to LinkTarget
$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 = $user->isAllowUsertalk();
// 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 wfReadOnly().
*
* @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 master 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.
* @throws Exception
*/
private function getPermissionErrorsInternal(
$action,
User $user,
LinkTarget $page,
$rigor = self::RIGOR_SECURE,
$short = false
) {
if ( !in_array( $rigor, [ self::RIGOR_QUICK, self::RIGOR_FULL, self::RIGOR_SECURE ] ) ) {
throw new Exception( "Invalid rigor parameter '$rigor'." );
}
# Read has special handling
if ( $action == 'read' ) {
$checks = [
'checkPermissionHooks',
'checkReadPermissions',
'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 = [
'checkQuickPermissions',
'checkPermissionHooks',
'checkPageRestrictions',
'checkCascadingSourcesRestrictions',
'checkActionPermissions',
'checkUserBlock'
];
} else {
$checks = [
'checkQuickPermissions',
'checkPermissionHooks',
'checkSpecialsAndNSPermissions',
'checkSiteConfigPermissions',
'checkUserConfigPermissions',
'checkPageRestrictions',
'checkCascadingSourcesRestrictions',
'checkActionPermissions',
'checkUserBlock'
];
}
$errors = [];
foreach ( $checks as $method ) {
$errors = $this->$method( $action, $user, $errors, $rigor, $short, $page );
if ( $short && $errors !== [] ) {
break;
}
}
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 master 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
) {
// 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 ) {
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 master 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
) {
// TODO: remove when LinkTarget usage will expand further
$title = Title::newFromLinkTarget( $page );
$whiteListRead = $this->options->get( 'WhitelistRead' );
$whitelisted = false;
if ( $this->isEveryoneAllowed( 'read' ) ) {
# Shortcut for public wikis, allows skipping quite a bit of code
$whitelisted = true;
} elseif ( $this->userHasRight( $user, 'read' ) ) {
# If the user is allowed to read pages, he is allowed to read all pages
$whitelisted = true;
} elseif ( $this->isSameSpecialPage( 'Userlogin', $title )
|| $this->isSameSpecialPage( 'PasswordReset', $title )
|| $this->isSameSpecialPage( 'Userlogout', $title )
) {
# Always grant access to the login page.
# Even anons need to be able to log in.
$whitelisted = 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 ) ) {
$whitelisted = true;
} elseif ( $title->getNamespace() == NS_MAIN ) {
# Old settings might have the title prefixed with
# a colon for main-namespace pages
if ( in_array( ':' . $name, $whiteListRead ) ) {
$whitelisted = true;
}
} elseif ( $title->isSpecialPage() ) {
# If it's a special page, ditch the subpage bit and check again
$name = $title->getDBkey();
list( $name, /* $subpage */ ) =
$this->specialPageFactory->resolveAlias( $name );
if ( $name ) {
$pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
if ( in_array( $pure, $whiteListRead, true ) ) {
$whitelisted = true;
}
}
}
}
$whitelistReadRegexp = $this->options->get( 'WhitelistReadRegexp' );
if ( !$whitelisted && is_array( $whitelistReadRegexp )
&& !empty( $whitelistReadRegexp ) ) {
$name = $title->getPrefixedText();
// Check for regex whitelisting
foreach ( $whitelistReadRegexp as $listItem ) {
if ( preg_match( $listItem, $name ) ) {
$whitelisted = true;
break;
}
}
}
if ( !$whitelisted ) {
# If the title is not whitelisted, give extensions a chance to do so...
$this->hookRunner->onTitleReadWhitelist( $title, $user, $whitelisted );
if ( !$whitelisted ) {
$errors[] = $this->missingPermissionError( $action, $short );
}
}
return $errors;
}
/**
* Get a description array when the user doesn't have the right to perform
* $action (i.e. when User::isAllowed() returns false)
*
* @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( $action, $short ) {
// 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];
}
/**
* Returns true if this 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 ) {
if ( $page->getNamespace() == NS_SPECIAL ) {
list( $thisName, /* $subpage */ ) =
$this->specialPageFactory->resolveAlias( $page->getDBkey() );
if ( $name == $thisName ) {
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 master 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
) {
// Account creation blocks handled at userlogin.
// Unblocking handled in SpecialUnblock
if ( $rigor === self::RIGOR_QUICK || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
return $errors;
}
// Optimize for a very common case
if ( $action === 'read' && !$this->options->get( 'BlockDisablesLogin' ) ) {
return $errors;
}
if ( $this->options->get( 'EmailConfirmToEdit' )
&& !$user->isEmailConfirmed()
&& $action === 'edit'
) {
$errors[] = [ 'confirmedittext' ];
}
$useReplica = ( $rigor !== self::RIGOR_SECURE );
$block = $user->getBlock( $useReplica );
// 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;
if ( Action::exists( $action ) ) {
// 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.
$title = Title::newFromLinkTarget( $page, 'clone' );
$context = RequestContext::getMain();
$actionObj = Action::factory(
$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 ) ) {
// @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;
}
/**
* Permissions checks that fail most often, and which are easiest to test.
*
* @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 master 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
) {
// 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 : 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->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
}
} 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->groupHasPermission( 'user', 'move' );
$autoconfirmedCanMove = $this->groupHasPermission( 'autoconfirmed', 'move' );
if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
// custom message if logged-in users without any special rights can move
$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 );
}
return $errors;
}
/**
* Check against page_restrictions table requirements on this
* page. The user must possess all required rights for this
* 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 master as needed
* @param bool $short Short circuit on first error
*
* @param LinkTarget $page
*
* @return array List of errors
*/
private function checkPageRestrictions(
$action,
User $user,
$errors,
$rigor,
$short,
LinkTarget $page
) {
// TODO: remove & rework upon further use of LinkTarget
$title = Title::newFromLinkTarget( $page );
foreach ( $title->getRestrictions( $action ) as $right ) {
// Backwards compatibility, rewrite sysop -> editprotected
if ( $right == 'sysop' ) {
$right = 'editprotected';
}
// Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
if ( $right == 'autoconfirmed' ) {
$right = 'editsemiprotected';
}
if ( $right == '' ) {
continue;
}
if ( !$this->userHasRight( $user, $right ) ) {
$errors[] = [ 'protectedpagetext', $right, $action ];
} elseif ( $title->areRestrictionsCascading() &&
!$this->userHasRight( $user, 'protect' )
) {
$errors[] = [ 'protectedpagetext', 'protect', $action ];
}
}
return $errors;
}
/**
* Check restrictions on cascading pages.
*
* @param string $action The action to check
* @param UserIdentity $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 master as needed
* @param bool $short Short circuit on first error
*
* @param LinkTarget $page
*
* @return array List of errors
*/
private function checkCascadingSourcesRestrictions(
$action,
UserIdentity $user,
$errors,
$rigor,
$short,
LinkTarget $page
) {
// TODO: remove & rework upon further use of LinkTarget
$title = Title::newFromLinkTarget( $page );
if ( $rigor !== self::RIGOR_QUICK && !$title->isUserConfigPage() ) {
list( $cascadingSources, $restrictions ) = $title->getCascadeProtectionSources();
# Cascading protection depends on more than this page...
# Several cascading protected pages may include this page...
# Check each cascading level
# This is only for protection restrictions, not for all actions
if ( isset( $restrictions[$action] ) ) {
foreach ( $restrictions[$action] as $right ) {
// Backwards compatibility, rewrite sysop -> editprotected
if ( $right == 'sysop' ) {
$right = 'editprotected';
}
// Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
if ( $right == 'autoconfirmed' ) {
$right = 'editsemiprotected';
}
if ( $right != '' && !$this->userHasAllRights( $user, 'protect', $right ) ) {
$wikiPages = '';
/** @var Title $wikiPage */
foreach ( $cascadingSources as $wikiPage ) {
$wikiPages .= '* [[:' . $wikiPage->getPrefixedText() . "]]\n";
}
$errors[] = [ 'cascadeprotected', count( $cascadingSources ), $wikiPages, $action ];
}
}
}
}
return $errors;
}
/**
* Check action permissions not already checked in checkQuickPermissions
*
* @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 master as needed
* @param bool $short Short circuit on first error
*
* @param LinkTarget $page
*
* @return array List of errors
*/
private function checkActionPermissions(
$action,
User $user,
$errors,
$rigor,
$short,
LinkTarget $page
) {
global $wgDeleteRevisionsLimit, $wgLang;
// TODO: remove & rework upon further use of LinkTarget
$title = Title::newFromLinkTarget( $page );
if ( $action == 'protect' ) {
if ( count( $this->getPermissionErrorsInternal( 'edit', $user, $title, $rigor, true ) ) ) {
// If they can't edit, they shouldn't protect.
$errors[] = [ 'protect-cantedit' ];
}
} elseif ( $action == 'create' ) {
$title_protection = $title->getTitleProtection();
if ( $title_protection ) {
if ( $title_protection['permission'] == ''
|| !$this->userHasRight( $user, $title_protection['permission'] )
) {
$errors[] = [
'titleprotected',
// TODO: get rid of the User dependency
User::whoIs( $title_protection['user'] ),
$title_protection['reason']
];
}
}
} elseif ( $action == 'move' ) {
// Check for immobile pages
if ( !$this->nsInfo->isMovable( $title->getNamespace() ) ) {
// Specific message for this case
$nsText = $title->getNsText();
if ( $nsText === '' ) {
$nsText = wfMessage( 'blanknamespace' )->text();
}
$errors[] = [ 'immobile-source-namespace', $nsText ];
} elseif ( !$title->isMovable() ) {
// Less specific message for rarer cases
$errors[] = [ 'immobile-source-page' ];
}
} elseif ( $action == 'move-target' ) {
if ( !$this->nsInfo->isMovable( $title->getNamespace() ) ) {
$nsText = $title->getNsText();
if ( $nsText === '' ) {
$nsText = wfMessage( 'blanknamespace' )->text();
}
$errors[] = [ 'immobile-target-namespace', $nsText ];
} elseif ( !$title->isMovable() ) {
$errors[] = [ 'immobile-target-page' ];
}
} elseif ( $action == 'delete' ) {
$tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true, $title );
if ( !$tempErrors ) {
$tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
$user, $tempErrors, $rigor, true, $title );
}
if ( $tempErrors ) {
// If protection keeps them from editing, they shouldn't be able to delete.
$errors[] = [ 'deleteprotected' ];
}
if ( $rigor !== self::RIGOR_QUICK && $wgDeleteRevisionsLimit
&& !$this->userCan( 'bigdelete', $user, $title ) && $title->isBigDeletion()
) {
$errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
}
} elseif ( $action === 'undelete' ) {
if ( count( $this->getPermissionErrorsInternal( 'edit', $user, $title, $rigor, true ) ) ) {
// Undeleting implies editing
$errors[] = [ 'undelete-cantedit' ];
}
if ( !$title->exists()
&& count( $this->getPermissionErrorsInternal( 'create', $user, $title, $rigor, true ) )
) {
// Undeleting where nothing currently exists implies creating
$errors[] = [ 'undelete-cantcreate' ];
}
}
return $errors;
}
/**
* Check permissions on special pages & namespaces
*
* @param string $action The action to check
* @param UserIdentity $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 master as needed
* @param bool $short Short circuit on first error
*
* @param LinkTarget $page
*
* @return array List of errors
*/
private function checkSpecialsAndNSPermissions(
$action,
UserIdentity $user,
$errors,
$rigor,
$short,
LinkTarget $page
) {
// TODO: remove & rework upon further use of LinkTarget
$title = Title::newFromLinkTarget( $page );
# Only 'createaccount' can be performed on special pages,
# which don't actually exist in the DB.
if ( $title->getNamespace() == NS_SPECIAL && $action !== 'createaccount' ) {
$errors[] = [ 'ns-specialprotected' ];
}
# Check $wgNamespaceProtection for restricted namespaces
if ( $this->isNamespaceProtected( $title->getNamespace(), $user ) ) {
$ns = $title->getNamespace() == NS_MAIN ?
wfMessage( 'nstab-main' )->text() : $title->getNsText();
$errors[] = $title->getNamespace() == NS_MEDIAWIKI ?
[ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
}
return $errors;
}
/**
* Check sitewide CSS/JSON/JS permissions
*
* @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 master as needed
* @param bool $short Short circuit on first error
*
* @param LinkTarget $page
*
* @return array List of errors
*/
private function checkSiteConfigPermissions(
$action,
User $user,
$errors,
$rigor,
$short,
LinkTarget $page
) {
// TODO: remove & rework upon further use of LinkTarget
$title = Title::newFromLinkTarget( $page );
if ( $action != 'patrol' ) {
$error = null;
// Sitewide CSS/JSON/JS/RawHTML changes, like all NS_MEDIAWIKI changes, also require the
// editinterface right. That's implemented as a restriction so no check needed here.
if ( $title->isSiteCssConfigPage() && !$this->userHasRight( $user, 'editsitecss' ) ) {
$error = [ 'sitecssprotected', $action ];
} elseif ( $title->isSiteJsonConfigPage() && !$this->userHasRight( $user, 'editsitejson' ) ) {
$error = [ 'sitejsonprotected', $action ];
} elseif ( $title->isSiteJsConfigPage() && !$this->userHasRight( $user, 'editsitejs' ) ) {
$error = [ 'sitejsprotected', $action ];
}
if ( $title->isRawHtmlMessage() && !$this->userCanEditRawHtmlPage( $user ) ) {
$error = [ 'siterawhtmlprotected', $action ];
}
if ( $error ) {
if ( $this->userHasRight( $user, 'editinterface' ) ) {
// Most users / site admins will probably find out about the new, more restrictive
// permissions by failing to edit something. Give them more info.
// TODO remove this a few release cycles after 1.32
$error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
}
$errors[] = $error;
}
}
return $errors;
}
/**
* Check CSS/JSON/JS sub-page permissions
*
* @param string $action The action to check
* @param UserIdentity $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 master as needed
* @param bool $short Short circuit on first error
*
* @param LinkTarget $page
*
* @return array List of errors
*/
private function checkUserConfigPermissions(
$action,
UserIdentity $user,
$errors,
$rigor,
$short,
LinkTarget $page
) {
// TODO: remove & rework upon further use of LinkTarget
$title = Title::newFromLinkTarget( $page );
# Protect css/json/js subpages of user pages
# XXX: this might be better using restrictions
if ( $action === 'patrol' ) {
return $errors;
}
if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $title->getText() ) ) {
// Users need editmyuser* to edit their own CSS/JSON/JS subpages.
if (
$title->isUserCssConfigPage()
&& !$this->userHasAnyRight( $user, 'editmyusercss', 'editusercss' )
) {
$errors[] = [ 'mycustomcssprotected', $action ];
} elseif (
$title->isUserJsonConfigPage()
&& !$this->userHasAnyRight( $user, 'editmyuserjson', 'edituserjson' )
) {
$errors[] = [ 'mycustomjsonprotected', $action ];
} elseif (
$title->isUserJsConfigPage()
&& !$this->userHasAnyRight( $user, 'editmyuserjs', 'edituserjs' )
) {
$errors[] = [ 'mycustomjsprotected', $action ];
} elseif (
$title->isUserJsConfigPage()
&& !$this->userHasAnyRight( $user, 'edituserjs', 'editmyuserjsredirect' )
) {
// T207750 - do not allow users to edit a redirect if they couldn't edit the target
$rev = $this->revisionLookup->getRevisionByTitle( $title );
$content = $rev ? $rev->getContent( 'main', RevisionRecord::RAW ) : null;
$target = $content ? $content->getUltimateRedirectTarget() : null;
if ( $target && (
!$target->inNamespace( NS_USER )
|| !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $target->getText() )
) ) {
$errors[] = [ 'mycustomjsredirectprotected', $action ];
}
}
} else {
// Users need edituser* to edit others' CSS/JSON/JS subpages, except for
// deletion/suppression which cannot be used for attacks and 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.
if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
if (
$title->isUserCssConfigPage()
&& !$this->userHasRight( $user, 'editusercss' )
) {
$errors[] = [ 'customcssprotected', $action ];
} elseif (
$title->isUserJsonConfigPage()
&& !$this->userHasRight( $user, 'edituserjson' )
) {
$errors[] = [ 'customjsonprotected', $action ];
} elseif (
$title->isUserJsConfigPage()
&& !$this->userHasRight( $user, 'edituserjs' )
) {
$errors[] = [ 'customjsprotected', $action ];
}
}
}
return $errors;
}
/**
* Testing a permission
*
* @since 1.34
*
* @param UserIdentity $user
* @param string $action
*
* @return bool
*/
public function userHasRight( UserIdentity $user, $action = '' ) {
if ( $action === '' ) {
return true; // In the spirit of DWIM
}
// Use strict parameter to avoid matching numeric 0 accidentally inserted
// by misconfiguration: 0 == 'foo'
return in_array( $action, $this->getUserPermissions( $user ), true );
}
/**
* Check if user is allowed to make any action
*
* @param UserIdentity $user
* @param string ...$actions
* @return bool True if user is allowed to perform *any* of the given actions
* @since 1.34
*/
public function userHasAnyRight( UserIdentity $user, ...$actions ) {
foreach ( $actions as $action ) {
if ( $this->userHasRight( $user, $action ) ) {
return true;
}
}
return false;
}
/**
* Check if user is allowed to make all actions
*
* @param UserIdentity $user
* @param string ...$actions
* @return bool True if user is allowed to perform *all* of the given actions
* @since 1.34
*/
public function userHasAllRights( UserIdentity $user, ...$actions ) {
foreach ( $actions as $action ) {
if ( !$this->userHasRight( $user, $action ) ) {
return false;
}
}
return true;
}
/**
* Get the permissions this user has.
*
* @since 1.34
*
* @param UserIdentity $user
*
* @return string[] permission names
*/
public function getUserPermissions( UserIdentity $user ) {
$user = User::newFromIdentity( $user );
$rightsCacheKey = $this->getRightsCacheKey( $user );
if ( !isset( $this->usersRights[ $rightsCacheKey ] ) ) {
$this->usersRights[ $rightsCacheKey ] = $this->getGroupPermissions(
$user->getEffectiveGroups()
);
$this->hookRunner->onUserGetRights( $user, $this->usersRights[ $rightsCacheKey ] );
// Deny any rights denied by the user's session, unless this
// endpoint has no sessions.
if ( !defined( 'MW_NO_SESSION' ) ) {
// FIXME: $user->getRequest().. need to be replaced with something else
$allowedRights = $user->getRequest()->getSession()->getAllowedUserRights();
if ( $allowedRights !== null ) {
$this->usersRights[ $rightsCacheKey ] = array_intersect(
$this->usersRights[ $rightsCacheKey ],
$allowedRights
);
}
}
$this->hookRunner->onUserGetRightsRemove(
$user, $this->usersRights[ $rightsCacheKey ] );
// Force reindexation of rights when a hook has unset one of them
$this->usersRights[ $rightsCacheKey ] = array_values(
array_unique( $this->usersRights[ $rightsCacheKey ] )
);
if (
$user->isLoggedIn() &&
$this->options->get( 'BlockDisablesLogin' ) &&
$user->getBlock()
) {
$anon = new User;
$this->usersRights[ $rightsCacheKey ] = array_intersect(
$this->usersRights[ $rightsCacheKey ],
$this->getUserPermissions( $anon )
);
}
}
$rights = $this->usersRights[ $rightsCacheKey ];
foreach ( $this->temporaryUserRights[ $user->getId() ] ?? [] as $overrides ) {
$rights = array_values( array_unique( array_merge( $rights, $overrides ) ) );
}
return $rights;
}
/**
* Clears users permissions cache, if specific user is provided it tries to clear
* permissions cache only for provided user.
*
* @since 1.34
*
* @param UserIdentity|null $user
*/
public function invalidateUsersRightsCache( $user = null ) {
if ( $user !== null ) {
$rightsCacheKey = $this->getRightsCacheKey( $user );
if ( isset( $this->usersRights[ $rightsCacheKey ] ) ) {
unset( $this->usersRights[ $rightsCacheKey ] );
}
} else {
$this->usersRights = null;
}
}
/**
* Gets a unique key for user rights cache.
* @param UserIdentity $user
* @return string
*/
private function getRightsCacheKey( UserIdentity $user ) {
return $user->isRegistered() ? "u:{$user->getId()}" : "anon:{$user->getName()}";
}
/**
* Check, if the given group has the given permission
*
* If you're wanting to check whether all users have a permission, use
* PermissionManager::isEveryoneAllowed() instead. That properly checks if it's revoked
* from anyone.
*
* @since 1.34
*
* @param string $group Group to check
* @param string $role Role to check
*
* @return bool
*/
public function groupHasPermission( $group, $role ) {
$groupPermissions = $this->options->get( 'GroupPermissions' );
$revokePermissions = $this->options->get( 'RevokePermissions' );
return isset( $groupPermissions[$group][$role] ) && $groupPermissions[$group][$role] &&
!( isset( $revokePermissions[$group][$role] ) && $revokePermissions[$group][$role] );
}
/**
* Get the permissions associated with a given list of groups
*
* @since 1.34
*
* @param array $groups Array of Strings List of internal group names
* @return array Array of Strings List of permission key names for given groups combined
*/
public function getGroupPermissions( $groups ) {
$rights = [];
// grant every granted permission first
foreach ( $groups as $group ) {
if ( isset( $this->options->get( 'GroupPermissions' )[$group] ) ) {
$rights = array_merge( $rights,
// array_filter removes empty items
array_keys( array_filter( $this->options->get( 'GroupPermissions' )[$group] ) ) );
}
}
// now revoke the revoked permissions
foreach ( $groups as $group ) {
if ( isset( $this->options->get( 'RevokePermissions' )[$group] ) ) {
$rights = array_diff( $rights,
array_keys( array_filter( $this->options->get( 'RevokePermissions' )[$group] ) ) );
}
}
return array_unique( $rights );
}
/**
* Get all the groups who have a given permission
*
* @since 1.34
*
* @param string $role Role to check
* @return array Array of Strings List of internal group names with the given permission
*/
public function getGroupsWithPermission( $role ) {
$allowedGroups = [];
foreach ( array_keys( $this->options->get( 'GroupPermissions' ) ) as $group ) {
if ( $this->groupHasPermission( $group, $role ) ) {
$allowedGroups[] = $group;
}
}
return $allowedGroups;
}
/**
* Check if all users may be assumed to have the given permission
*
* We generally assume so if the right is granted to '*' and isn't revoked
* on any group. It doesn't attempt to take grants or other extension
* limitations on rights into account in the general case, though, as that
* would require it to always return false and defeat the purpose.
* Specifically, session-based rights restrictions (such as OAuth or bot
* passwords) are applied based on the current session.
*
* @param string $right Right to check
*
* @return bool
* @since 1.34
*/
public function isEveryoneAllowed( $right ) {
// Use the cached results, except in unit tests which rely on
// being able change the permission mid-request
if ( isset( $this->cachedRights[$right] ) ) {
return $this->cachedRights[$right];
}
if ( !isset( $this->options->get( 'GroupPermissions' )['*'][$right] )
|| !$this->options->get( 'GroupPermissions' )['*'][$right] ) {
$this->cachedRights[$right] = false;
return false;
}
// If it's revoked anywhere, then everyone doesn't have it
foreach ( $this->options->get( 'RevokePermissions' ) as $rights ) {
if ( isset( $rights[$right] ) && $rights[$right] ) {
$this->cachedRights[$right] = false;
return false;
}
}
// Remove any rights that aren't allowed to the global-session user,
// unless there are no sessions for this endpoint.
if ( !defined( 'MW_NO_SESSION' ) ) {
// XXX: think what could be done with the below
$allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
$this->cachedRights[$right] = false;
return false;
}
}
// Allow extensions to say false
if ( !$this->hookRunner->onUserIsEveryoneAllowed( $right ) ) {
$this->cachedRights[$right] = false;
return false;
}
$this->cachedRights[$right] = true;
return true;
}
/**
* Get a list of all available permissions.
*
* @since 1.34
*
* @return string[] Array of permission names
*/
public function getAllPermissions() {
if ( $this->allRights === null ) {
if ( count( $this->options->get( 'AvailableRights' ) ) ) {
$this->allRights = array_unique( array_merge(
$this->coreRights,
$this->options->get( 'AvailableRights' )
) );
} else {
$this->allRights = $this->coreRights;
}
$this->hookRunner->onUserGetAllRights( $this->allRights );
}
return $this->allRights;
}
/**
* Determines if $user is unable to edit pages in namespace because it has been protected.
* @param int $index
* @param UserIdentity $user
* @return bool
*/
private function isNamespaceProtected( $index, UserIdentity $user ) {
$namespaceProtection = $this->options->get( 'NamespaceProtection' );
if ( isset( $namespaceProtection[$index] ) ) {
return !$this->userHasAllRights( $user, ...(array)$namespaceProtection[$index] );
}
return false;
}
/**
* Determine which restriction levels it makes sense to use in a namespace,
* optionally filtered by a user's rights.
*
* @param int $index Index to check
* @param UserIdentity|null $user User to check
* @return array
*/
public function getNamespaceRestrictionLevels( $index, UserIdentity $user = null ) {
if ( !isset( $this->options->get( 'NamespaceProtection' )[$index] ) ) {
// All levels are valid if there's no namespace restriction.
// But still filter by user, if necessary
$levels = $this->options->get( 'RestrictionLevels' );
if ( $user ) {
$levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
$right = $level;
if ( $right == 'sysop' ) {
$right = 'editprotected'; // BC
}
if ( $right == 'autoconfirmed' ) {
$right = 'editsemiprotected'; // BC
}
return $this->userHasRight( $user, $right );
} ) );
}
return $levels;
}
// $wgNamespaceProtection can require one or more rights to edit the namespace, which
// may be satisfied by membership in multiple groups each giving a subset of those rights.
// A restriction level is redundant if, for any one of the namespace rights, all groups
// giving that right also give the restriction level's right. Or, conversely, a
// restriction level is not redundant if, for every namespace right, there's at least one
// group giving that right without the restriction level's right.
//
// First, for each right, get a list of groups with that right.
$namespaceRightGroups = [];
foreach ( (array)$this->options->get( 'NamespaceProtection' )[$index] as $right ) {
if ( $right == 'sysop' ) {
$right = 'editprotected'; // BC
}
if ( $right == 'autoconfirmed' ) {
$right = 'editsemiprotected'; // BC
}
if ( $right != '' ) {
$namespaceRightGroups[$right] = $this->getGroupsWithPermission( $right );
}
}
// Now, go through the protection levels one by one.
$usableLevels = [ '' ];
foreach ( $this->options->get( 'RestrictionLevels' ) as $level ) {
$right = $level;
if ( $right == 'sysop' ) {
$right = 'editprotected'; // BC
}
if ( $right == 'autoconfirmed' ) {
$right = 'editsemiprotected'; // BC
}
if ( $right != '' &&
!isset( $namespaceRightGroups[$right] ) &&
( !$user || $this->userHasRight( $user, $right ) )
) {
// Do any of the namespace rights imply the restriction right? (see explanation above)
foreach ( $namespaceRightGroups as $groups ) {
if ( !array_diff( $groups, $this->getGroupsWithPermission( $right ) ) ) {
// Yes, this one does.
continue 2;
}
}
// No, keep the restriction level
$usableLevels[] = $level;
}
}
return $usableLevels;
}
/**
* Check if user is allowed to edit sitewide pages that contain raw HTML.
* Pages listed in $wgRawHtmlMessages allow raw HTML which can be used to deploy CSS or JS
* code to all users so both rights are required to edit them.
*
* @param UserIdentity $user
* @return bool True if user has both rights
*/
private function userCanEditRawHtmlPage( UserIdentity $user ) {
return $this->userHasAllRights( $user, 'editsitecss', 'editsitejs' );
}
/**
* Add temporary user rights, only valid for the current scope.
* This is meant for making it possible to programatically trigger certain actions that
* the user wouldn't be able to trigger themselves; e.g. allow users without the bot right
* to make bot-flagged actions through certain special pages.
* Returns a "scope guard" variable; whenever that variable goes out of scope or is consumed
* via ScopedCallback::consume(), the temporary rights are revoked.
*
* @since 1.34
*
* @param UserIdentity $user
* @param string|string[] $rights
* @return ScopedCallback
*/
public function addTemporaryUserRights( UserIdentity $user, $rights ) {
$userId = $user->getId();
$nextKey = count( $this->temporaryUserRights[$userId] ?? [] );
$this->temporaryUserRights[$userId][$nextKey] = (array)$rights;
return new ScopedCallback( function () use ( $userId, $nextKey ) {
unset( $this->temporaryUserRights[$userId][$nextKey] );
} );
}
/**
* Overrides user permissions cache
*
* @since 1.34
*
* @param User $user
* @param string[]|string $rights
*
* @throws Exception
*/
public function overrideUserRightsForTesting( $user, $rights = [] ) {
if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
throw new Exception( __METHOD__ . ' can not be called outside of tests' );
}
$this->usersRights[ $this->getRightsCacheKey( $user ) ] =
is_array( $rights ) ? $rights : [ $rights ];
}
}
|